2013-01-14 186 views
5

我一直試圖讓這個工作,但不斷得到相同的錯誤。我已經嘗試了主機的fqdn和ip。我試圖通過它憑證和沒有。我查看了錯誤消息中指示的行。谷歌搜索,但想不通這是爲什麼不工作:SSH - 與paramiko問題的Python

import paramiko 
ssh = paramiko.SSHClient() 
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
ssh.connect('host', username='loginname') 
stdin, stdout, stderr = ssh.exec_command("pwd") 
stdout.readlines() 

錯誤:

Traceback (most recent call last): 
    File "audit.py", line 7, in <module> 
    ssh.connect('host', username='loginname') 
    File "/usr/lib/python2.6/site-packages/paramiko/client.py", line 338, in connect 
    self._auth(username, password, pkey, key_filenames, allow_agent, look_for_keys) 
    File "/usr/lib/python2.6/site-packages/paramiko/client.py", line 520, in _auth 
    raise SSHException('No authentication methods available') 
  • 我能夠通過ssh沒有問題連接到主機。
  • SSH版本:OpenSSH_5.3p1,OpenSSL的1.0.0-FIPS 2010年03月29
  • 要注意:我試圖創建多個遠程服務器上運行的一系列命令的方式。我使用sys import argv來運行諸如python audit.py host1 host2 host3這樣的腳本,然後該腳本將通過針對這些特定主機的審計。我已經創建了一個完成這個的bash腳本,但是我想通過Python來實現它。
+1

難道這是由於缺少'password'關鍵字? – Tshepang

回答

6

你應該提供無論是密碼私鑰(或兩者),否則SSH客戶端不知道如何使用登錄數據進行身份驗證。

這是我的代碼示例供您參考。

#!/usr/bin/python 

from StringIO import StringIO 
import paramiko 

class SshClient: 
    "A wrapper of paramiko.SSHClient" 
    TIMEOUT = 4 

    def __init__(self, host, port, username, password, key=None, passphrase=None): 
     self.username = username 
     self.password = password 
     self.client = paramiko.SSHClient() 
     self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
     if key is not None: 
      key = paramiko.RSAKey.from_private_key(StringIO(key), password=passphrase) 
     self.client.connect(host, port, username=username, password=password, pkey=key, timeout=self.TIMEOUT) 

    def close(self): 
     if self.client is not None: 
      self.client.close() 
      self.client = None 

    def execute(self, command, sudo=False): 
     feed_password = False 
     if sudo and self.username != "root": 
      command = "sudo -S -p '' %s" % command 
      feed_password = self.password is not None and len(self.password) > 0 
     stdin, stdout, stderr = self.client.exec_command(command) 
     if feed_password: 
      stdin.write(self.password + "\n") 
      stdin.flush() 
     return {'out': stdout.readlines(), 
       'err': stderr.readlines(), 
       'retval': stdout.channel.recv_exit_status()} 

if __name__ == "__main__": 
    client = SshClient(host='host', port=22, username='username', password='password') 
    try: 
     ret = client.execute('dmesg', sudo=True) 
     print " ".join(ret["out"]), " E ".join(ret["err"]), ret["retval"] 
    finally: 
     client.close() 
-2

之前,你需要ssh.connect:
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

然後,你需要做stdout.read(東西),如:

print stdout.read() 
+0

我已經有了。 – Kryten