Python全局变量不起作用

时间:2016-08-22 03:12:04

标签: python-2.7 paramiko

目前,我正在开发一些功能,以便同时对多个远程设备进行SSH访问。我遇到了类似下面的问题。

Traceback (most recent call last):
  File "/Volume/Projects/SSH_Conn.py", line 51, in <module>
    SSH_Thread()
  File "/Volume/Projects/SSH_Conn.py", line 43, in SSH_Thread
    for ip in list_ip:
NameError: global name 'list_ip' is not defined

我很确定我在下面的代码中创建了全局参数:

def ip_file():
    **global list_ip**
    ip_list_file = open('ip.txt', 'r')
    ip_list_file.seek(0)
    list_ip = ip_list_file.readlines()
    ip_list_file.close()

def ssh_conn(ip):
    date_time = datetime.datetime.now().strftime("%Y-%m-%d")
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, port=22, username='x', password='y', look_for_keys=False, timeout=None)
    connection = ssh.invoke_shell()
    connection.send("\n")
    connection.send("ls -l\n")
    time.sleep(2)
    file_output = connection.recv(9999)
    hostname = (re.search(r'(.+)$', file_output)).group().strip('$')
    outFile = open(hostname + "-" + str(date_time) + ".txt", "w")
    outFile.write(file_output)

def SSH_Thread():
    threads_instance = []
    for ip in list_ip:
        ti = threading.Thread(target=ssh_conn, args=(ip,))
        ti.start()
        threads_instance.append(ti)

    for ti in threads_instance:
        ti.join()

SSH_Thread()

我的代码中是否还需要使用其他参数?

2 个答案:

答案 0 :(得分:0)

只需返回函数中的值,而不是处理全局变量。

def ip_file():
    ip_list_file = open('ip.txt', 'r')
    ip_list_file.seek(0)
    list_ip = ip_list_file.readlines()
    ip_list_file.close()
    return list_ip  # return the value, so others can use it.

然后,当您想要使用它时,只需调用该函数并保存结果:

def SSH_Thread():
    threads_instance = []
    list_ip = ip_file()  # here is where you get the result back
    for ip in list_ip:
        ti = threading.Thread(target=ssh_conn, args=(ip,))
        ti.start()
        threads_instance.append(ti)

    for ti in threads_instance:
        ti.join()

答案 1 :(得分:0)

您已在list_ip函数中创建了全局参数ip_file,但函数从未被调用

因此,quickfix将是:

def SSH_Thread():
    threads_instance = []
    ip_file() # <--------------- generate the list
    for ip in list_ip:
        ti = threading.Thread(target=ssh_conn, args=(ip,))
        ti.start()
        threads_instance.append(ti)

    for ti in threads_instance:
        ti.join()

顺便说一下,return列表更好,而不是将结果存储在全局变量中。