8

我一直试图让它工作,但不断收到同样的错误。我试过主机的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 更好地执行此操作。
4

2 回答 2

15

您应该提供密码私钥(或两者),否则 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() 
于 2014-03-23T16:57:20.330 回答
-3

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

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

print stdout.read()
于 2013-01-14T21:11:48.467 回答