河北中凯建设有限公司网站,wordpress网址转跳页面插件,一站式营销型网站建设服务,沈阳中讯国际网站建设Python基础教程#xff1a;用Python怎么telnet到网络设备0.前言Telnet协议属于TCP/IP协议族里的一种#xff0c;对于我们这些网络攻城狮来说#xff0c;再熟悉不过了#xff0c;常用于远程登陆到网络设备进行操作#xff0c;但是#xff0c;它的缺陷太明显了#xff0c;…Python基础教程用Python怎么telnet到网络设备0.前言Telnet协议属于TCP/IP协议族里的一种对于我们这些网络攻城狮来说再熟悉不过了常用于远程登陆到网络设备进行操作但是它的缺陷太明显了就是不安全信息明文传送极容易被攻击窃取信息不推荐使用但本节我还是先从它入手哈。1. 测试环境及关键代码解释1.1 简单测试环境使用python3环境使用内置telnetlib模块简单的实验环境说明cmd.txt文件里面命令如下terminal length 0 show clock show ip interface brieflist.txt文件里面的IP如下192.168.1.101 192.168.1.102 192.168.1.1031.2 关键代码import xx导入模块class xx定义类def xx: 定义函数try-except 处理可能引发的异常tn.read_until(expected, timeoutNone)等待预期字符串或等待超时tn.write(buffer)写入的字符串(意思发送给命令给设备)tn.expect(list, timeoutNone)读显list采用正则表达式(意思把执行过程显示出来)tn.read_very_eager()读显(意思把执行过程显示出来)tn.open(host, port0[, timeout])连接主机tn.close()关闭连接Tips终端与网络设备交付的信息是以byte类型所以要把终端上的字符串encode编码转换为byte对象,网络设备回显的byte信息要decode解码。2. 完整代码欢迎关注333 此平台是网路工程师个人日常技术、项目案例经验分享 为巩固及提升技术能力乃至共享所学所知技术 也欢迎各位工程师一起分享、一起成长。#!/usr/bin/env python#coding:utf-8导入模块from telnetlib import Telnetimport timeimport logging定义类class TelnetClient(): 初始化属性 def __init__(self): self.tn Telnet() 定义login_host函数用于登陆设备 def login_host(self,ip,username,password,enableNone,verboseTrue): 连接设备try-except结构 try: self.tn.open(ip,port23) except: logging.warning(%s网络连接失败 %ip) return False 输入用户名 self.tn.read_until(bUsername:, timeout1) self.tn.write(b) self.tn.write(username.encode() b) rely self.tn.expect([], timeout1)[2].decode().strip() #读显 if verbose: print(rely) 输入用户密码 self.tn.read_until(bPassword:, timeout1) self.tn.write(password.encode() b) rely self.tn.expect([], timeout1)[2].decode().strip() if verbose: print(rely) 进去特权模式 if enable is not None: self.tn.write(benable) self.tn.write(enable.encode() b) if verbose: rely self.tn.expect([], timeout1)[2].decode().strip() print(rely) time.sleep(1) rely self.tn.read_very_eager().decode() if Login invalid not in rely: logging.warning(%s登陆成功 % ip) return True else: logging.warning(%s登陆失败用户名或密码错误 % ip) return False 定义do_cmd函数,用于执行命令 def do_cmd(self,cmds): 读取文件for语句循环执行命令 with open(cmds) as cmd_obj: for cmd in cmd_obj: self.tn.write(cmd.encode().strip() b) time.sleep(2) rely self.tn.read_very_eager().decode() logging.warning(命令执行结果: %s %rely) 定义logout_host函数关闭程序 def logout_host(self): self.tn.close()if __name__ __main__: username cisco #用户名 password cisco #密码 enable cisco #特权密码 lists list.txt #存放IP地址文件相对路径 cmds cmd.txt #存放执行命令文件相对路径 telnet_client TelnetClient() 读取文件for语句循环登陆IP with open(lists,rt) as list_obj: for ip in list_obj: 如果登录结果为True则执行命令然后退出 if telnet_client.login_host(ip.strip(),username,password,enable): telnet_client.do_cmd(cmds) telnet_client.logout_host() time.sleep(2)3. 运行效果备注这个运行的效果我只存放了192.168.1.101这个IP精简一下为了效果。4. 报错效果远程连接不上 用户名和密码错误5. 碎碎念这些只是一些简单的代码待优化的地方还是很多先给小伙伴们学习一下telnet协议是个不安全的基本网络环境很少用了ssh为常用的协议安全又好用伙伴们有需要 补充的欢迎留言