python 处理telnet返回的More,以及get想要的那个参数方法
问题:
需要循环获取网元返回的某个参数,并计算出平均值。
解决方案:
通过expect解决返回More的问题。
通过具体的参数位置,精确获取到参数。
讨论:
参数位置固定,不好复用。
#!usr/bin/envpython #-*-coding:utf-8-*- importtelnetlib importmath importtime defget_param(b): "获取相应的参数,返回float型参数组" c=[] b=list(b) length=len(b) printlength forxinb: c.append(float(x)) printc returnc defget_avg(a): "获取平均值" length=len(a) sum=0 forxina: sum+=x avg=sum/length returnavg defget_telnet(tn): "获取telnet数据" forcommandincommands: tn.write('%s\n'%command) time.sleep(0.5) ##result=tn.read_very_eager()#不用read_all(),不能处理More print"**************" a=[] a.append('More') printa result=str() whileTrue: b,c,d=tn.expect(a,timeout=1) printb#有More为0,无More为-1 print'cccccccccccccccccccccccccccccccccccccccccccc' printc print'dddddddddddddddddddddddddddddddddddddddddddd' printd result+=d if0==b: print"Therehas'More'!!!" tn.write(r'')#不用\r\n来继续 else: break print'getresultsuccess!' printresult#获取到带More的所有返回结果 a=result.split('\r\n')#不要加r length=len(a) printlength b=a[1].split('') printb printa[32] c=a[32] d=c.split('') printd length=len(d) printd[8] e=d[8].split('(') printe[0] returne[0] defclose_telnet(tn): "执行完毕后,终止Telnet连接(或输入exit退出)" tn.write('exit\n') tn.close() defopen_telnet(Host,username,password,finish,commands): "Telnet远程登录" #连接Telnet服务器 tn=telnetlib.Telnet(Host,port=23,timeout=10) tn.set_debuglevel(2) #输入登录用户名 tn.read_until('Username:') tn.write(username+'\n') #输入登录密码 tn.read_until('Password:') tn.write(password+'\n') #登录完毕后执行命令 tn.read_until(finish) returntn if__name__=='__main__': Host=''#Telnet服务器IP username=''#登录用户名 password=''#登录密码 finish='#'#命令提示符 param=[] commands=['shooptical-module-infoxgei-1/3/1'] tn=open_telnet(Host,username,password,finish,commands) foriinrange(1,10): param.append(get_telnet(tn)) close_telnet(tn) printparam printget_avg(get_param(param)) ''' 运行结果: 37 ['Optical','Module','Position',':','xgei-1/3/1'] Bias-Upper:131(mA)Bias-Lower:0(mA) ['Bias-Upper','','','','','','',':','131(mA)','','','','','','','','','','','','','','','','Bias-Lower','','','','','','',':','0(mA)'] 131(mA) 131 Telnet(172.10.1.123,23):send'exit\n' ['131','131','131','131','131','131','131','131','131'] 9 [131.0,131.0,131.0,131.0,131.0,131.0,131.0,131.0,131.0] 131.0 >>> '''
以上这篇python处理telnet返回的More,以及get想要的那个参数方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。