我使用netmiko进行网络自动化的简单代码如下:所以首先我有:
- 函数 cisco_command 用于从输入文件中读取命令
- 函数 cisco_host 用于从输入文件中读取主机信息
- 函数 open_connection 用于启动与设备的连接
- 用于多处理的函数 run_program
- 函数 main 是主程序
所以我的代码有问题,你可以在 open_connection func 上看到我们有全局变量 commands_info 但是如果我们通过多处理 (run_program func) 运行这个程序,则 open_connection func 无法读取全局变量。
import time
import os
import concurrent.futures
from netmiko import ConnectHandler
from functools import partial
full_path = os.path.dirname(__file__)
host_file = os.path.join(full_path, "lab-router.txt")
command_file = os.path.join(full_path, "cisco-log.txt")
starting_time = ""
command_info = []
def cisco_command():
global command_info
command_info = []
with open(command_file, 'r') as commands:
for line in commands:
com = line.strip()
command_info.append(com)
return command_info
def cisco_host():
global starting_time
hosts_info = []
with open(host_file, 'r') as devices:
for line in devices:
deviceip = line.strip()
host = {
'device_type': 'cisco_ios',
'ip': deviceip,
'username': 'dodo',
'password': 'dodo',
'secret': 'dodo'
}
hosts_info.append(host)
starting_time = time.perf_counter()
return hosts_info
def open_connection(host):
global command_info
sendcommand = ""
try:
connection = ConnectHandler(**host)
print('Connection Established to Host:', host['ip'])
connection.enable()
for i in command_info:
sendcommand += "\n"
sendcommand += "==== {} ====".format(i)
sendcommand += "\n"
sendcommand += connection.send_command(i)
sendcommand += "\n"
# return sendcommand
with open("{}/{}_log.txt".format(full_path, host['ip']), 'w') as nf:
nf.write(sendcommand)
except:
print('Connection Failed to host', host['ip'])
def run_program(hosts_info):
with concurrent.futures.ProcessPoolExecutor() as executor:
results = executor.map(open_connection, hosts_info)
for result in results:
pass
finish = time.perf_counter()
print('Time Elapsed:', finish - starting_time)
def main():
commads = cisco_command()
hosts_info = cisco_host()
run_program(hosts_info)
if __name__ == '__main__':
main()
我不知道我错了什么