您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“怎么用python3+telnetlib實現(xiàn)簡單自動測試”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
1 telnetlib介紹
1.1 簡介
1.2 庫常用函數(shù)及使用
1.2.1 建立連接
1.2.2 發(fā)送命令
1.2.3 讀取返回數(shù)據(jù)
1.2.4 關(guān)閉連接
1.3 使用示例
2 自動測試
官方介紹文檔:telnetlib – Telnet 客戶端 — Python 3.9.6 文檔
telnetlib 模塊提供一個實現(xiàn)Telnet協(xié)議的類 Telnet。
建立連接有兩種方式:1、實例化函數(shù)的時候,將可選參數(shù) host 和 port 傳遞給構(gòu)造函數(shù),在這種情況下,到服務(wù)器的連接將在構(gòu)造函數(shù)返回前建立。2、使用telnetlib.Telnet類的open函數(shù)建立連接。
如以下兩種方式是等同的,參數(shù)timeout表示阻塞的時間(單位為秒),默認(rèn)為一直阻塞:
import telnetlib HOST = "10.102.1.12" #方式1 tn = telnetlib.Telnet(HOST, port=21, timeout=10) #方式2 tn = telnetlib.Telnet() tn.open(HOST, port=21)
發(fā)送命令使用的是Telnet類的write方法,注意參數(shù)buffer是字節(jié)字符串byte string,網(wǎng)絡(luò)數(shù)據(jù)傳輸都是使用的byte string,也就是字節(jié)流,在發(fā)送的字符串前面加一個b,就可以將字符串轉(zhuǎn)換為字節(jié)流。
Telnet.write(buffer)
例如,發(fā)送一個“exit”命令給服務(wù)器,也就是退出telnet連接。
tn.write(b"exit\n")
Telnet類提供的讀取返回結(jié)果的函數(shù)比較多,這里列舉3個:
Telnet.read_until(expected, timeout=None) 讀取直到遇到給定字節(jié)串 expected 或 timeout 秒已經(jīng)過去。默認(rèn)為阻塞性的讀。
Telnet.read_all() 讀取數(shù)據(jù),直到遇到 EOF;連接關(guān)閉前都會保持阻塞。
Telnet.read_very_eager() 在不阻塞 I/O 的情況下讀取所有的內(nèi)容(eager)。
關(guān)閉telnet連接直接使用Telnet.close()函數(shù),或者發(fā)送"exit"命令,以下兩種用法是一樣的。
tn = telnetlib.Telnet() #方式1 tn.close() #方式2 tn.write(b"exit\n")
首先,我們先使用IPOP創(chuàng)建一個FTP服務(wù),端口為21,用戶名為admin,密碼為admin。
然后,編寫一個簡單的測試用例,連接telnet服務(wù)器,然后退出。
import getpass import telnetlib HOST = "10.102.1.12" user = input("Enter your remote account: ") password = getpass.getpass() tn = telnetlib.Telnet(HOST, port=21, timeout=10) tn.write(user.encode('ascii') + b"\n") if password: tn.write(password.encode('ascii') + b"\n") print(tn.read_very_eager().decode('ascii')) tn.write(b"exit\n") print ("exit")
直接執(zhí)行,結(jié)果如下,可以看出,連接了一次telnet服務(wù)器,然后退出了:
參考代碼:Python3+telnetlib實現(xiàn)telnet客戶端 - 諸子流 - 博客園 (cnblogs.com)
先簡單說明代碼實現(xiàn)的功能,首先先運(yùn)行一個程序,這個程序會創(chuàng)建一個telnet服務(wù);然后使用python編寫一個telnet客戶端,連接telnet服務(wù),并輸入命令,獲取命令返回結(jié)果,根據(jù)結(jié)果來判斷命令是否執(zhí)行正確。
命令及期望結(jié)果:命令和期望的結(jié)果存放在excel中,期望結(jié)果用來從命令的返回數(shù)據(jù)中進(jìn)行字符串查找的,如果找到了,表示命令執(zhí)行成功,否則認(rèn)為執(zhí)行失敗。格式如下:
執(zhí)行失敗結(jié)果保存:如果命令執(zhí)行失敗,則將命令和得到的返回數(shù)據(jù)存放到一個單獨(dú)的文件中。
下面說明代碼目錄結(jié)構(gòu):
1078885-20210817232240481-1025625638
C_parse_excel.py類用于解析excel,獲取命令及返回結(jié)果: # -*- coding: utf-8 -*- import os import sys import re import xlrd import logging logging.basicConfig(level=logging.NOTSET, format='[%(filename)s:%(lineno)d]-%(levelname)s %(message)s') class CCsrConfig(object): def __init__(self, excelName): self._registerDict = {} self._excelName = excelName def OpenExcel(self): if self._excelName == "": self._excelName = None else: self._excelfd = xlrd.open_workbook(self._excelName) for sheetName in self._excelfd.sheet_names(): pass def ReadCSRCfg(self): return_dict = {} #{sheetName: [cmdlist]} for sheetName in self._excelfd.sheet_names(): tmp_list = [] sheet = self._excelfd.sheet_by_name(sheetName) if None != sheet: if sheet.nrows == 0: # no content continue sheetName = str(sheetName.strip()).lower() logging.debug(sheetName) row_start = 0 for row in range(sheet.nrows): if sheet.cell(row, 0).value.strip() == u"command": row_start = row + 1 break for row in range(row_start, sheet.nrows, 1): cmd = str(sheet.cell(row, 0).value).strip() exp_ret = str(sheet.cell(row, 1).value).strip() tmp_list.append([cmd, exp_ret]) return_dict[sheetName.lower()] = tmp_list return return_dict
C_telnet.py類實現(xiàn)telnet連接,以及發(fā)送命令和獲取結(jié)果,并解析結(jié)果信息:
# -*- coding:utf-8 -*- import logging import telnetlib import time class TelnetClient(): def __init__(self,): self.tn = telnetlib.Telnet() # 此函數(shù)實現(xiàn)telnet登錄主機(jī) def login_host(self, host_ip, remote_port, username, password): try: self.tn.open(host_ip, port = remote_port) except: logging.warning('%s網(wǎng)絡(luò)連接失敗' % host_ip) return False # 等待login出現(xiàn)后輸入用戶名,最多等待10秒 self.tn.read_until(b'login: ', timeout=2) self.tn.write(username.encode('ascii') + b'\n') # 等待Password出現(xiàn)后輸入用戶名,最多等待10秒 self.tn.read_until(b'Password: ', timeout=2) self.tn.write(password.encode('ascii') + b'\n') # 延時兩秒再收取返回結(jié)果,給服務(wù)端足夠響應(yīng)時間 time.sleep(2) # 獲取登錄結(jié)果 command_result = self.tn.read_very_eager().decode('ascii') if 'Login incorrect' not in command_result: logging.debug(u'%s登錄成功' % host_ip) return True else: logging.warning(u'%s登錄失敗,用戶名或密碼錯誤' % host_ip) return False def start_test_cmd(self, cmd_dict): for sheet_item in cmd_dict: for sheet in sheet_item: cmd_list = sheet_item[sheet] tmp_err_list = [] for cmd in cmd_list: cmd_in = cmd[0] exp_ret = cmd[1] self.tn.write(cmd_in.encode('ascii')+b'\n') time.sleep(1) # 獲取命令結(jié)果 command_result = self.tn.read_very_eager().decode('ascii') if command_result.find(exp_ret) == -1: tmp_err_list.append([cmd_in, command_result]) else: print('%s' % command_result) if len(tmp_err_list) != 0: # 將錯誤信息記錄到文件中 with open("./out_file/%s_err_log.txt" % sheet, "w+", newline="") as f: for err_item in tmp_err_list: logging.debug(err_item[0]) f.write("%s" % err_item[0]) f.write("%s" % err_item[1]) # 退出telnet def logout_host(self): self.tn.write(b"exit\n")
main_func.py是主函數(shù)入口:
# -*- coding:utf-8 -*- import logging import os import sys from C_telnet import * from C_parse_excel import * Host_ip = '192.168.17.128' Username = 'admin' Password = 'admin' Remote_port = 8000 def parse_cmd_excel(dir_name): objList = [] list_f = os.listdir(dir_name) for item in list_f: item = dir_name + item if os.path.isfile(item) and (item[-5:] == '.xlsx' or item[-5:] == '.xlsm'): if item.find("$") != -1: continue csrConfig = CCsrConfig(item) csrConfig.OpenExcel() tmp = csrConfig.ReadCSRCfg() objList.append(tmp) elif os.path.isdir(item): item = item + '/' new_obj_list = [] new_obj_list = parse_cmd_excel(item) for each in new_obj_list: objList.append(each) return objList if __name__ == '__main__': # 從表格中獲取測試的命令 all_cmd_dict = {} all_cmd_dict = parse_cmd_excel("./src_file/") #啟動telnet客戶端連接,并進(jìn)行測試 telnet_client = TelnetClient() if telnet_client.login_host(Host_ip, Remote_port, Username, Password) == False: print("Telnet disconnected!\n") else: telnet_client.start_test_cmd(all_cmd_dict) telnet_client.logout_host()
這樣就能實現(xiàn)一個簡單的自動測試命令的方式。
“怎么用python3+telnetlib實現(xiàn)簡單自動測試”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。