2015-02-09 81 views

回答

24

當然,有幾種方法可以做到這一點!

假設您的raspberry.lan主機上有Raspberry Pi,並且您的用戶名是irfan

子流程

這是運行命令的默認Python庫。
您可以使其運行ssh並在遠程服務器上執行任何您需要的操作。

scrat has it covered in his answer。如果你不想使用任何第三方庫,你絕對應該這樣做。

您還可以使用pexpect自動輸入密碼/密碼。

的paramiko

paramiko是一個第三方庫,增加了SSH協議支持,所以它可以工作像一個SSH客戶端。

的示例代碼,將連接到服務器,執行和搶ls -l命令的結果看起來就像是:

import paramiko 

client = paramiko.SSHClient() 
client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
client.connect('raspberry.lan', username='irfan', password='my_strong_password') 

stdin, stdout, stderr = client.exec_command('ls -l') 

for line in stdout: 
    print line.strip('\n') 

client.close() 

面料

您也可以使用fabric實現它。
Fabric是一種在遠程服務器上執行各種命令的部署工具。

它經常被用來在遠程服務器上運行的東西,所以你可以很容易地用一個命令把你的最新版本的Web應用程序,重新啓動web服務器和諸如此類的東西。實際上,您可以在多臺服務器上運行相同的命令,這非常棒!

儘管它是作爲部署和遠程管理工具製作的,但您仍然可以使用它來執行基本命令。

# fabfile.py 
from fabric.api import * 

def list_files(): 
    with cd('/'): # change the directory to '/' 
     result = run('ls -l') # run a 'ls -l' command 
     # you can do something with the result here, 
     # though it will still be displayed in fabric itself. 

這就像在遠程服務器上鍵入,cd /ls -l,所以你會得到你的根文件夾的目錄列表。

然後在shell中運行:

fab list_files 

它會提示輸入服務器地址:

No hosts found. Please specify (single) host string for connection: [email protected] 

快速注意:您還可以分配用戶名和主機在fab指令中:

fab list_files -U irfan -H raspberry.lan 

或者您可以將一個主機放入您的fabfile中的env.hosts變量。 Here's how to do it


然後你會被提示輸入SSH密碼:

[[email protected]] run: ls -l 
[[email protected]] Login password for 'irfan': 

然後在命令將成功運行。從here

[[email protected]] out: total 84 
[[email protected]] out: drwxr-xr-x 2 root root 4096 Feb 9 05:54 bin 
[[email protected]] out: drwxr-xr-x 3 root root 4096 Dec 19 08:19 boot 
... 
+0

如何安裝它 – 2015-02-09 14:29:38

+2

@ IrfanGhaffar7您可以使用'pip'或'easy_install'安裝第三方Python庫。所以它會是'pip安裝結構'。檢查文檔(我鏈接到面料和paramiko文檔),它有快速入門和教程! – 2015-02-09 14:31:20

+0

我的遠程機器主機名是'Pi @ 192.168.2.34',密碼是'raspberrypi'。當它提示你輸入一個主機名時,我怎麼在織物 – Fahadkalis 2015-02-09 14:40:15

6

簡單的例子:

import subprocess 
import sys 

HOST="www.example.org" 
# Ports are handled in ~/.ssh/config since we use OpenSSH 
COMMAND="uname -a" 

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 
else: 
    print result 

它做你想要什麼:連接通過SSH,執行命令,返回的輸出。沒有第三方庫需要。

+0

當我使用這個命令=「ls -l」,其結果是在一行中,意味着不可讀,但它工作 – 2015-02-09 15:57:59

+1

@ IrfanGhaffar7這是因爲'結果'是一個列表,而不是串。你可以做'print''.join(result)'而不是使它看起來可讀。 – 2015-02-09 16:09:50

+0

謝謝....現在確定 – 2015-02-09 16:35:30