2013-05-29 111 views
1

我對Paramiko的工作原理相當陌生,但我的主要目標是能夠使用Python通過SSH運行自動命令。Python:Paramiko在嘗試通過SSH執行命令時掛起

我有以下代碼,我試圖運行一個簡單的ls命令開始,但由於某種奇怪的原因代碼似乎卡住,沒有輸出或錯誤消息產生。

import sys 
import paramiko as pm 
sys.stderr = sys.__stderr__ 
import os 

class AllowAllKeys(pm.MissingHostKeyPolicy): 
    def missing_host_key(self, client, hostname, key): 
     return 

HOST = '192.168.31.1' 
USER = 'admin' 
PASSWORD = 'admin' 

client = pm.SSHClient() 
client.load_system_host_keys() 
client.set_missing_host_key_policy(pm.AutoAddPolicy()) 

client.connect(HOST, username=USER, password=PASSWORD) 

channel = client.invoke_shell() 
stdin = channel.makefile('wb') 
stdout = channel.makefile('rb') 

stdin.write(''' 
ls 
exit 
''') 
print stdout.read() 

stdout.close() 
stdin.close() 

任何幫助,將不勝感激:)

+1

確定'stdin'和'stdout'不倒? – Elazar

+0

@ mrpopo,更好的,你可以使用pexpect模塊,而不是paramiko – abhi

+1

我想最初使用pexpect,但我使用的是Windows機器:/ 無法在Windows上導入資源。不用擔心,我只會虛擬一個debian客戶端並學習pexpect。 – mrpopo

回答

2

我嘗試你所要去的同一條路線,並沒有多少運氣無論是。然後我選擇了paramiko Channel類的send()recv()方法。下面是我用什麼:

>>> s = paramiko.SSHClient() 
>>> s.load_system_host_keys() 
>>> s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
>>> s.connect(HOST,USER,PASS) 
>>> c = s.invoke_shell() 
>>> c.send('ls') 
>>> c.recv(1024) 
ls 
bin  etc  usr  home 
proc var  lib  tmp 
-1

@ mrpopo,試試這個代碼,它使用pecpect,

import pexpect 
import pxssh 
import time 
import os 

    def tc(ipaddr,password): 
     try: 
      ss = pexpect.spawn(ipaddr) 
      ss.logfile = sys.stdout 
       print "SSH connecting" 
       print 
     except: 
      print "connection refused" 
      print 
      #sys.exit() 

      try: 
       ss.expect (':') 
       ss.sendline (password +"\n") 
        print "connected" 
        time.sleep(30) 
        ss.expect (">") 
        print "connection established" 
        print 

      except: 
        print "Permission denied, please try again." 
         print 
         sys.exit() 
      try: 
       ss.sendline ('ls\n') 
       ss.expect ('>') 

    tc("ssh [email protected],admin") 
1

import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) target_host = 'x.x.x.x' target_port = 22 target_port = 22 pwd = ':)' un = 'root' ssh.connect(hostname = target_host , username = un, password = pwd) stdin, stdout, stderr = ssh.exec_command('ls;exit')