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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1233655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 17:35:21  来源:igfitidea点击:

What is the simplest way to SSH using Python?

pythonlinuxunixssh

提问by Christopher Tokar

How can I simply SSH to a remote server from a local Python (3.0) script, supply a login/password, execute a command and print the output to the Python console?

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

I would rather not use any large external library or install anything on the remote server.

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

采纳答案by ThomasH

I haven't tried it, but this pysftpmodule might help, which in turn uses paramiko. I believe everything is client-side.

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

The interesting command is probably .execute()which executes an arbitrary command on the remote machine. (The module also features .get()and .putmethods which allude more to its FTP character).

有趣的命令可能是.execute()在远程机器上执行任意命令。(该模块还具有更多暗示其 FTP 特性的功能.get().put方法)。

UPDATE:

更新:

I've re-written the answer after the blog post I originally linked to is not available anymore. Some of the comments that refer to the old version of this answer will now look weird.

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

回答by Cascabel

Your definition of "simplest" is important here - simple code means using a module (though "large external library" is an exaggeration).

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

I believe the most up-to-date (actively developed) module is paramiko. It comes with demo scripts in the download, and has detailed online API documentation. You could also try PxSSH, which is contained in pexpect. There's a short sample along with the documentation at the first link.

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

Again with respect to simplicity, note that good error-detection is always going to make your code look more complex, but you should be able to reuse a lot of code from the sample scripts then forget about it.

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

回答by hughdbrown

You can code it yourself using Paramiko, as suggested above. Alternatively, you can look into Fabric, a python application for doing all the things you asked about:

如上所述,您可以使用 Paramiko 自己编写代码。或者,您可以查看 Fabric,这是一个 Python 应用程序,可以完成您询问的所有事情:

Fabric is a Python library and command-line tool designed to streamline deploying applications or performing system administration tasks via the SSH protocol. It provides tools for running arbitrary shell commands (either as a normal login user, or via sudo), uploading and downloading files, and so forth.

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

I think this fits your needs. It is also not a large library and requires no server installation, although it does have dependencies on paramiko and pycrypt that require installation on the client.

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

The app used to be here. It can now be found here.

该应用程序曾经在这里。现在可以在这里找到它。

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

There are several good articles on it, though you should be careful because it has changed in the last six months:

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

Deploying Django with Fabric

使用 Fabric 部署 Django

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

现代 Python 黑客的工具:Virtualenv、Fabric 和 Pip

Simple & Easy Deployment with Fabric and Virtualenv

使用 Fabric 和 Virtualenv 进行简单轻松的部署



Later: Fabric no longer requires paramiko to install:

后来: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...

This is mostly cosmetic, however: ssh is a fork of paramiko, the maintainer for both libraries is the same (Jeff Forcier, also the author of Fabric), and the maintainer has plans to reunite paramiko and ssh under the name paramiko. (This correction via pbanka.)

然而,这主要是装饰性的:ssh 是 paramiko 的一个分支,两个库的维护者是相同的(Jeff Forcier,也是 Fabric 的作者),并且维护者计划以 paramiko 的名义重新统一 paramiko 和 ssh。(此更正通过pbanka。)

回答by Neil

If you want to avoid any extra modules, you can use the subprocess module to run

如果你想避免任何额外的模块,你可以使用 subprocess 模块来运行

ssh [host] [command]

and capture the output.

并捕获输出。

Try something like:

尝试类似:

process = subprocess.Popen("ssh example.com ls", shell=True,
    stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output,stderr = process.communicate()
status = process.poll()
print output

To deal with usernames and passwords, you can use subprocess to interact with the ssh process, or you could install a public key on the server to avoid the password prompt.

处理用户名和密码,可以使用子进程与 ssh 进程交互,也可以在服务器上安装公钥来避免密码提示。

回答by juanjux

Like hughdbrown, I like Fabric. Please notice that while it implement its own declarative scripting (for making deploys and the such) it can also be imported as a Python module and used on your programs without having to write a Fabric script.

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

Fabric has a new maintainer and is in the process of being rewriten; that means that most tutorials you'll (currently) find on the web will not work with the current version. Also, Google still shows the old Fabric page as the first result.

Fabric 有一个新的维护者,正在被重写;这意味着您(当前)在网络上找到的大多数教程不适用于当前版本。此外,谷歌仍然将旧的 Fabric 页面显示为第一个结果。

For up to date documentation you can check: http://docs.fabfile.org

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

回答by Sebastian Noack

I have written Python bindings for libssh2. Libssh2 is a client-side library implementing the SSH2 protocol.

我已经为 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)

回答by Michael Williamson

I found paramiko to be a bit too low-level, and Fabric not especially well-suited to being used as a library, so I put together my own library called spurthat uses paramiko to implement a slightly nicer interface:

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

You can also choose to print the output of the program as it's running, which is useful if you want to see the output of long-running commands before it exits:

您还可以选择在程序运行时打印输出,如果您想在退出之前查看长时间运行的命令的输出,这将非常有用:

result = shell.run(["echo", "-n", "hello"], stdout=sys.stdout)

回答by Naveen

This worked for me

这对我有用

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

回答by oceanuz

For benefit of those who reach here googling for python ssh sample. The original question and answer are almost a decode old now. It seems that the paramiko has gain a bit of functionalities (Ok. I'll admit - pure guessing here - I'm new to Python) and you can create ssh client directly with paramiko.

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

This code was adapted from demo of https://github.com/paramiko/paramikoIt works for me.

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

回答by marko.ristin

Have a look at spurplus, a wrapper around spurand paramikothat we developed to manage remote machines and perform file operations.

看一下spurplus,这是我们开发的用于管理远程机器和执行文件操作的spurparamiko的包装器。

Spurplus provides a check_output()function out-of-the-box:

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)