问题描述
我要编写第一个代码来处理python上的ssh命令,我确实搜索了stackoverflow,可以看到有多个python库可用于处理通过ssh传递的命令,例如 paramiko , pexpect ,也许还有一些.
I'm going to write first code for handling ssh commands on python and I did search over the stackoverflow and can see that there are several python libraries that can be used for handling commands passed through ssh, like paramiko, pexpect and perhaps some others.
特别是,我将需要从远程服务器读取文件的内容,通过ssh/scp复制文件,在远程服务器上启动脚本后从远程服务器获取输出.
Particularly, I will need to read content of the files from the remote server, copy files through ssh/scp, get output from remote server after starting the script on remote server.
也许一些专家会建议哪种图书馆更好,并说明优缺点?
Perhaps some experts could advice what library is better and specify advantages or disadvantages?
推荐答案
库,包装器:
#!/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) utilizes the 2) and provides some higher level functions. If the latter suit your requirements, I'd suggest trying out 1)
更新:1)现在不见了(2017-09-12)
Update: 1) is gone now (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()
注意:上面的代码示例仅用于印象.该代码未经测试.
Note: The code examples above are provided just for getting an impression; the code is not tested.
这篇关于用于ssh处理的python库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!