SSH - 使用paramiko的Python问题

9

我一直在尝试让这个工作,但是不断出现相同的错误。我已经尝试过主机的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 29 Mar 2010
  • 需要注意的是:我正在尝试创建一种在多台远程服务器上运行一系列命令的方式。我使用sys import argv来运行脚本,例如python audit.py host1 host2 host3,然后脚本将在特定主机上运行审核。我已经创建了一个完成此操作的bash脚本,但我希望通过Python找到更好的方法。

2
这可能是由于缺少 password 关键字引起的吗? - tshepang
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() 

-4

在ssh.connect之前,你需要执行以下操作:
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

然后你需要对stdout.read()进行一些操作,例如:

print stdout.read()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接