无法使用从 paramiko 文件中读取的主机名进行连接

Unable to connect using hostname read from a file in paramiko

我正在尝试使用 paramiko 连接到节点列表(主机名),并且在尝试连接时出现 socket.gaierror。它正在从一个文件中读取主机名,但是当它尝试连接时,我得到一个 gaierror。

import paramiko
import socket

f = open('<filename>', 'r')

 for node in f.readlines():
    try:
        ssh = paramiko.SSHClient()
        ssh.load_system_host_keys()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        print('Connecting to %s.' % node)
        node.strip()
        ssh.connect(node, username=user,password=passw)
        print('Connected to %s.' % node)
        stdin, stdout, stderr = ssh.exec_command(cmd)
        ssh.close()

    except socket.gaierror:
        print('Unable to connect to %s.' % node)
        pass

包含主机名的文件只是每行列出一个主机名。例如:

主机名1
主机名2
主机名3
等...

但是,如果我将代码从 for 循环中取出,并将主机名分配给一个变量,那么它就可以工作了。

import paramiko
import socket

node = '<hostname>'

try:
    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    print('Connecting to %s.' % node)
    node.strip()
    ssh.connect(node, username=user,password=passw)
    print('Connected to %s.' % node)
    stdin, stdout, stderr = ssh.exec_command(cmd)
    ssh.close()

except socket.gaierror:
    print('Unable to connect to %s.' % node)
    pass

提前致谢。

尝试使用 universal newline support('rU')打开文件以确保它没有拾取回车 returns。

编辑: 此外,将您的 node.strip() 作为参数添加到 ssh.connect() 调用中。 strip() 调用不在位。我编辑了代码示例以反映这一点:

import paramiko
import socket

with open('<filename>', 'rU') as f:

    for node in f.readlines():
        try:
            ssh = paramiko.SSHClient()
            ssh.load_system_host_keys()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            print('Connecting to %s.' % node)
            ssh.connect(node.strip(), username=user,password=passw)
            print('Connected to %s.' % node)
            stdin, stdout, stderr = ssh.exec_command(cmd)
            ssh.close()

        except socket.gaierror:
            print('Unable to connect to %s.' % node)
            pass