使用python多处理登录路由器

时间:2017-04-24 02:51:31

标签: python multiprocessing cisco

我对编码/脚本编程有点新意,需要一些帮助来实现多处理。

我目前有两个功能,我将专注于此处。第一个,def getting_routes(router):登录到我的所有路由器(路由器列表来自前一个函数)并运行命令。第二个函数`def parse_paths(routes):解析该命令的结果。

def get_list_of_routers 
<some code> 
    return routers

def getting_routes(router):
    routes = sh.ssh(router, "show ip route")
    return routes

def parse_paths(routes):
    l = routes.split("\n")
...... <more code>.....
return parsed_list

我的列表大约有50个路由器,并且随后进行解析,需要相当多的时间,所以我想使用多处理模块在所有路由器上并行运行sshing到路由器,命令执行和后续解析。 我写道:

#!/usr/bin/env python
import multiprocessing.dummy import Pool as ThreadPool
def get_list_of_routers  (***this part does not need to be threaded)
<some code> 
    return routers

def getting_routes(router):
    routes = sh.ssh(router, "show ip route")
    return routes

def parse_paths(routes):
    l = routes.split("\n")
...... <more code>.....
    return parsed_list

if __name__ == '__main__':
    worker_1 = multiprocessing.Process(target=getting_routes)
    worker_2 = multiprocessing.Process(target=parse_paths)


   worker_1.start()
   worker_2.start()

我想要的是并行sshing到路由器,运行命令,并返回解析的输出。我一直在阅读http://kmdouglass.github.io/posts/learning-pythons-multiprocessing-module.html和多处理模块,但仍然没有得到我需要的结果并继续得到未定义的错误。对多处理模块中可能缺少的内容有何帮助?提前谢谢!

1 个答案:

答案 0 :(得分:0)

您似乎没有将路由器参数发送到 getting_routes 功能。

另外,我认为使用线程就足够了,您不需要创建新进程。

您需要做的是在主块中创建一个循环,该循环将为从 get_list_of_routers 函数返回的每个路由器启动一个新线程。然后你有两个选择 - 从线程中调用 parse_paths 函数,或者从线程中获取返回结果,然后调用parse_paths。

例如:     导入队列     来自线程导入线程

que = Queue.Queue()
threads = []


for router in get_list_of_routers():
    t = Thread(target=lambda q, arg1: q.put(getting_routers(arg1)), args=(que, router))
    t.start()
    threads.append(t)


for t in threads:
    t.join()


results = []
while not que.empty():
    results.append(que.get())


parse_paths(results)