使用Python进行SSH的最简单方法是什么?

时间:2009-08-05 14:34:25

标签: python linux unix ssh

如何从本地Python(3.0)脚本简单地SSH到远程服务器,提供登录/密码,执行命令并将输出打印到Python控制台?

我不想使用任何大型外部库或在远程服务器上安装任何东西。

11 个答案:

答案 0 :(得分:60)

如上所述,您可以使用Paramiko自行编码。或者,您可以查看Fabric,这是一个python应用程序,用于执行您询问的所有事情:

  

Fabric是一个Python库和   命令行工具旨在   简化部署应用程序或   执行系统管理任务   通过SSH协议。它提供   用于运行任意shell的工具   命令(作为普通登录   用户,或通过sudo),上传和   下载文件,等等。

我认为这符合您的需求。它也不是一个大型库,不需要服务器安装,但它确实依赖于需要在客户端安装的paramiko和pycrypt。

该应用曾是here。现在可以找到here

* The official, canonical repository is git.fabfile.org
* The official Github mirror is GitHub/bitprophet/fabric

有几篇好文章,虽然你应该小心,因为它在过去的六个月里发生了变化:

Deploying Django with Fabric

Tools of the Modern Python Hacker: Virtualenv, Fabric and Pip

Simple & Easy Deployment with Fabric and 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的作者)和the maintainer has plans to reunite paramiko and ssh under the name paramiko。 (通过pbanka进行此更正。)

答案 1 :(得分:39)

我还没有尝试过,但是这个pysftp模块可能有所帮助,而后者则使用了paramiko。我相信一切都是客户端的。

有趣的命令可能是.execute(),它在远程机器上执行任意命令。 (该模块还具有.get().put方法,其中包含更多其FTP字符。)

更新:

在我最初链接的博客文章不再可用之后,我重写了答案。现在,一些引用此答案的旧版本的评论看起来很奇怪。

答案 2 :(得分:24)

如果您想避免任何额外的模块,可以使用子进程模块运行

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进程交互,也可以在服务器上安装公钥以避免密码提示。

答案 3 :(得分:17)

我写过Python bindings for libssh2。 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)

答案 4 :(得分:8)

你对“最简单”的定义在这里很重要 - 简单的代码意味着使用模块(虽然“大型外部库”是夸大其词)。

我相信最新(积极开发)的模块是paramiko。它下载了演示脚本,并提供详细的在线API文档。您还可以尝试PxSSH中包含的pexpect。在第一个链接上有一个简短的示例以及文档。

再次说明简单性,请注意良好的错误检测总是会使您的代码看起来更复杂,但您应该能够重用示例脚本中的大量代码,然后忘记它。

答案 5 :(得分:6)

像hughdbrown一样,我喜欢Fabric。请注意,虽然它实现了自己的声明性脚本(用于制作部署等),但它也可以作为Python模块导入并在程序中使用,而无需编写Fabric脚本。

Fabric有一个新的维护者,正在重写;这意味着您(目前)在网上找到的大多数教程都无法使用当前版本。此外,Google仍然会将旧的Fabric页面显示为第一个结果。

有关最新文档,您可以查看:http://docs.fabfile.org

答案 6 :(得分:6)

我发现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)

答案 7 :(得分:3)

为了那些到达这里搜寻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()

此代码改编自https://github.com/paramiko/paramiko的演示 它对我有用。

答案 8 :(得分:1)

这对我有用

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

答案 9 :(得分:0)

看看spurplus,它是我们为管理远程计算机和执行文件操作而开发的spurparamiko的包装。

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)

答案 10 :(得分:0)

please refer to paramiko.org, its very useful while doing ssh using python.

导入paramiko

导入时间

ssh = paramiko.SSHClient()#SSHClient()是paramiko对象

'''''以下几行自动将服务器密钥添加到know_hosts文件中。请使用以下任意一项'''

ssh.load_system_host_keys()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

尝试:

我们实际上正在连接到服务器。

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')

我们正在从输出中读取行。

output = stdout.readlines() 

print(output)

Below all are the Exception handled by paramiko while ssh. Refer to paramiko.org for more information about exception.

除了(BadHostKeyException,AuthenticationException,
        SSHException,socket.error),例如e

print(e)
相关问题