放弃之路0x02 Python模块netmiko
安装模块:
pip3 install netmiko 和 loguru(日志模块)
实例1:
1、创建ip_list.txt用来存放设备IP地址
2、使用open打开txt文件读取IP地址
3、使用for循环IP
# coding=utf-8
"""
netmiko登陆H3C交换机
user:admin
password:admin123
"""
from netmiko import ConnectHandler
from loguru import logger
with open('ip_list.txt', encoding='utf-8') as f:
for i in f:
# 创建字典
sw1 = {
'device_type': 'hp_comware', # 定义设备类型
'ip': i, # 变量IP
'username': 'admin', # 用户名
'password': 'admin123' # 密码
# 'port':'22' # 指定登陆端口,默认22
}
connect = ConnectHandler(**sw1) # 传入设备字典与设备建立SSH连接。
logger.info('成功连接' + sw1['ip'])
config_commands = ['int g1/0/1', 'dis this'] # 定义需要配置的命令
output = connect.send_config_set(config_commands) # 执行命令
logger.info(output) # 打印结果
result = connect.send_command('dis ip int br')
logger.info(result)
回显结果:
实例2:
1、创建ip_list.txt用来存放设备IP地址
2、创建command_list.txt用来存放命令
3、使用open打开txt文件读取IP地址和命令
4、使用for循环IP
# coding=utf-8
"""
netmiko登陆交换机
user:admin
password:admin123
"""
from netmiko import ConnectHandler
from loguru import logger
with open('ip_list.txt', encoding='utf-8') as f:
for i in f:
sw1 = {
'device_type': 'hp_comware',
'ip': i,
'username': 'admin',
'password': 'admin123'
}
connect = ConnectHandler(**sw1)
logger.info('成功连接' + sw1['ip'])
commands_list = open('command_list.txt', 'r') # 打开配置文件
for s in commands_list: # 循环读取配置
config_commands = s
output = connect.send_config_set(commands_list)
logger.info(output)
result = connect.send_command('dis ospf lsdb')
logger.info(result)
commands_list.close()
回显结果: