2016-08-22 9 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

あなたはip_file機能でグローバルパラメータlist_ipを作成しましたが、機能は決してありませんと呼ばれます。

だからクイックフィックスは次のようになります。ところで

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

関連する問題