网络工程师自动化之Python入门到放弃—SSH

放弃之路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()

回显结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值