2016-08-22 61 views
-1

目前,我正在開發一些功能來同時對多個遠程設備進行SSH訪問。我遇到了像下面這樣的問題。Python全局變量不起作用

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

有,我需要在我的代碼使用任何其他參數?

回答

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

謝謝,它效果不錯 – nanto

0

您所創建的全局參數list_ipip_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列表中,而不是存儲在一個全局變量的結果。

+0

謝謝你,謝謝你的建議。我使用ip_file函數返回 – nanto