如何在Python项目中使用SSH连接到网络设备
本篇文章给大家分享的是有关如何在Python项目中使用SSH连接到网络设备,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
1. 测试环境及关键代码解释
1.1 简单测试环境
使用python3环境
使用第三方Netmiko模块(基于Paramiko库进行改版)
简单的实验环境
1.2 关键代码
import xx:导入模块
class xx:定义类
def xx: 定义函数
try-except :处理可能引发的异常
ssh.enable():进入enable模式
ssh.find_prompt():返回当前提示符
ssh.send_command():发送查询命令并返回结果
ssh.send_config_set():发送配置命令到目标设备
ssh.disconnect():关闭连接
Tips: import ConnectHandler和import Netmiko是一样的效果的哈。
2. 完整代码
''' 欢迎关注微信公众号:'diandijishu' 此平台是网路工程师个人日常技术、项目案例经验分享, 为巩固及提升技术能力乃至共享所学所知技术, 也欢迎各位工程师一起分享、一起成长。 ''' #!/usr/bin/env python #coding:utf-8 from netmiko import ConnectHandler from netmiko.ssh_exception import NetMikoTimeoutException from netmiko.ssh_exception import NetMikoAuthenticationException from datetime import datetime import time import logging from my_devices import device_list as devices '定义类' class SSH_Client(): '定义login_host函数,用于登陆设备' def login_host(self , a_device): try: self.ssh = ConnectHandler(**a_device) self.ssh.enable() reply = self.ssh.find_prompt() print('>' * 10 + '成功登陆结果如下:' + '>' * 10 + '\n' + reply) return True except ValueError: logging.warning(a_device['host'] + ' Secret 密码错误') except NetMikoTimeoutException: logging.warning(a_device['host'] + ' 连接不上设备,请检查网络是否正常通信') except NetMikoAuthenticationException: logging.warning(a_device['host'] + ' 登陆失败,用户名或密码错误') '定义do_cmd函数,用于执行命令' def do_cmd(self,cmds): '读取文件,for语句循环执行命令' with open(cmds) as cmd_obj: for cmd in cmd_obj: reply = self.ssh.send_command(cmd) time.sleep(2) logging.warning('>' * 10 + cmd.rstrip() + ' 命令执行结果如下:' + '>' * 10 + '\n' + reply) '定义logout_host函数,关闭程序' def logout_host(self): self.ssh.disconnect() if __name__ == '__main__': cmds = 'cmd.txt' # 存放执行命令文件,相对路径 ssh_client = SSH_Client() start_time = datetime.now() for a_device in devices: '如果登录结果为True,则执行命令,然后退出' if ssh_client.login_host(a_device): ssh_client.do_cmd(cmds) ssh_client.logout_host() time.sleep(2) stop_time = datetime.now() print('总花费时长:{0}\n'.format(stop_time - start_time))
3. 运行效果
4. 报错效果
4.1 远程连接不上
4.2 用户名和密码错误
以上就是如何在Python项目中使用SSH连接到网络设备,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注行业资讯频道。