簡體   English   中英

使用 Python 進行 SSH 的最簡單方法是什么?

[英]What is the simplest way to SSH using Python?

如何從本地 Python (3.0) 腳本簡單地通過 SSH 連接到遠程服務器、提供登錄名/密碼、執行命令並將輸出打印到 Python 控制台?

我寧願不使用任何大型外部庫或在遠程服務器上安裝任何東西。

如上所述,您可以使用 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 的名稱重新組合 paramiko 和 ssh (通過pbanka進行此更正。)

我還沒有嘗試過,但是這個pysftp模塊可能會有所幫助,它反過來使用 paramiko。 我相信一切都是客戶端。

有趣的命令可能是.execute() ,它在遠程機器上執行任意命令。 (該模塊還具有.get().put方法,這些方法更多地暗示了它的 FTP 字符)。

更新:

在我最初鏈接到的博客文章不再可用后,我重新編寫了答案。 一些引用此答案舊版本的評論現在看起來很奇怪。

如果你想避免任何額外的模塊,你可以使用 subprocess 模塊來運行

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 進程交互,也可以在服務器上安裝一個公鑰來避免密碼提示。

我已經 為 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)

您對“最簡單”的定義在這里很重要 - 簡單的代碼意味着使用模塊(盡管“大型外部庫”有點誇張)。

我相信最新(積極開發)的模塊是paramiko 它在下載中附帶演示腳本,並具有詳細的在線 API 文檔。 您也可以嘗試PxSSH ,它包含在pexpect中。 在第一個鏈接中有一個簡短的示例以及文檔。

再次關於簡單性,請注意,良好的錯誤檢測總是會讓您的代碼看起來更復雜,但您應該能夠重用示例腳本中的大量代碼,然后忘記它。

喜歡hughdbrown,我喜歡Fabric。 請注意,雖然它實現了自己的聲明性腳本(用於進行部署等),但它也可以作為 Python 模塊導入並在您的程序中使用,而無需編寫 Fabric 腳本。

Fabric 有一個新的維護者,正在重寫; 這意味着您(當前)在網絡上找到的大多數教程都不適用於當前版本。 此外,Google 仍將舊的 Fabric 頁面顯示為第一個結果。

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

我發現 paramiko 有點太低級了,Fabric 也不是特別適合用作庫,所以我將我自己的庫放在一起,稱為spark ,它使用 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)

為了那些到達這里谷歌搜索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的演示它適用於我。

這對我有用

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

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)

看一下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)
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)

`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM