SSH Connection with Python 3.0

2019-01-12 04:03发布

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.

标签: python file ssh
6条回答
狗以群分
2楼-- · 2019-01-12 04:27

I have written Python bindings for libssh2, that run on Python 2.4, 2.5, 2.6, 2.7 and 3.

查看更多
Bombasti
3楼-- · 2019-01-12 04:28

It might take a little work because "twisted:conch" does not appear to have a 3.0 variant.

查看更多
你好瞎i
4楼-- · 2019-01-12 04:30

You want all of the ssh-functionality implemented as a python library? Have a look at paramiko, although I think it's not ported to Python 3.0 (yet?).

If you can use an existing ssh installation you can use the subprocess way Dietrich described, or (another way) you could also use pexpect (website here).

查看更多
Summer. ? 凉城
5楼-- · 2019-01-12 04:32

First:

Two steps to login via ssh without password

in your terminal

[macm@macm ~]$  ssh-keygen
[macm@macm ~]$  ssh-copy-id -i $HOME/.ssh/id_rsa.pub root@192.168.1.XX <== change

Now with 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)
查看更多
做自己的国王
6楼-- · 2019-01-12 04:33

libssh2 works great for Python 3.x.
See this Stack Overflow article How to send a file using scp using python 3.2?

查看更多
老娘就宠你
7楼-- · 2019-01-12 04:46

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:
    ...
查看更多
登录 后发表回答