与 Python 3.0 的 SSH 连接 [英] SSH Connection with Python 3.0
本文介绍了与 Python 3.0 的 SSH 连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 Python 3.0 中建立 SSH 连接?我想在设置了无密码 SSH 的远程计算机上保存文件.
How can I make an SSH connection in Python 3.0? I want to save a file on a remote computer where I have password-less SSH set up.
推荐答案
我建议将 ssh 作为子进程调用.它可靠且便携.
I recommend calling ssh as a subprocess. It's reliable and portable.
import subprocess
proc = subprocess.Popen(['ssh', 'user@host', 'cat > %s' % filename],
stdin=subprocess.PIPE)
proc.communicate(file_contents)
if proc.retcode != 0:
...
您必须担心引用目标文件名.如果您想要更大的灵活性,您甚至可以这样做:
You'd have to worry about quoting the destination filename. If you want more flexibility, you could even do this:
import subprocess
import tarfile
import io
tardata = io.BytesIO()
tar = tarfile.open(mode='w:gz', fileobj=tardata)
... put stuff in tar ...
proc = subprocess.Popen(['ssh', 'user@host', 'tar xz'],
stdin=subprocess.PIPE)
proc.communicate(tardata.getvalue())
if proc.retcode != 0:
...
这篇关于与 Python 3.0 的 SSH 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文