I want to be able to store the output of a command I run (say top
) on a remote host, from within a Python script using SSH, into a file.
I know how to use SSH( I am currently using Paramiko to connect to the remote device). I need to run the command, and then store the output in a text file.
What have you tried something?
Depend on your command you can do something like this:
ssh user@machine command > log
The log will be saved to your machine. A real example:
ssh root@192.168.x.x ls > log
If your command does not support outputs to stdout, run it like this:
ssh root@192.168.x.x "command -o output; cat output" > log
With python, you can use subprocess and do the respective command, something like:
import subprocess
def yourfunction():
subprocess.call("ssh user@machine command > log",shell=False)
yourfunction()
If you use paramiko 's exec_command method to execute the command, you could do something like this:
stdin, stdout, stderr = your_ssh_client_object.exec_command("top")
with open("out.txt", "w") as f:
f.writelines(stdout.readlines())
If you care about error output too, you need to append it to the same file or store it in a separate one.
( NOTE : The above code is neither tested nor working on it's own, since the OP didn't provide a minimal, workable example himself.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.