当前位置: 首页 > 后端技术 > Python

如何使用Pythontelnet到网络设备

时间:2023-03-26 02:10:20 Python

0。前言Telnet协议属于TCP/IP协议族。对我们网络攻城狮来说再熟悉不过了。常用于远程登录网络设备进行操作,但是它的缺陷太明显了,就是不安全,信息以明文形式传输,极易被攻击窃取信息。不推荐使用它,但我会在本节开始使用它。一、测试环境及关键代码解释1.1简单测试环境使用python3环境使用内置的telnetlib模块简单实验环境说明:cmd.txt文件中命令如下:terminallength0showclockshowipinterfacebrieflist.txt文件中IP如下:192.168.1.101192.168.1.102192.168.1.1031.2关键代码importxx:importmoduleclassxx:defineclassdefxx:definefunctiontry-except:handlepossibleexceptionstn.read_until(expected,timeout=None):waitforexpectedStringorwaitfortimeouttn.write(buffer):写入的字符串(意思是向设备发送命令)tn.expect(list,timeout=None):读取并显示,list采用正则表达式(意思是显示执行过程出来)tn.read_very_eager():读显示(意思是显示执行过程)tn.open(host,port=0[,timeout]):连接主机tn.close():关闭连接提示:终端和网络设备下发信息ion是byte类型,所以终端上的字符串编码要转成byte对象,网络设备回显的字节信息要解码。2.完整代码'''欢迎关注微信公众号:'diandijishu'这个平台是网络工程师分享日常技术和项目案例经验的平台。为了巩固和提高技术能力,甚至分享所学知识,欢迎工程师加入我们一起分享,共同成长。'''#!/usr/bin/envpython#coding:utf-8'importmodule'fromtelnetlibimportTelnetimporttimeimportlogging'defineclass'classTelnetClient():'initializationattribute'def__init__(self):self.tn=Telnet()'定义登录设备的login_host函数'deflogin_host(self,ip,username,password,enable=None,verbose=True):'连接设备,try-except结构'try:self.tn.open(ip,port=23)except:logging.warning('%snetworkconnectionfailed'%ip)returnFalse'Enterusername'self.tn.read_until(b'Username:',timeout=1)self.tn.写(b'\n')self.tn.write(username.encode()+b'\n')rely=self.tn.expect([],timeout=1)[2].decode().strip()#Readifverbose:print(rely)'Enteruserpassword'self.tn.read_until(b'Password:',timeout=1)self.tn.write(password.encode()+b'\n')rely=self.tn.expect([],timeout=1)[2].decode().strip()如果冗长:print(rely)'Enterprivilegedmode'如果enable不是None:self.tn.write(b'enable\n')self.tn.write(enable.encode()+b'\n')如果冗长:rely=self.tn.expect([],timeout=1)[2].decode().strip()print(rely)time.sleep(1)rely=self.tn.read_very_eager().decode()如果'Logininvalid'notinrely:logging.warning('%slogin成功'%ip)returnTrueelse:logging.warning('%s登录失败,用户名或密码错误'%ip)returnFalse'定义do_cmd函数,用于执行命令'defdo_cmd(self,cmds):'阅读Fetchthefile,executethecommandinaloopwiththeforstatement'withopen(cmds)ascmd_obj:forcmdincmd_obj:self.tn.write(cmd.encode().strip()+b'\n')time.sleep(2)rely=self.tn.read_very_eager().decode()logging.warning('命令执行结果:\n%s'%rely)'定义logout_host函数,关闭程序'deflogout_host(self):self.tn.close()if__name__=='__main__':username='cisco'#username密码='cisco'#passwordenable='cisco'#privilegedpasswordlists='list.txt'#存储IP地址文件,相对路径cmds='cmd.txt'#存储执行命令文件,相对路径telnet_client=TelnetClient()'读取文件,使用for语句登录IP'withopen(lists,'rt')aslist_obj:foripinlist_obj:'如果登录结果为True,执行命令然后退出'iftelnet_client.login_host(ip.strip(),username,password,enable):telnet_client.do_cmd(cmds)telnet_client.logout_host()time.sleep(2)3.运行效果备注:我只存储IP192.168.1.101这个运行效果.效果4.报错效果4.1远程连接不可用4.2用户名和密码错误5.破烂的语言以上只是一些简单的代码,还有很多地方需要优化,先让小伙伴们学习一下,telnet协议不安全,基本上很少使用网络环境。ssh是一种常用的协议,安全且易于使用。在下一篇文章中,我将介绍如何在python中使用ssh模块。本人代码功底不深,如有不足请指教,谢谢。如果喜欢我的文章,欢迎关注我的公众号:滴滴科技,扫码关注,不定时分享