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

基于Python的Telnet客户端和网页下载脚本

时间:2023-03-25 23:06:37 Python

1.背景:本人在工作中管理近百台交换机,其中Hessman大约有60台。现在需要定期备份配置,查看日志检查隐患。但是通过网页下载太费时间了,安排两个人轮流下载用了1天,而且ms1600的配置是二进制的,于是萌生了研究python脚本的念头2、解决方法:在Windows网管上运行脚本,自动获取交换机配置并保存到本地,下载日志页面。①确认非营业时间下载②获取时间,放入文件夹名③读取IpAddress文件,获取交换机ip④登录交换机⑤根据命令列表输入命令⑥读取返回值并保存文件⑦下载日志页面3.实现代码:;“复制代码”)1#!python32#下载Hirschmann事件日志和配置3importos,requests,time,logging,telnetlib45#TODO:Telnetlogin,command,exitmodule6classTelnetClient():7def__init__(self,):8self.tn=telnetlib.Telnet()9deflogin_host(self,host_ip,username,password):10try:11#self.tn=telnetlib.Telnet(host_ip,port=23)另一种方法12self.tn.open(host_ip,port=23)13except:14logging.warning('%snetworkconnectionfailed'%k)#Connectionfailed15errorlog=open(os.path.join("D:\\%s"%DirName,"error.log"),'a')16errorlog.write('%sconnectionfailed\n'%host_ip)17errorlog.close()18returnFalse19self.tn.read_until(b'User:',timeout=5)#Read"User"访问后的返回值,最多等待5s,超过20次执行下一步self.tn.write(username.encode('utf-8')+b'\n')#用于写账户名,换行表示回车21self.tn.read_until(b'Password:',timeout=5)22self.tn.write(password.encode('utf-8')+b'\n')23time.sleep(5)#等待5s响应时间24command_result=self.tn.read_very_eager().decode('utf-8')#读取返回值,read_very_eager()获取的是上次获取之后获取所有之前output2526if'>'incommand_result:#判断登录成功27print('%s登录成功'%host_ip)28returnTrue29else:30logging.warning('%s登录不成功'%host_ip)31errorlog=open(os.path.join("D:\\%s"%DirName,"error.log"),'a')32errorlog.write('%s记录失败\n'%host_ip)33errorlog.close()34returnFalse35defexec_command(self,command):36foriinrange(len(command)):37self.tn.write(command[i].encode('utf-8')+b'\n')#executecommandlist38time.sleep(5)#一定要提供响应时间39command_result=self.tn.read_very_eager().decode('utf-8')40if"snooping"incommand_result:#判断数据完整性41config_file=open(os.path.join("D:\\%s"%DirName,"%s"%k+"_config.txt"),'a')#新建配置文件42config_file.write(command_result)#写入读取数据43config_file.close()44else:45Errorconfig=open(os.path.join("D:\\%s"%DirName,"error.log"),'a')#打开错误文件46Errorconfig.write('%s配置不完整\n'%v)#记录错误数据47errorconfig.close()48deflogout_host(self):49self.tn.write(b"exit\n")#输入exit退出505152#TODO:下载网页模块:53classDnld():54defdnldevent(self,name,ip):55url="http://"+ip+"/base/system/event_log.html"#Makeurl56res=requests.get(url)#获取网页57res.raise_for_status()58EventFile=open(os.path.join("D:\\%s"%DirName,"%s"%name+"_eventlog.html"),'wb')#新建html文件59forchunkinres.iter_content(100000):#Shardwrite60EventFile.write(chunk)61EventFile.close()62defdnldsys(self,name,ip):63url="http://"+ip+"/base/system/systemInfo.html"64res=requests.get(url)65res.raise_for_status()66EventFile=open(os.path.join("D:\\%s"%DirName,"%s"%name+"systemInfo.html"),'wb')67forchunkinres.iter_content(100000):68EventFile.write(chunk)69EventFile.close()7071#TODO:创建主程序,导入字典72if__name__=='__main__':73confirm=input('非营业时间请确认下载配置,请在下方输入“ok”\n')74ifconfirm.lower()=='ok':75localtime=time.strftime("%Y%m%d%H%M",time.localtime())#获取当前年月日时分76DirName=localtime+"_dump"#生成文件夹名称77DirName2=DirName#双文件夹,为下面同名文件夹做一个容器78Dic=[]#新建一个字典作为ip地址容器79i=180whileos.path.exists("D:\\%s"%DirName):#防止文件夹重复81DirName=DirName2+'_'+'%s'%i#在末尾添加序号82i+=183os.makedirs("D:\\%s"%DirName)#创建新文件夹84f=open('IpAddress.txt','r')#IpAddress.txt中的url末尾不要有“/”85forlineinf.readlines():86line=line.strip('\n')#去除换行符\n87b=line.split('')#将每一行转换为以空格作为分隔符的列表88Dic.append(b)#逐行读取txt文件并转换为嵌套列表89dic=dict(Dic)#使用dict方法将嵌套列表转换为字典90else:91exit()#退出程序,不输入ok9293#TODO:导入用户密码命令参数94fork,vinDic.items():95host_ip=v96host_name=k97username='xxxxx'98password='xxxxx'99command=['en','showrunning-config']#commandlist100#Respond=['#']#response特征值,还没有with101telnet_client=TelnetClient()102Download_web=Dnld()103iftelnet_client.login_host(host_ip,username,pas剑):104telnet_client.exec_command(命令)105telnet_client.logout_host()106Download_web.dnldevent(host_name,host_ip)107Download_web.dnldsys(host_name,host_ip);《复制代码》)编译成exe,我用的是Pyinstaller,用pycharm安装编译器后,可以在终端安装输入pyinstaller-Fxxx.py编译成exe。注意,如果编译系统是64位的,则无法在32位系统上运行。四、期间遇到如下问题:1、文件夹同名:时间精确到所以一分钟内重复运行os.makedirs会报文件已经存在,所以判断添加文件夹的存在。如果名称相同,则数字将在末尾递增。2、日志下载不完整:该问题主要是命令之间的响应时间不够,需要现场调试增加响应时间。同时增加一个判断点,以配置末尾的特征值作为判断点。如果不完整,将记录在错误日志中。3、如果网页下载没有错误记录:这个还在研究中,初步是换个顺序,先telnet连接,ok后再下载网页。五、心得:这是我做的第一个比较实用的脚本。确实是摸着石头过河。参考网上高手的方案,遇到问题就解决。最后还是需要到现场实测,验证功能的好坏。继续研究其他一些实用的脚本,做好自动化运维工作。