1

简而言之,我编写了一个 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 秒直到退出......既然情况并非如此,它是否与线程挂起或锁定有关?

4

0 回答 0