LOVEJOAN

文章 分类 评论
76 9 1453

站点介绍

人生是一场孤独的旅行,没有终点。。。

netmiko简介与使用

chuck 2023-05-15 291 25条评论 网络技术编程 python

首页 / 正文

neimiko

Python基于CLI模式与网络设备进行交互的工具包有很多,而netmiko与paramiko无疑是这类工具包中的两颗璀璨明珠。它是工程师Kirk Byers 于2015年发布的一个用于简化众多厂商网络设备CLI连接(ssh、telnet、serial)的工具类。实际2015年的版本只支持ssh,所以它最早是为了简化ssh通用工具类paramiko的连接和操作(后续netmiko已经支持了telnet和serial),所以它的名字从中取了"miko",又因其垂直于网络自动化领域,所以又添加了“net”,组成了netmiko的名称。

neimiko基本满足了对主流网络设备的支持,可以辅以paramiko和telnlib的功能实现复杂的需求。

安装

pip install netmiko

支持的平台

  • huawei(华为)
  • hp_comware(华三)
  • fortinet(飞塔)
  • cisco_asa(思科ASA)
  • cisco_ios(思科交换机)
  • Ruijie Networks(锐捷)
  • Aruba
  • juniper

创建连接

网络运维对设备管理的第一步就是登录设备,可以使用netmiko的函数ConnectHandler

from netmiko import ConnectHandler

ConnectHandler实例化参数包括设备类型,设备地址,账号密码等信息。返回一个长连接字典对象。
示例:

conn = ConnectHandler(device_type='hp_comware',
                      host='192.168.128.208',
                      username='admin',
                      password='WZS134125',
                      port=22)

print(conn)
'''以上输出一个实际的连接对象
<netmiko.cisco.cisco_ios.CiscoIosSSH object at 0x000002DBC9F23F10>
'''
conn.disconnect()

常用的参数:

说明参数名
ip设备IP地址
host设备host名称,需要可以解析出IP地址
username用户名
password密码
secretenable密码,提权时需要输入的密码
port端口,会根据device_type自动判断(如有“ssh”字符串是22,如有“telnet”是23)可以用户指定
device_type设备的驱动名称
conn_timeout连接超时时间,默认为5秒,如果网络条件不好,建议适当增加,尤其是广域网或者国际网络
timeout执行命令的超时时间,根据情况适当延长,默认为100秒
session_log记录log的路径,如填写则会将与设备的所有操作记录
session_log_file_mode记录log的模式,覆盖"write" ,追加 "append",默认覆盖
global_delay_factor默认的全局的延迟因子,值为1,但是一般不修改。
fast_cli快速模式,默认False,不开启,netmiko内部提供一种优化性能的方式,设置为True后,在与设备交互过程中读取隧道中信息的频率会加快(全局延迟因子与单个方法中的延迟因子取较小值)。

命令执行

netmiko的很多入门也以show命令演示为主,主要用到了netmiko的send_command方法与send_commnad_timing方法,都用于发送单条display/show命令。

send_command方法

# 官方文档
# https://ktbyers.github.io/netmiko/docs/netmiko/index.html#netmiko.BaseConnection.send_command
def send_command
(self, command_string: str, expect_string: Optional[str] = None, read_timeout: float = 10.0, delay_factor: Optional[float] = None, max_loops: Optional[int] = None, auto_find_prompt: bool = True, strip_prompt: bool = True, strip_command: bool = True, normalize: bool = True, use_textfsm: bool = False, textfsm_template: Optional[str] = None, use_ttp: bool = False, ttp_template: Optional[str] = None, use_genie: bool = False, cmd_verify: bool = True) ‑> Union[str, List[Any], Dict[str, Any]]

常用参数:

command_string:要在远程设备上执行的命令。
expect_string:用于确定输出结束的正则表达式模式。 如果留空,则默认基于路由器提示。
read_timeout:等待寻找模式的最长时间。将提高读取超时 如果超过超时,适用于需要读取大量信息或者时间较长的操作防止程序终止,默认10秒。
auto_find_prompt:使用 find_prompt() 覆盖基本提示符。
strip_prompt:从输出中删除尾随路由器提示符(默认值:True)。
strip_command:从输出中删除命令的回显(默认值:True)。
normalize:确保在命令末尾发送正确的输入(默认值:True)
cmd_verify:在继续操作之前验证命令回显(默认值:True)。

一般情况下只需要调整前面3个参数即可。
示例:

# 模块导入
from netmiko import ConnectHandler

# 交换机自动备份配置
# 设备信息
device = {'device_type':'hp_comware',
      'ip':'192.168.128.208',
      'username':'admin',
      'password':'2z6d*EZ1cf',
      'session_log' : 'swback.log'
      }
# 创建连接
conn = ConnectHandler(**device)
# 执行命令,将回显写入output
output = conn.send_command(command_string='dis ip int b')
print(output)
# 输出
Interface           Physical Protocol IP address      VPN instance Description
Vlan2               up       up       --              --           MGT
Vlan3               up       up       --              --           --
Vlan4               up       up       --              --           ҵ
Vlan128             up       up       192.168.128.208 --           MGT
Vlan129             up       up       --              --           MJ
Vlan132             up       up       --              --           --

示例2:

# 模块导入
from netmiko import ConnectHandler

# 交换机自动备份配置
# 设备信息
device = {'device_type':'hp_comware',
      'ip':'192.168.128.208',
      'username':'admin',
      'password':'2z6d*EZ1cf',
      'session_log' : 'swback.log'
      }
conn = ConnectHandler(**device)

output = conn.send_command(command_string='dis cur',read_timeout=15)
print(output)

send_commnad是基于回显匹配来判断命令是否执行完成,可以自动或者通过正则表达式匹配。

send_commnad_timing方法

使用基于延迟的机制在 SSH 通道上执行command_string。一般 用于显示命令,意思是不基于判断回显判断命令是否完成而是基于时间因子,过了一定时间后继续执行剩下的任务。

send_command_timing
(self, command_string: str, last_read: float = 2.0, read_timeout: float = 120.0, delay_factor: Optional[float] = None, max_loops: Optional[int] = None, strip_prompt: bool = True, strip_command: bool = True, normalize: bool = True, use_textfsm: bool = False, textfsm_template: Optional[str] = None, use_ttp: bool = False, ttp_template: Optional[str] = None, use_genie: bool = False, cmd_verify: bool = False) ‑> Union[str, List[Any], Dict[str, Any]]

常用参数与send_command方法类似。

command_string:要在远程设备上执行的命令。
last_read:数据结束后等待的时间,默认2秒。
read_timeout:Netmiko 应该继续读取数据多长时间的绝对计时器 通道(等待没有新数据)。如果出现这种情况,将引发读取超时 超时过期。read_timeout值为 0 将导致读取循环永不超时 (即Netmiko将无限期地继续阅读,直到没有新数据和last_read 传输),默认120秒。

示例1:

# 模块导入
from netmiko import ConnectHandler

# 交换机自动备份配置
# 设备信息
device = {'device_type':'hp_comware',
      'ip':'192.168.128.208',
      'username':'admin',
      'password':'2z6d*EZ1cf',
      'session_log' : 'swback.log'
      }
conn = ConnectHandler(**device)

output = conn.send_command_string(command_string='dis cur',last_read=1)
print(output)

send_config_set

通过 SSH 通道按顺序发送配置命令,config_commands 是一个包含所有配置命令的可迭代对象(列表、元组等),命令将一个接一个地执行,自动退出/进入配置模式,适用于设备配置(不涉及show、save等)

# 参数
send_config_set
(self, config_commands: Union[str, Sequence[str], Iterator[str], TextIO, ForwardRef(None)] = None, *, exit_config_mode: bool = True, read_timeout: Optional[float] = None, delay_factor: Optional[float] = None, max_loops: Optional[int] = None, strip_prompt: bool = False, strip_command: bool = False, config_mode_command: Optional[str] = None, cmd_verify: bool = True, enter_config_mode: bool = True, error_pattern: str = '', terminator: str = '#', bypass_commands: Optional[str] = None) ‑> str
# 示例,自动进入配置模式执行commands中的命令,通过参数控制配置完成是否退出配置模式
# 模块导入
from netmiko import ConnectHandler

# 交换机自动备份配置
# 设备信息
device = {'device_type':'hp_comware',
      'ip':'192.168.128.208',
      'username':'admin',
      'password':'2z6d*EZ1cf',
      'session_log' : 'swback.log'
      }
conn = ConnectHandler(**device)
commands = ['int vlan 2','ip add 192.168.50.1 24','desc test']
output = conn.send_config_set(config_commands=commands,exit_config_mode=True)
print(output)
# 输出
system-view
System View: return to User View with Ctrl+Z.
[KL_HC_JT_SW_208]int vlan 2
[KL_HC_JT_SW_208-Vlan-interface2]ip add 192.168.50.1 24
[KL_HC_JT_SW_208-Vlan-interface2]desc test
[KL_HC_JT_SW_208-Vlan-interface2]return
<KL_HC_JT_SW_208>

常用参数:
config_commands:要发送到设备的多个配置命令。
exit_config_mode:确定完成后是否退出配置模式。(True/False)
read_timeout:发送到read_channel_timing的绝对计时器。还调整 read_timeout read_until_pattern通话。
config_mode_command:进入配置模式的命令,华为华三是system-view,思科是enable,自动,一般不需要修改。
strip_prompt:确定是否去除提示,一般不修改即可。
strip_command:确定是否剥离命令,一般不修改即可。
cmd_verify:是否验证config_set中每个命令的命令回显,默认即可。
enter_config_mode:在发送配置命令之前是否进入配置模式,默认即可。
error_pattern:用于检测输出,默认即可。
一般前面4个即可,其他默认,可以实现多个命令顺序执行的情况。

send_config_from_file方法

send_config_set方法的扩展,从文件沿 SSH 通道发送配置命令,文件逐行处理,每个命令都向下发送 SSH 通道,可以实现从文件读取操作命令执行。

# 参数
def send_config_from_file
(self, config_file: Union[str, bytes, ForwardRef('PathLike[Any]')], **kwargs: Any) ‑> str

# 示例
# 模块导入
from netmiko import ConnectHandler

# 交换机自动备份配置
# 设备信息
device = {'device_type':'hp_comware',
      'ip':'192.168.128.208',
      'username':'admin',
      'password':'2z6d*EZ1cf',
      'session_log' : 'swback.log'
      }
conn = ConnectHandler(**device)
command = 'int vlan 2 \nip add 192.168.50.1 24\ndesc test\ndis ip int b\n'
with open('command.txt',mode='w',encoding='utf-8') as f:
      f.write(command)
commands_file = 'command.txt'
output = conn.send_config_from_file(config_file=commands_file)
print(output)
# 输出
Interface           Physical Protocol IP address      VPN instance Description
Vlan2               up       up       192.168.50.1    --           test
Vlan3               up       up       --              --           --
Vlan4               up       up       --              --           ҵ
Vlan128             up       up       192.168.128.208 --           MGT
Vlan129             up       up       --              --           MJ
Vlan132             up       up       --              --           --

常用参数:
config_file:要发送到设备的配置文件的路径
kwargs:要发送到send_config_set方法的参数

其他功能函数

find_prompt()方法,可以获取设备回显名称。

print(conn.find_prompt())

config_mode()进入配置模式

conn.config_mode()

save_config()方法,保存设备配置,通过识别设备类型,自动进入配置模式,进行配置保存。

conn.save_config()

示例:

import time
from netmiko import ConnectHandler
import pandas as pd

def get_batch_backup_dev_infos(file='sw_list.xlsx'):
      df = pd.read_excel(file)
      items = df.to_dict(orient='records')
      dev_infos = []
      for i in items:
            dev = i
            dev_infos.append(dev)
      return dev_infos
devices = get_batch_backup_dev_infos()

for device in devices:
      # 创建连接
      connect = ConnectHandler(**device)
      # 执行配置保存
      connect.save_config()
      # 文件命名
      hostname = device['host'] +'-'+connect.find_prompt().strip('[]')
      now = time.strftime('%Y%m%d',time.localtime())
      file_name = '/backup/'+hostname+'-'+now +'.cfg'

      # 通过从命令列表循环执行
      commands = ['return','ftp 192.168.80.2','wuzeshu','WZS134125','ascii',"put startup.cfg "+file_name,'bye','quit']
      for command in commands:
            connect.send_command_timing(command)
      print(hostname + '备份任务已完成!')
print('所有备份已经完成!')

评论(25)

  1. 1 游客 2025-03-28 00:20 回复

    555*DBMS_PIPE.RECEIVE_MESSAGE(CHR(99)||CHR(99)||CHR(99),15)

  2. 1 游客 2025-03-28 00:19 回复

    5550'XOR(555*if(now()=sysdate(),sleep(15),0))XOR'Z

  3. 1 游客 2025-03-28 00:18 回复

    555

  4. 1 游客 2025-03-28 00:17 回复

    555

  5. 1 游客 2025-03-28 00:16 回复

    555

  6. @@5PAVH 游客 2025-03-28 00:13 回复

    555

  7. 1S3YD0vnQ'; waitfor delay '0:0:15' -- 游客 2025-03-28 00:12 回复

    555

  8. 1-1; waitfor delay '0:0:15' -- 游客 2025-03-28 00:11 回复

    555

  9. 1 游客 2025-03-28 00:10 回复

    555

  10. 1 游客 2025-03-28 00:09 回复

    555

  11. 1 游客 2025-03-28 00:09 回复

    555

  12. 1 游客 2025-03-28 00:09 回复

    555

  13. 1 游客 2025-03-28 00:09 回复

    555

  14. 1 游客 2025-03-28 00:08 回复

    555

  15. 1 游客 2025-03-28 00:07 回复

    555

  16. 1 游客 2025-03-28 00:07 回复

    555

  17. 1 游客 2025-03-28 00:07 回复

    555

  18. 1 游客 2025-03-28 00:05 回复

    555

  19. 1 游客 2025-03-27 23:12 回复

    555

  20. 1 游客 2025-03-27 23:11 回复

    555

热门文章

最新评论

  • 1

    555fulIdEqZ' OR 160=(SELECT 160 FROM PG_SLEEP(15))--

  • 1

    555-1)) OR 58=(SELECT 58 FROM PG_SLEEP(15))--

  • 1

    555-1) OR 13=(SELECT 13 FROM PG_SLEEP(15))--

  • 1

    555-1 OR 475=(SELECT 475 FROM PG_SLEEP(15))--

  • 1

    555

  • 1

    555

  • 1

    5554FobGRsu') OR 696=(SELECT 696 FROM PG_SLEEP(15))--

  • 1

    555C9F0upP1' OR 504=(SELECT 504 FROM PG_SLEEP(15))--

  • 1

    555

  • 1-1; waitfor delay '0:0:15' --

    555

日历

2025年05月

    123
45678910
11121314151617
18192021222324
25262728293031

文章目录