使用 Python 进行 SSH 的最简单方法是什么?
- 2025-03-06 08:52:00
- admin 原创
- 61
问题描述:
我如何才能简单地从本地 Python(3.0)脚本通过 SSH 连接到远程服务器,提供登录名/密码,执行命令并将输出打印到 Python 控制台?
我宁愿不使用任何大型外部库或在远程服务器上安装任何东西。
解决方案 1:
您可以使用 Paramiko 自行编写代码,如上所述。或者,您可以研究 Fabric,这是一个 Python 应用程序,可以完成您询问的所有事情:
Fabric 是一个 Python 库和命令行工具,旨在简化通过 SSH 协议部署应用程序或执行系统管理任务的过程。它提供了用于运行任意 shell 命令(以普通登录用户或通过 sudo 运行)、上传和下载文件等的工具。
我认为这符合您的需求。它也不是一个大型库,不需要安装服务器,尽管它确实依赖于需要在客户端上安装的 paramiko 和 pycrypt。
该应用程序以前位于此处。现在可以在此处找到。
* The official, canonical repository is git.fabfile.org
* The official Github mirror is GitHub/bitprophet/fabric
关于它有几篇很好的文章,但你应该小心,因为它在过去六个月中发生了变化:
使用 Fabric 部署 Django
现代 Python 黑客的工具:Virtualenv、Fabric 和 Pip
使用 Fabric 和 Virtualenv 进行简单轻松的部署
稍后: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 的一个分支,两个库的维护者是相同的(Jeff Forcier,也是 Fabric 的作者),并且维护者计划将 paramiko 和 ssh 重新统一在 paramiko 的名下。 (此更正来自pbanka。)
解决方案 2:
我还没有尝试过,但这个pysftp模块可能会有帮助,它反过来使用 paramiko。我相信一切都是客户端的。
有趣的命令可能是.execute()
在远程机器上执行任意命令。(该模块还具有更多暗示其 FTP 特性的功能.get()
和方法)。.put
更新:
由于我最初链接的博客文章不再可用,我重写了答案。一些引用此答案旧版本的评论现在看起来很奇怪。
解决方案 3:
如果你想避免任何额外的模块,你可以使用子进程模块来运行
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
为了处理用户名和密码,您可以使用子进程与 ssh 进程交互,或者您可以在服务器上安装公钥以避免密码提示。
解决方案 4:
我已经为 libssh2 编写了 Python 绑定。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)
解决方案 5:
您对“最简单”的定义在这里很重要 - 简单的代码意味着使用模块(尽管“大型外部库”有些夸张)。
我认为最新的(积极开发的)模块是paramiko。它在下载中附带了演示脚本,并具有详细的在线 API 文档。您还可以尝试PxSSH,它包含在pexpect中。第一个链接处有一个简短的示例以及文档。
再次关于简单性,请注意,良好的错误检测总是会使您的代码看起来更复杂,但您应该能够重用示例脚本中的大量代码,然后忘记它。
解决方案 6:
和 hughdbrown 一样,我喜欢 Fabric。请注意,虽然它实现了自己的声明性脚本(用于进行部署等),但它也可以作为 Python 模块导入并在您的程序中使用,而无需编写 Fabric 脚本。
Fabric 有了新的维护者,并且正在重写;这意味着您(目前)在网上找到的大多数教程都不适用于当前版本。此外,Google 仍将旧版 Fabric 页面显示为第一个结果。
如需最新文档,您可以查看:http://docs.fabfile.org
解决方案 7:
我发现 paramiko 有点太低级了,而 Fabric 并不特别适合用作库,因此我组建了自己的库spur,它使用 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)
解决方案 8:
对于那些通过谷歌搜索 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('
'))
client.close()
此代码改编自https://github.com/paramiko/paramiko的演示
,对我有用。
解决方案 9:
这对我有用
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
解决方案 10:
please refer to paramiko.org, its very useful while doing ssh using python.
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)
解决方案 11:
看一下spurplus ,这是我们开发的用于管理远程机器和执行文件操作的spur和paramiko的包装器。
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)
解决方案 12:
host = "test.rebex.net"
port = 22
username = "demo"
password = "password"
command = "ls"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port, username, password)
stdin, stdout, stderr = ssh.exec_command(command)
lines = stdout.readlines()
print(lines)
`
扫码咨询,免费领取项目管理大礼包!