![](/img/trans.png)
[英]Extract output of Juniper Devices and save to dictionary file via netmiko python
[英]Not getting output for multiprocessing netmiko multiple devices
使用多處理無法獲取多設備連接的輸出
我嘗試了以下代碼:
import multiprocessing as mp
from netmiko import ConnectHandler
import netmiko
import re
from datetime import datetime
def get_ip (input):
return(re.findall(r'(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)', input))
def make_connection (ip, username, password):
device_connect = ConnectHandler(device_type='cisco_nxos', ip=ip, username=username, password=password)
output = device_connect.send_command("sh hostname")
print(output)
device_connect.disconnect()
def get_ips_nexus (file_name):
for line in open(file_name, 'r').readlines():
line = get_ip(line)
for ip in line:
ips_nexus.append(ip)
ips_nexus = []
get_ips_nexus("ips-Copy.txt")
print(ips_nexus)
username = 'x.x.x.x'
password = 'xxxxxxxx'
startTime = datetime.now()
processes = []
for ip in ips_nexus:
print('***********')
print(ip)
print('***********')
p = mp.Process(target=make_connection, args=(ip, username, password))
processes.append(p)
p.start()
print('!!!!!!!!!!!!!!!!!!!!!!!!!')
for p in processes:
print(p)
p.join()
print(datetime.now() - startTime
我只得到打印ip而不是sh主機名的netmiko連接的輸出。
我只想使用多處理來實現多設備連接!!!
請幫忙。
您缺少if __name__ == "__main__"
子句!
將其添加到for-循環的上方:
if __name__ == "__main__": # add this
for ip in ips_nexus:
print('***********')
print(ip)
print('***********')
p = mp.Process(target=make_connection, args=(ip, username, password))
processes.append(p)
p.start()
print('!!!!!!!!!!!!!!!!!!!!!!!!!')
首先:如果您運行自己的代碼,則python解釋器會將其導入為“ 主 ”文件。 您可以通過添加print(__name__)
來嘗試。 無論如何,如果您使用multiprocessing
啟動新進程,則python解釋器會再次導入您的代碼,並將其作為額外進程和新Skript運行! 好吧,如果它再次達到(對於您而言)這部分:
p = mp.Process(target=make_connection, args=(ip, username, password))
它將再次開始一個新過程,再次導入它,依此類推。 最后,您將有一個無限循環,它每次都會以新進程的形式啟動代碼! 這就是為什么您必須添加( 重要 ) if __name__ == "__main__"
子句的原因! 通過添加此名稱, __name__
將不會在首次調用新進程后成為__main__
!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.