Python处理Telnet返回More提示及提取指定参数详解

追风的人
追风的人
发布时间:2026-10-13 | 6人浏览过
原创

本文介绍使用Python处理Telnet交互中出现的More分页提示,通过expect机制循环读取完整数据,并基于固定参数位置精确提取目标值。代码包含获取参数列表、计算平均值及处理Telnet会话的完整逻辑,适用于网络设备自动化运维场景。

问题背景

在实际操作中,需要循环从网元设备获取特定参数,并计算这些参数的平均值。

解决方案概述

利用Python的expect方法来解决Telnet返回内容中包含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提示以及获取目标参数的方法分享完毕,希望能为读者提供参考,并欢迎大家继续支持本站。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表