Python“concurrent.futures”线程的执行问题

时间:2015-06-02 00:03:25

标签: python multithreading ssh concurrent.futures

简而言之,我编写了一个Python脚本,尝试与大约600个网络设备建立SSH连接(使用Paramiko模块),然后发出一个简单的命令,解析并返回输出。

我没有线程运行我的脚本,它按预期工作,所以我知道我的问题是线程方面(或我对它的理解)。我之前唯一的线程体验是在C ...

这是我对期货的使用:

with futures.ThreadPoolExecutor(max_workers=10) as executor:
    for x in nodeList:
        futureSSH = {executor.submit(connectHost,node): node for node in x.nodes}
        for future in futures.as_completed(futureSSH):
            print future.running()
            successes.append(futureSSH[future])
            counter +=1
            print counter

这是尝试SSH连接的功能:

def connectHost(node):

    myList = [],USERNAME = '#######',   MY_PASSWORD = '########' ,nodeNeighbors = nodeHierarchy(),counter = 0

    for i in range(10):
        try:
            print ("success")
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            print ("Attempting connection")
            ssh.connect(node,username = USERNAME,password = MY_PASSWORD, timeout = 10)
            print ("Connection established")
            stdin,stdout,stderr = ssh.exec_command('show cdp ne')

            ###Pattern match output here###
            break

        except Exception as error:
            continue
    else:
        return None 

现在所有这一切都完美无缺。除了在第153次迭代中我的脚本似乎冻结,仅在大约10分钟后恢复的事实。这将继续执行其余的执行。

让我感到困惑的是,我最多有10个活动线程尝试SSH连接最多10次,每次尝试超时10秒。所以我的理解是,在最糟糕的情况下,一个线程将闲置100秒直到退出......由于情况并非如此,它是否与线程挂起或锁定有关?

0 个答案:

没有答案