python paramiko与fileinput连接

时间:2013-02-27 10:27:28

标签: 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 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

我不确定我在这里缺少什么。请帮忙!

1 个答案:

答案 0 :(得分:2)

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

print('Connecting with "%s"...' % (line))

此名称可以包含CR,LF,空格或为空。核实。如果有换行符,请使用

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

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