SSH到远程服务器-并将结果写入本地服务器

时间:2018-08-10 04:16:38

标签: python python-3.x subprocess

因此,我希望能够将我从本地服务器启动的此信息获取到此远程设备,而不是将结果获取到本地屏幕。我想将其写入本地文件。我可以在paramiko中看到示例,但是我在为python3安装它时遇到了问题,因为这是我更喜欢使用的。所以我正在尝试使用子过程。现在的独特之处在于,该远程设备接受的命令很有限,这更像是我必须在设备上运行“ show”命令。因此对SCP没有任何影响。因此我不使用SCP的原因。

这会将它写到我的屏幕上,但这对我没有多大帮助:(

xfer = subprocess.Popen(["ssh", "user@mysystem.com", " show my_secret_file"], stderr=subprocess.PIPE)
errdata = prog.communicate()[1]

这可能吗?

1 个答案:

答案 0 :(得分:0)

假设您的设备实际上会将其输出写入stdout,则只要您在Popen()中请求stdout,它的输出实际上就会在prog.communicate()中返回。

然后您可以使用standard file IO functions将返回的标准输出保存到文件中。

换句话说,这是它的工作方式:

import subprocess

# Call subprocess and save stdout and stderr
prog = subprocess.Popen(["ssh", "user@mysystem.com", " show my_secret_file"],
                        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                      # ^ Add this bit
out, err = prog.communicate()

# Do your error handling here...
# ...

# Now write to file
writefile = open("Put your file name here", "w")
writefile.write(out.decode("utf-8"))
writefile.close()

请注意,以上假设stdout处于文本模式。如果它处于二进制模式,则可能必须进行一些str / bytes转换,或者以其他模式打开文件。