使用Python进行SSH的最简单方法是什么?
如何从本地Python(3.0)脚本SSH到远程服务器,提供登录/密码,执行命令并将输出打印到Python控制台 我不希望使用任何大型外部库或在远程服务器上安装任何东西。您对“最简单”的定义在这里很重要-简单代码意味着使用模块(尽管“大型外部库”有些夸张) 我相信最新的(积极开发的)模块是。下载时附带了演示脚本,并提供了详细的在线API文档。您也可以尝试,它包含在中。在第一个链接中有一个简短的示例和文档使用Python进行SSH的最简单方法是什么?,python,linux,unix,ssh,Python,Linux,Unix,Ssh,如何从本地Python(3.0)脚本SSH到远程服务器,提供登录/密码,执行命令并将输出打印到Python控制台 我不希望使用任何大型外部库或在远程服务器上安装任何东西。您对“最简单”的定义在这里很重要-简单代码意味着使用模块(尽管“大型外部库”有些夸张) 我相信最新的(积极开发的)模块是。下载时附带了演示脚本,并提供了详细的在线API文档。您也可以尝试,它包含在中。在第一个链接中有一个简短的示例和文档 同样关于简单性,请注意,良好的错误检测总是会使代码看起来更复杂,但是您应该能够重用示例脚本中
同样关于简单性,请注意,良好的错误检测总是会使代码看起来更复杂,但是您应该能够重用示例脚本中的大量代码,然后忘记它。我没有尝试过它,但是这个模块可能会有所帮助,它反过来使用paramiko。我相信一切都是客户端的 有趣的命令可能是
.execute()
,它在远程机器上执行任意命令。(该模块还具有.get()
和.put
方法,这些方法更多地暗示了其FTP特性)
更新:
在我最初链接到的博客帖子不再可用后,我重新写下了答案。一些引用此答案旧版本的注释现在看起来很奇怪。如上文所述,您可以使用Paramiko自己编写。或者,您可以研究Fabric,它是一个python应用程序,可以完成您要求的所有事情: Fabric是一个Python库和 命令行工具,用于 优化部署应用程序或 执行系统管理任务 通过SSH协议。它提供 运行任意shell的工具 命令(作为正常登录) 用户,或通过sudo),上传和 下载文件等等 我想这符合你的需要。它也不是一个大型库,不需要安装服务器,尽管它确实依赖于需要在客户机上安装的paramiko和pycrypt 这个应用程序以前是。现在可以找到了 有几篇关于它的好文章,但你应该小心,因为它在过去六个月里发生了变化:
以后:Fabric不再需要paramiko来安装:
$ pip install fabric
Downloading/unpacking fabric
Downloading Fabric-1.4.2.tar.gz (182Kb): 182Kb downloaded
Running setup.py egg_info for package fabric
warning: no previously-included files matching '*' found under directory 'docs/_build'
warning: no files found matching 'fabfile.py'
Downloading/unpacking ssh>=1.7.14 (from fabric)
Downloading ssh-1.7.14.tar.gz (794Kb): 794Kb downloaded
Running setup.py egg_info for package ssh
Downloading/unpacking pycrypto>=2.1,!=2.4 (from ssh>=1.7.14->fabric)
Downloading pycrypto-2.6.tar.gz (443Kb): 443Kb downloaded
Running setup.py egg_info for package pycrypto
Installing collected packages: fabric, ssh, pycrypto
Running setup.py install for fabric
warning: no previously-included files matching '*' found under directory 'docs/_build'
warning: no files found matching 'fabfile.py'
Installing fab script to /home/hbrown/.virtualenvs/fabric-test/bin
Running setup.py install for ssh
Running setup.py install for pycrypto
...
Successfully installed fabric ssh pycrypto
Cleaning up...
不过,这基本上是装饰性的:ssh是paramiko的分支,两个库的维护者是相同的(jeffforcier,也是Fabric的作者),并且。(此更正通过。)如果要避免任何额外的模块,可以使用子流程模块运行
ssh [host] [command]
并捕获输出
尝试以下方法:
process = subprocess.Popen("ssh example.com ls", shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output,stderr = process.communicate()
status = process.poll()
print output
要处理用户名和密码,可以使用subprocess与ssh进程交互,也可以在服务器上安装公钥以避免出现密码提示。像hughdbrown一样,我喜欢Fabric。请注意,虽然它实现了自己的声明性脚本(用于进行部署等),但它也可以作为Python模块导入并在程序中使用,而无需编写结构脚本 Fabric有了一个新的维护者,并且正在被重写;这意味着你(目前)在网上找到的大多数教程都不能与当前版本一起使用。此外,谷歌仍将旧的Fabric页面作为第一个结果显示 有关最新文档,您可以查看:我已经写了。Libssh2是一个实现SSH2协议的客户端库
import socket
import libssh2
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('exmaple.com', 22))
session = libssh2.Session()
session.startup(sock)
session.userauth_password('john', '******')
channel = session.channel()
channel.execute('ls -l')
print channel.read(1024)
我发现paramiko有点太低级了,而且Fabric不太适合用作库,所以我建立了自己的库,名为,它使用paramiko实现了一个稍微好一点的接口:
import spur
shell = spur.SshShell(hostname="localhost", username="bob", password="password1")
result = shell.run(["echo", "-n", "hello"])
print result.output # prints hello
您还可以选择在程序运行时打印其输出,如果您希望在退出之前查看长时间运行的命令的输出,这将非常有用:
result = shell.run(["echo", "-n", "hello"], stdout=sys.stdout)
这对我有用
import subprocess
import sys
HOST="IP"
COMMAND="ifconfig"
def passwordless_ssh(HOST):
ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
error = ssh.stderr.readlines()
print >>sys.stderr, "ERROR: %s" % error
return "error"
else:
return result
对于那些到达这里的人来说,谷歌搜索python ssh示例是有益的。 原来的问题和答案现在几乎是一个古老的解码。 看起来paramiko已经获得了一些功能(好吧,我承认——这里纯粹是猜测——我是Python新手),您可以直接使用paramiko创建ssh客户端
import base64
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.1.1', username='user', password='password')
stdin, stdout, stderr = client.exec_command('cat /proc/meminfo')
for line in stdout:
print('... ' + line.strip('\n'))
client.close()
此代码改编自的演示
它适合我。看一看,它是一个包装器,我们开发用来管理远程机器和执行文件操作
Spurplus提供了一个现成的check_output()
函数:
import spurplus
with spurplus.connect_with_retries(
hostname='some-machine.example.com', username='devop') as shell:
out = shell.check_output(['/path/to/the/command', '--some_argument'])
print(out)
请参考paramiko.org,它在使用python进行ssh时非常有用。
import paramiko
import time
ssh = paramiko.SSHClient() #SSHClient() is the paramiko object</n>
#Below lines adds the server key automatically to know_hosts file.use anyone one of the below
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
#Here we are actually connecting to the server.
ssh.connect('10.106.104.24', port=22, username='admin', password='')
time.sleep(5)
#I have mentioned time because some servers or endpoint prints there own information after
#loggin in e.g. the version, model and uptime information, so its better to give some time
#before executing the command.
#Here we execute the command, stdin for input, stdout for output, stderr for error
stdin, stdout, stderr = ssh.exec_command('xstatus Time')
#Here we are reading the lines from output.
output = stdout.readlines()
print(output)
#Below all are the Exception handled by paramiko while ssh. Refer to paramiko.org for more information about exception.
except (BadHostKeyException, AuthenticationException,
SSHException, socket.error) as e:
print(e)
导入paramiko
导入时间
ssh=paramiko.SSHClient()#SSHClient()是paramiko对象
#以下几行自动添加服务器密钥以了解\u hosts文件。请使用以下任一选项
ssh.load\u system\u host\u keys()
ssh.set_缺少_主机_密钥_策略(paramiko.AutoAddPolicy())
尝试:
#这里我们实际上是在连接服务器。
ssh.connect('10.106.104.24',端口=22,用户名='admin',密码='')
时间。睡眠(5)
#我提到了时间,因为一些服务器或端点会在之后打印自己的信息
#登录版本、型号和正常运行时间等信息,因此最好留出一些时间
#在执行命令之前。
#这里我们执行命令,stdin表示输入,stdout表示输出,stderr表示错误
stdin,stdout,stderr=ssh.exec_命令('xstatus Time')
#这里我们从输出中读取行。
output=stdout.readlines()
打印(输出)
#下面是paramiko在ssh时处理的异常。有关异常的更多信息,请参阅paramiko.org。
除外(BadHostKeyException、AuthenticationException、,
SSHException,socket.error)作为e:
打印(e)
好发现!只要您不关心定制错误响应,这个额外的抽象就非常有用。简单又好用。没有搜索
import paramiko
import time
ssh = paramiko.SSHClient() #SSHClient() is the paramiko object</n>
#Below lines adds the server key automatically to know_hosts file.use anyone one of the below
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
#Here we are actually connecting to the server.
ssh.connect('10.106.104.24', port=22, username='admin', password='')
time.sleep(5)
#I have mentioned time because some servers or endpoint prints there own information after
#loggin in e.g. the version, model and uptime information, so its better to give some time
#before executing the command.
#Here we execute the command, stdin for input, stdout for output, stderr for error
stdin, stdout, stderr = ssh.exec_command('xstatus Time')
#Here we are reading the lines from output.
output = stdout.readlines()
print(output)
#Below all are the Exception handled by paramiko while ssh. Refer to paramiko.org for more information about exception.
except (BadHostKeyException, AuthenticationException,
SSHException, socket.error) as e:
print(e)