如何在Python 3.0中建立SSH连接?我想在远程计算机上保存一个文件,在那里我设置了无密码的SSH。
答案 0 :(得分:12)
我建议将ssh作为子进程调用。它可靠,便携。
import subprocess
proc = subprocess.Popen(['ssh', 'user@host', 'cat > %s' % filename],
stdin=subprocess.PIPE)
proc.communicate(file_contents)
if proc.retcode != 0:
...
您必须担心引用目标文件名。如果您想要更多灵活性,您甚至可以这样做:
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:
...
答案 1 :(得分:1)
您希望将所有ssh功能实现为python库吗?看看paramiko,虽然我认为它没有移植到Python 3.0(但是?)。
如果你可以使用现有的ssh安装,你可以使用Dietrich描述的subprocess
方式,或者(另一种方式)你也可以使用pexpect
(website here)。
答案 2 :(得分:1)
首先:
通过ssh无密码登录的两个步骤
在您的终端
[macm@macm ~]$ ssh-keygen
[macm@macm ~]$ ssh-copy-id -i $HOME/.ssh/id_rsa.pub root@192.168.1.XX <== change
现在使用python
from subprocess import PIPE, Popen
cmd = 'uname -a'
stream = Popen(['ssh', 'root@192.168.1.XX', cmd],
stdin=PIPE, stdout=PIPE)
rsp = stream.stdout.read().decode('utf-8')
print(rsp)
答案 3 :(得分:0)
可能需要一些工作,因为“twisted:conch”似乎没有3.0版本。
答案 4 :(得分:0)
我写过Python bindings for libssh2,运行在Python 2.4,2.5,2.6,2.7和 3 上。
答案 5 :(得分:0)
libssh2适用于Python 3.x.
请参阅此Stack Overflow文章
How to send a file using scp using python 3.2?