当前位置:首页 >> 脚本专栏

python 处理telnet返回的More,以及get想要的那个参数方法

问题:

需要循环获取网元返回的某个参数,并计算出平均值。

解决方案:

通过expect解决返回More的问题。

通过具体的参数位置,精确获取到参数。

讨论:

参数位置固定,不好复用。

#! usr/bin/env python

# -*- coding: utf-8 -*-

import telnetlib
import math
import time

def get_param(b):
 "获取相应的参数,返回float型参数组"
 c = []
 b = list(b)
 length = len(b)
 print length
 for x in b:
 c.append(float(x))
 print c
 return c

def get_avg(a):
 "获取平均值"
 length = len(a)
 sum = 0
 for x in a:
 sum += x
 avg = sum/length
 return avg

def get_telnet(tn):
 "获取telnet数据"
 for command in commands: 
 tn.write('%s\n' % command)
 time.sleep(0.5)
## result = tn.read_very_eager() # 不用read_all(),不能处理More
 print "**************"
 a = []
 a.append('More')
 print a
 result = str()
 while True:
  b,c,d = tn.expect(a,timeout=1)
  print b # 有More为0,无More为-1
  print 'cccccccccccccccccccccccccccccccccccccccccccc'
  print c
  print 'dddddddddddddddddddddddddddddddddddddddddddd'
  print d
  result += d
  if 0 == b:
  print "There has 'More'!!!"
  tn.write(r' ') #不用\r\n来继续
  else:
  break
 print 'get result success!'
 print result #获取到带More的所有返回结果 
 a = result.split('\r\n') # 不要加r
 length = len(a)
 print length
 b = a[1].split(' ')
 print b
 print a[32]
 c = a[32]
 d = c.split(' ')
 print d
 length = len(d)
 print d[8]
 e = d[8].split('(')
 print e[0]
 return e[0] 

def close_telnet(tn):
 "执行完毕后,终止Telnet连接(或输入exit退出)"
 tn.write('exit\n')
 tn.close()
 
def open_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) 
 return tn
 
if __name__=='__main__': 
 Host = '' # Telnet服务器IP 
 username = '' # 登录用户名 
 password = '' # 登录密码 
 finish = '#' # 命令提示符
 param = []

 commands = ['sho optical-module-info xgei-1/3/1']
 tn = open_telnet(Host, username, password, finish, commands)
 for i in range(1,10):
 param.append(get_telnet(tn))
 close_telnet(tn)
 print param
 print get_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想要的那个参数方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。