2

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



    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

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

4

1 回答 1

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())

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

于 2013-02-27T10:31:04.353 回答