使用Python Paramiko建立SSH连接时出现"getaddrinfo"错误
我正在使用Paramiko这个工具,想要和一个服务器建立连接,但连接失败了,输出的信息如下:
Traceback (most recent call last):
File "C:\ucatsScripts\cleanUcatsV2.py", line 13, in <module>
ssh.connect(host,username,password)
File "C:\Python27\lib\site-packages\paramiko-1.7.6-py2.7.egg\paramiko\client.py", line 278, in connect
for (family, socktype, proto, canonname, sockaddr) in socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM):
socket.gaierror: [Errno 10109] getaddrinfo failed
这是我正在使用的代码:
import paramiko
import cmd
import sys
# Connect to Server
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
success = ssh.connect('MASKED',username='MASKED',password='MASKED')
if (success != True):
print "Connection Error"
sys.exit()
else:
print "Connection Established"
有没有什么建议呢?
4 个回答
0
你确定这个主机名能找到对应的IP地址吗?你可以在你的电脑上试试输入 ping that_hostname
来检查一下。
3
要注意,主机名中不要包含用户名。
ssh.connect(hostname='user@example.com', port=22)
user@example.com
不是一个适合用于连接的主机名参数。
你应该使用:
ssh.connect(hostname='example.com', port=22, username='user')
10
只需要在主机后面加上端口号就可以了:
ssh.connect('MASKED', 22, username='MASKED',password='MASKED')
顺便说一下,正如robots.jpg所说,connect方法并不会返回任何东西。它不是返回值,而是会触发一些异常。
这里有一个更完整的例子:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import paramiko, os, string, pprint, socket, traceback, sys
time_out = 20 # Number of seconds for timeout
port = 22
pp = pprint.PrettyPrinter(indent=2)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
file = open( "file.txt", "r" )
# NOTE: The file contains:
# host user current_password
array = []
for line in file:
array = string.split(line.rstrip('\n'),)
# pp.pprint(array)
try:
ssh.connect(array[0], port, array[1], array[2], timeout=time_out)
print "Success!! -- Server: ", array[0], " Us: ", array[1]
except paramiko.AuthenticationException:
print "Authentication problem -- Server: ", array[0], " User: ", array[1]
continue
except socket.error, e:
print "Comunication problem -- Server: ", array[0], " User: ", array[1]
continue
ssh.close()
file.close()
代码需要稍微修整一下,但基本上能完成任务。