您好,登錄后才能下訂單哦!
這篇文章主要介紹python如何處理telnet返回的More,文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!
問題:
需要循環(huán)獲取網(wǎng)元返回的某個參數(shù),并計算出平均值。
解決方案:
通過expect解決返回More的問題。
通過具體的參數(shù)位置,精確獲取到參數(shù)。
討論:
參數(shù)位置固定,不好復(fù)用。
#! usr/bin/env python # -*- coding: utf-8 -*- import telnetlib import math import time def get_param(b): "獲取相應(yīng)的參數(shù),返回float型參數(shù)組" 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數(shù)據(jù)" 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來繼續(xù) else: break print 'get result success!' print result #獲取到帶More的所有返回結(jié)果 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): "執(zhí)行完畢后,終止Telnet連接(或輸入exit退出)" tn.write('exit\n') tn.close() def open_telnet(Host, username, password, finish, commands): "Telnet遠程登錄" # 連接Telnet服務(wù)器 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') # 登錄完畢后執(zhí)行命令 tn.read_until(finish) return tn if __name__=='__main__': Host = '' # Telnet服務(wù)器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)) ''' 運行結(jié)果: 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”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。