【发布时间】:2018-04-10 16:17:37
【问题描述】:
在学习使用 python 进行网络自动化时,我创建了一个脚本来使用某些命令来捕获少数网络交换机的详细信息。我已经明确地将命令保存在commands.txt 中,并以 Jason 格式在文件devices.json 中登录凭据以从中选择它,当我运行它时,它通过创建一个带有时间戳的命令输出详细信息的文件按预期工作。
我想要什么:因为我有 commands.txt 文件,其中包含不同的命令,我想在其中为我拥有的每个命令创建一个单独的文件 commands.txt。到目前为止,所有内容都被捕获到一个文件中,所需的示例..
prod-stvdx-sw_vcs_details.txt-Apr-10-2018:12:53
prod-stvdx-sw_vcs.txt-Apr-10-2018:12:53
prod-stvdx-sw_fabric_trunk.txt-Apr-10-2018:12:53
以下是脚本版本:
from __future__ import absolute_import, division, print_function
import json
import netmiko
import signal
import sys
import time
timestamp = time.strftime('%b-%d-%Y:%H:%M')
signal.signal(signal.SIGPIPE, signal.SIG_DFL) # IOError: Broken pipe
signal.signal(signal.SIGINT, signal.SIG_DFL) # KeyboardInterrupt: Ctrl-C
if len(sys.argv) < 3:
print('Usage: cmdrunner.py commands.txt devices.json')
exit()
netmiko_exceptions = (netmiko.ssh_exception.NetMikoTimeoutException,
netmiko.ssh_exception.NetMikoAuthenticationException)
#username, password = getPass.get_credentials()
with open(sys.argv[1]) as cmd_file:
commands = cmd_file.readlines()
with open(sys.argv[2]) as dev_file:
devices = json.load(dev_file)
for device in devices:
#device['username'] = username
#device['password'] = password
try:
print('~' * 79)
print('Connecting to device:', device['ip'])
connection = netmiko.ConnectHandler(**device)
filename = connection.base_prompt + '.txt' + '-' + timestamp
with open(filename, 'w') as out_file:
for command in commands:
out_file.write('++++ Output of ' + command + '\n\n')
out_file.write(connection.send_command(command) + '\n\n')
connection.disconnect()
except netmiko_exceptions as e:
print('Failed to ', device['ip'], e)
我的commands.txt文件:
$ cat commands.txt
show vcs details
show vcs
show fabric islports
show fabric isl
show fabric trunk
show logging raslog
show version
show ip int brief
运行
$ ./brocade_2.py commands.txt devices.json
-rw-r--r-- 1 moli moli 286K Apr 10 12:53 prod-stvdx-sw.txt-Apr-10-2018:12:53
【问题讨论】:
标签: python-3.x