Python多线程循环问题?

Python多线程循环问题?,python,python-3.x,multithreading,python-2.7,queue,Python,Python 3.x,Multithreading,Python 2.7,Queue,我正在构建一个具有多线程功能的脚本来访问设备和执行命令。这里的问题是,我看到脚本连接到设备两次,而不是仅连接一次。在每个函数上添加了一个打印,以标识循环发生的区域 从输出来看,我认为循环在connect_now函数上,但我无法找到解决方案。我的try声明有什么问题吗 #!/usr/bin/env python3 # coding=utf-8 # ~~~~~~~~ # Import modules # ~~~~~~~~ import subprocess, logging, re, getpas

我正在构建一个具有多线程功能的脚本来访问设备和执行命令。这里的问题是,我看到脚本连接到设备两次,而不是仅连接一次。在每个函数上添加了一个打印,以标识循环发生的区域

从输出来看,我认为循环在connect_now函数上,但我无法找到解决方案。我的try声明有什么问题吗

#!/usr/bin/env python3
# coding=utf-8

# ~~~~~~~~
# Import modules
# ~~~~~~~~
import subprocess, logging, re, getpass,time
from netmiko import ConnectHandler
from netmiko.ssh_exception import NetMikoTimeoutException, NetMikoAuthenticationException
from paramiko.ssh_exception import SSHException
import threading
from queue import Queue
##from threading import Thread

logging.basicConfig(level=logging.INFO,
                    format="{asctime} {levelname:<8} {message}",
                    style='{',
                    filename='%slog' % __file__[:-2],
                    filemode='a'
                    )
##logging.info("this is a message")

# ~~~~~~~~
# Define functions
# ~~~~~~~~
dev_list = []
success_dev = []
failed_dev = []

def ping_ip(ip):
    global gips
    rstlongstr = ''
    (output,error) = subprocess.Popen((['ping', ip, '-c', '2']), stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True).communicate()
    if 'bytes from' in output:
        dev_list.append(ip)
        logging.info(output)
##        print (output)
        reg_rttavg = re.findall(r'(?=rtt.*=\s[\d.]+\/([\d.]+))',output)
        strpreg_rttavg = [test2.strip() for test2 in reg_rttavg]
        str_rttavg = '\n'.join(strpreg_rttavg)
        reg_ploss = re.findall(r'[\d%.]+(?= packet loss)',output)
        strpreg_ploss = [test2.strip() for test2 in reg_ploss]
        str_ploss = '\n'.join(strpreg_ploss)
        #return ".....Device is Reachable - " + ip
        return "[ " + ip + " ] Reachable - rtt(avg): %s ploss: %s" % (str_rttavg,str_ploss)
    elif 'Host Unreachable' in output:
##        print (output)
        return "[ " + ip + " ] Unreachable"
    else:
        #return "Unreachable"
##        print (output)
        return "[ " + ip + " ] Unreachable"
    thread_q.put

def seq_sendcmd(device_conn):
    global success_dev, failed_dev,output_dict
    print ("SEND COMMAND FUNCTION")
    sh_commands  = ['show run | i hostname', 'show clock']
    for cmd in sh_commands:
        print ("Sending command: ",cmd)
        result_out = device_conn.send_command(cmd)
    device_conn.disconnect()
    print ('[ ' + ip_a + ' ] Logged out')
##    success_dev.append(hostname)

def connect_now(ip_a,username,password,enable_s):
    global success_dev, failed_dev
    print ('[ ' + ip_a + ' ] Loging into IP')
    try:
        device_conn = ConnectHandler(device_type='cisco_ios_ssh', ip=ip_a,
                                             username=username, password=password,
                                             secret=enable_s, verbose=False)
        output = seq_sendcmd(device_conn)
        output_q.put(output)
        
    except:
        print ('[ ' + ip_a + ' ] Unable to access')
##        failed_dev.append(ip_a)  


#~~~~~~~~~~~~~~
#MAIN
#~~~~~~~~~~~~~~
##ipadd = ['192.168.2.111',"192.168.2.113", '9.9.9.222','192.168.2.112',"192.168.2.66",]
ipadd = ['192.168.2.111',"192.168.2.113"]
thread_q = Queue()
for x in ipadd:
##    print ("Pinging: ",x)
    m_thread = threading.Thread(target=ping_ip, args=(x,))
    m_thread.start()
    time.sleep(3)
m_thread.join()    
print (dev_list)   

Results = []
uname = "test"
pswd = "test"
ena = "test"

if uname == "" or pswd == "" or ena == "":
    print('username, password or enable_secret cannot be empty. Please enter valid credentials!!!')
    logging.info("username, password or enable_secret cannot be empty. Please enter valid credentials!!!")
    sys.exit()

logging.info("List of reachable device: " + str(dev_list))
start = time.time()
output_q = Queue()
for ip in dev_list:
    print ("Processing: ",ip)
    worker = threading.Thread(target=connect_now, args=(ip,uname,pswd,ena))
    worker.start()
    time.sleep(3)
worker.join()
print (output_q.get)

end = time.time()
total = int(end - start)
print("\n Elapsd Time: " + str(total) + " Sec\n")
#/usr/bin/env蟒蛇3
#编码=utf-8
# ~~~~~~~~
#导入模块
# ~~~~~~~~
导入子流程、日志记录、re、getpass、时间
从netmiko导入ConnectHandler
从netmiko.ssh_异常导入NetMikoTimeoutException、NetMikoAuthenticationException
从paramiko.ssh_异常导入SSHException
导入线程
从队列导入队列
##从线程导入线程
logging.basicConfig(level=logging.INFO,

format=“{asctime}{levelname:
seq_sendcmd()
在发送
show clock
命令时,第一个设备出现错误。该消息来自
块,但:
块除外。由于您使用线程,因此在第二个设备完成第一个设备的处理之前,您登录到第二个设备,因此消息可能会出现故障。感谢您在@Barmar发表的评论,因此这是可能的该连接被中断。但是为什么..脚本应该正确地完成命令的执行?因为我有一个for循环?请尝试打印异常,以便知道失败的原因。
print(output\q.get)
应该是
print(output\q.get())
,但这与问题无关。
['192.168.2.111', '192.168.2.113']         <---- from dev_list
Processing:  192.168.2.111                 <---- from Main/Global
[ 192.168.2.111 ] Loging into IP           <---- from connect_now
SEND COMMAND FUNCTION                      <---- from seq_sendcmd func
Sending command:  show run | i hostname
Sending command:  show clock
Processing:  192.168.2.113                 
[ 192.168.2.113 ] Loging into IP         
[ 192.168.2.111 ] Unable to access         <---- from connect_now func,why script tries to connect again?
SEND COMMAND FUNCTION                    
Sending command:  show run | i hostname
Sending command:  show clock
[ 192.168.2.113 ] Unable to access
<bound method Queue.get of <queue.Queue object at 0x7faf12043eb8>>

 Elapsd Time: 6 Sec