[英]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')
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.