婷婷综合国产,91蜜桃婷婷狠狠久久综合9色 ,九九九九九精品,国产综合av

主頁(yè) > 知識(shí)庫(kù) > python3+telnetlib實(shí)現(xiàn)簡(jiǎn)單自動(dòng)測(cè)試示例詳解

python3+telnetlib實(shí)現(xiàn)簡(jiǎn)單自動(dòng)測(cè)試示例詳解

熱門標(biāo)簽:外呼并發(fā)線路 長(zhǎng)沙高頻外呼系統(tǒng)原理是什么 百度地圖標(biāo)注沒(méi)有了 西藏房產(chǎn)智能外呼系統(tǒng)要多少錢 地圖標(biāo)注審核表 ai電銷機(jī)器人源碼 湛江智能外呼系統(tǒng)廠家 宿遷星美防封電銷卡 ai電話機(jī)器人哪里好

1 telnetlib介紹

 1.1 簡(jiǎn)介

官方介紹文檔:telnetlib – Telnet 客戶端 — Python 3.9.6 文檔

telnetlib 模塊提供一個(gè)實(shí)現(xiàn)Telnet協(xié)議的類 Telnet。

1.2 庫(kù)常用函數(shù)及使用

1.2.1 建立連接

建立連接有兩種方式:1、實(shí)例化函數(shù)的時(shí)候,將可選參數(shù) host 和 port 傳遞給構(gòu)造函數(shù),在這種情況下,到服務(wù)器的連接將在構(gòu)造函數(shù)返回前建立。2、使用telnetlib.Telnet類的open函數(shù)建立連接。

如以下兩種方式是等同的,參數(shù)timeout表示阻塞的時(shí)間(單位為秒),默認(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)

1.2.2 發(fā)送命令

發(fā)送命令使用的是Telnet類的write方法,注意參數(shù)buffer是字節(jié)字符串byte string,網(wǎng)絡(luò)數(shù)據(jù)傳輸都是使用的byte string,也就是字節(jié)流,在發(fā)送的字符串前面加一個(gè)b,就可以將字符串轉(zhuǎn)換為字節(jié)流。

Telnet.write(buffer)

例如,發(fā)送一個(gè)“exit”命令給服務(wù)器,也就是退出telnet連接。

tn.write(b"exit\n")

1.2.3 讀取返回?cái)?shù)據(jù)

Telnet類提供的讀取返回結(jié)果的函數(shù)比較多,這里列舉3個(gè):
Telnet.read_until(expected, timeout=None) 讀取直到遇到給定字節(jié)串 expected 或 timeout 秒已經(jīng)過(guò)去。默認(rèn)為阻塞性的讀。

Telnet.read_all() 讀取數(shù)據(jù),直到遇到 EOF;連接關(guān)閉前都會(huì)保持阻塞。

Telnet.read_very_eager() 在不阻塞 I/O 的情況下讀取所有的內(nèi)容(eager)。

1.2.4 關(guān)閉連接

關(guān)閉telnet連接直接使用Telnet.close()函數(shù),或者發(fā)送"exit"命令,以下兩種用法是一樣的。

tn = telnetlib.Telnet()
#方式1
tn.close()
#方式2
tn.write(b"exit\n")

1.3 使用示例

首先,我們先使用IPOP創(chuàng)建一個(gè)FTP服務(wù),端口為21,用戶名為admin,密碼為admin。

然后,編寫一個(gè)簡(jiǎn)單的測(cè)試用例,連接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ù)器,然后退出了:

2 自動(dòng)測(cè)試

參考代碼:Python3+telnetlib實(shí)現(xiàn)telnet客戶端 - 諸子流 - 博客園 (cnblogs.com)

先簡(jiǎn)單說(shuō)明代碼實(shí)現(xiàn)的功能,首先先運(yùn)行一個(gè)程序,這個(gè)程序會(huì)創(chuàng)建一個(gè)telnet服務(wù);然后使用python編寫一個(gè)telnet客戶端,連接telnet服務(wù),并輸入命令,獲取命令返回結(jié)果,根據(jù)結(jié)果來(lái)判斷命令是否執(zhí)行正確。

命令及期望結(jié)果:命令和期望的結(jié)果存放在excel中,期望結(jié)果用來(lái)從命令的返回?cái)?shù)據(jù)中進(jìn)行字符串查找的,如果找到了,表示命令執(zhí)行成功,否則認(rèn)為執(zhí)行失敗。格式如下:

執(zhí)行失敗結(jié)果保存:如果命令執(zhí)行失敗,則將命令和得到的返回?cái)?shù)據(jù)存放到一個(gè)單獨(dú)的文件中。

下面說(shuō)明代碼目錄結(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類實(shí)現(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ù)實(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')
        # 延時(shí)兩秒再收取返回結(jié)果,給服務(wù)端足夠響應(yīng)時(shí)間
        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登錄失敗,用戶名或密碼錯(cuò)誤' % 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:  # 將錯(cuò)誤信息記錄到文件中
                    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__':
    # 從表格中獲取測(cè)試的命令
    all_cmd_dict = {}
    all_cmd_dict = parse_cmd_excel("./src_file/")

    #啟動(dòng)telnet客戶端連接,并進(jìn)行測(cè)試
    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()

這樣就能實(shí)現(xiàn)一個(gè)簡(jiǎn)單的自動(dòng)測(cè)試命令的方式。

到此這篇關(guān)于python3+telnetlib實(shí)現(xiàn)簡(jiǎn)單自動(dòng)測(cè)試的文章就介紹到這了,更多相關(guān)python3 telnetlib自動(dòng)測(cè)試內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • 如何在Python3中使用telnetlib模塊連接網(wǎng)絡(luò)設(shè)備
  • python自動(dòng)化運(yùn)維之Telnetlib的具體使用
  • 使用python telnetlib批量備份交換機(jī)配置的方法

標(biāo)簽:林芝 盤錦 普洱 南平 海南 漯河 大同 寧夏

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《python3+telnetlib實(shí)現(xiàn)簡(jiǎn)單自動(dòng)測(cè)試示例詳解》,本文關(guān)鍵詞  python3+telnetlib,實(shí)現(xiàn),簡(jiǎn)單,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《python3+telnetlib實(shí)現(xiàn)簡(jiǎn)單自動(dòng)測(cè)試示例詳解》相關(guān)的同類信息!
  • 本頁(yè)收集關(guān)于python3+telnetlib實(shí)現(xiàn)簡(jiǎn)單自動(dòng)測(cè)試示例詳解的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    主站蜘蛛池模板: 盘山县| 宜州市| 栖霞市| 太白县| 梧州市| 蓝田县| 楚雄市| 临漳县| 阿拉善右旗| 临夏市| 光山县| 华亭县| 蒙阴县| 雷州市| 高陵县| 桃园市| 平潭县| 东台市| 开远市| 岳西县| 乌拉特中旗| 新田县| 鄂伦春自治旗| 玛纳斯县| 日喀则市| 临夏县| 涟水县| 无极县| 洪湖市| 民县| 武功县| 冀州市| 华容县| 自贡市| 吴江市| 鄂伦春自治旗| 南漳县| 石首市| 舟山市| 乌拉特中旗| 嘉兴市|