簡體   English   中英

SSH - 與paramiko問題的Python

[英]SSH - Python with paramiko issue

我一直試圖讓這個工作,但不斷得到相同的錯誤。 我試過了主機的fqdn和ip。 我試圖用憑證傳遞它而沒有。 我查看了錯誤消息中指示的行。 搜索谷歌,但無法弄清楚為什么這不起作用:

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年3月29日
  • 要注意:我正在嘗試創建一種在多個遠程服務器上運行一系列命令的方法。 我正在使用sys import argv來運行python audit.py host1 host2 host3等腳本,然后腳本將通過對這些特定主機的審計運行。 我已經創建了一個bash腳本來完成這個,但我想通過Python更好地實現它。

您應該提供密碼私鑰 (或兩者),否則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() 

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

然后你需要用stdout.read()做一些事情:

print stdout.read()

暫無
暫無

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

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