python paramiko与fileinput连接

python paramiko与fileinput连接,python,paramiko,file-io,Python,Paramiko,File Io,我需要在多台服务器上运行一个命令,我使用以下代码: import paramiko, getpass, fileinput username = raw_input("Enter your username [%s]: " % getpass.getuser()) passwd = getpass.getpass("Enter your password: ") serverlist = raw_input("Enter the server list fi

我需要在多台服务器上运行一个命令,我使用以下代码:



    import paramiko, getpass, fileinput

    username = raw_input("Enter your username [%s]: " % getpass.getuser())
    passwd = getpass.getpass("Enter your password: ")
    serverlist = raw_input("Enter the server list file path with filename: ")

    for line in fileinput.input([serverlist]):
        paramiko.util.log_to_file('paramiko.log')
        s = paramiko.SSHClient()
        #s.load_system_host_keys()
        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        s.connect(line, 22, username, passwd)
        stdin, stdout, stderr = s.exec_command('uptime')
        print stdout.read()
        s.close()

但是,此代码正在生成以下错误消息:



    Traceback (most recent call last):
      File "test_paramiko.py", line 15, in 
        s.connect(line, 22, username, passwd)
      File "/usr/lib/python2.6/site-packages/paramiko/client.py", line 277, in connect
        socket.getaddrinfo(hostname, port):
    socket.gaierror: [Errno -2] Name or service not known


我不确定我在这里错过了什么。请帮忙

您可能从
serverlist
获得未知主机名。添加如下内容:

print('Connecting with "%s"...' % (line))
此名称可以包含CR、LF、空格或为空。检查一下。如果它有换行符,那么使用

hostname = line.strip()
print('Connecting with "%s"...' % (hostname))
s.connect(hostname, 22, username.strip(), passwd.strip())

username
passwd
变量也是如此。但请确保用户名和密码不能以空格或其他空格结尾。您可以使用
rstrip()
代替
strip()

是,使用
strip()
rstrip()
字符串方法。非常感谢,问题已解决。