由于在协议级别上您没有进行任何特殊操作,因此您可能不需要完全使用Python实现协议,而可以使用subprocess
模块运行ssh/scp命令。
import subprocess
subprocess.check_call(['ssh', 'server', 'command'])
subprocess.check_call(['scp', 'server:file', 'file'])
库、封装:
#!/usr/bin/env python
import paramiko
from contextlib import contextmanager
host = '192.168.10.142'
username = 'slacker'
password = 'password'
def create_ssh(host=host, username=username, password=password):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
print "creating connection"
ssh.connect(host, username=username, password=password)
print "connected"
yield ssh
finally:
print "closing connection"
ssh.close()
print "closed"
1) 使用 2) 并提供一些高级功能。如果后者符合您的要求,建议尝试使用 1)。
更新:1) 已经不存在了(2017-09-12)
http://media.commandline.org.uk/code/ssh.txt(示例用法:https://zeth.net/archive/2008/05/29/sftp-python-really-simple-ssh/)
s = ssh.Connection('example.com', 'warrior', password = 'lennalenna')
s.put('/home/warrior/hello.txt', '/home/zombie/textfiles/report.txt')
s.get('/var/log/strange.log', '/home/warrior/serverlog.txt')
s.execute('ls -l')
s.close()
注意: 上面的代码示例仅用于了解;这些代码未经测试。
试试看Twisted Conch。它可以处理你需要的一切。如果你只是想要SCP风格的文件传输,你可以使用Python模块secsh-filexfer。
secsh-filexfer
的链接已失效。 - nmichaels