简体   繁体   English

Python 多处理 - Netmiko

[英]Python Multiprocessing - Netmiko

I really a newbie to python and network automation;我真的是 Python 和网络自动化的新手; I am trying out multiprocessing with Python and netmiko, but haven't successful;我正在尝试使用 Python 和 netmiko 进行多处理,但没有成功; the code keeps being executed sequentially per device.代码不断按设备顺序执行。

Below is my code and results:下面是我的代码和结果:

======================== ========================

import datetime
from netmiko import ConnectHandler
import threading
from time import time
import multiprocessing
from multiprocessing import Process, Lock


starting_time = time()

def newthread():
    with open('routers.txt', 'r') as devices:
        for line in devices:
            deviceip = line.strip()
            host = {
                'device_type': 'cisco_ios',
                'ip': deviceip,
                'username': 'cisco',
                'password': 'cisco',
                'secret': 'cisco'
            }

            try:
                connection = ConnectHandler(**host)
                print('Trying router', deviceip)
                print('Connection Established to Host:', deviceip)
                connection.enable()
                sendcommand = connection.send_command('sh run | i hostname')
                print(sendcommand)
            except:
                print('Connection Failed to host', deviceip)


threadtask = Process(target=newthread)
threadtask.start()
threadtask.join()

print('Time Elaspsed:', time() - starting_time)


====Result===
Trying router 10.10.32.2
Connection Established to Host: 10.10.32.2
hostname R1
Trying router 10.10.32.3
Connection Established to Host: 10.10.32.3
hostname R2
Trying router 10.10.32.4
Connection Established to Host: 10.10.32.4
hostname R4
Trying router 10.10.32.5
Connection Established to Host: 10.10.32.5
hostname R3
Time Elaspsed: 26.788068771362305

Process finished with exit code 0

What could i be doing wrong?我可能做错了什么? am kinda stuck.我有点卡住了。 Thank You.谢谢你。

__ Regards Desmon K __ 问候戴斯蒙 K

Use concurrent.futures inbuilt module.使用 concurrent.futures 内置模块。 It provides high level API's to execute tasks asynchronously.它提供了高级 API 来异步执行任务。

https://docs.python.org/3/library/concurrent.futures.html https://docs.python.org/3/library/concurrent.futures.html

Below is modified code.下面是修改后的代码。 Hope it helps.希望能帮助到你。

import time
import concurrent.futures
from netmiko import ConnectHandler

hosts_info = []
with open('routers.txt', 'r') as devices:
    for line in devices:
        deviceip = line.strip()
        host = {
            'device_type': 'cisco_ios',
            'ip': deviceip,
            'username': 'cisco',
            'password': 'cisco',
            'secret': 'cisco'
        }
        hosts_info.append(host)

starting_time = time.perf_counter()

def open_connection(host):
    try:
        connection = ConnectHandler(**host)

        print('Trying router', host['ip'])
        print('Connection Established to Host:', host['ip'])
        connection.enable()
        sendcommand = connection.send_command('sh run | i hostname')
        return sendcommand
    except:
        print('Connection Failed to host', host['ip'])


with concurrent.futures.ProcessPoolExecutor() as executor:
    results = executor.map(open_connection, hosts_info)

    for result in results:
        print(result)

finish = time.perf_counter()
print('Time Elapsed:', finish - starting_time)

After following @Sandeep's code i edited a few things and finally achieved the primary goal;在遵循@Sandeep 的代码之后,我编辑了一些东西,最终实现了主要目标;

The final working code is here最终的工作代码在这里

import time
import concurrent.futures
from netmiko import ConnectHandler

hosts_info = []

starting_time = time.perf_counter()

with open('routers.txt', 'r') as devices:
    for line in devices:
        deviceip = line.strip()
        host = {
            'device_type': 'cisco_ios',
            'ip': deviceip,
            'username': 'cisco',
            'password': 'cisco',
            'secret': 'cisco'
        }
        hosts_info.append(host)

def open_connection(host):
    try:
        connection = ConnectHandler(**host)
        print('Connection Established to Host:', host['ip'])
        connection.enable()
        sendcommand = connection.send_command('sh run | i hostname')
        return sendcommand + ' ' + 'For Device:' + host['ip']
    except:
        print('Connection Failed to host', host['ip'])


if __name__ == '__main__':
    with concurrent.futures.ProcessPoolExecutor() as executor:
        results = executor.map(open_connection, hosts_info)
        for result in results:
            print(result)

    finish = time.perf_counter()
    print('Time Elapsed:', finish - starting_time)

Output:输出:

Connection Established to Host: 10.10.32.2
Connection Established to Host: 10.10.32.4
Connection Established to Host: 10.10.32.5
Connection Established to Host: 10.10.32.3
hostname R1 For Device:10.10.32.2
hostname R2 For Device:10.10.32.3
hostname R4 For Device:10.10.32.4
hostname R3 For Device:10.10.32.5
Time Elapsed: 7.035125793000589

Please note that ip is supposed to be in quotes as 'ip'.请注意,ip 应该用引号括起来作为 'ip'。 Output is not that Fancy, but this will do for now.输出不是那么花哨,但现在就可以了。 Thank you @ https://stackoverflow.com/users/4087758/sandeep-nagendra谢谢@https ://stackoverflow.com/users/4087758/sandeep-nagendra

确保在 BIOS 中启用了超线程设置/多核支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM