執行效果如下:
VIP通道:一起學Python-通過python腳本進行批量telnet連通性測試
文檔内容如下:
代碼如下:
使用方法:
源代碼如下:
import argparse
import os
import logging
import telnetlib
run_log = 'run.txt'
if os.path.exists(run_log):
os.remove(run_log)
logger = logging.getLogger()
logger.setLevel('DEBUG')
BASIC_FORMAT = "%(asctime)s :%(levelname)s :%(message)s"
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(BASIC_FORMAT, DATE_FORMAT)
chlr = logging.StreamHandler() # 輸出到控制台的handler
chlr.setFormatter(formatter)
chlr.setLevel('DEBUG') # 也可以不設定,不設定就預設用logger的level
fhlr = logging.FileHandler(run_log) # 輸出到檔案的handler
fhlr.setFormatter(formatter)
logger.addHandler(chlr)
logger.addHandler(fhlr)
##telnet通路函數
def to_up(Host, port, timeout, frequency):
info = ("第[%s]次通路位址[%s:%s]" %(frequency, Host, port))
try:
tn = telnetlib.Telnet(Host, port=port, timeout=timeout)
tn.close()
de = info + "成功\n"
logger.debug(de)
except:
err = info + "失敗\n"
logger.error(err)
#測試功能類
class Test:
def __init__(self, frequency, port, timeout, host):
self.frequency = frequency
self.host = host
self.port = int(port)
self.timeout = int(timeout)
def telnet(self):
end = self.frequency + 1
for s in range(1, end):
to_up(Host=self.host, port=self.port, timeout=self.timeout, frequency=s)
#擷取文本内容
def get_info(url_file, frequency=1, timeout=None):
if os.path.exists(url_file):
# 打開檔案
file = open(url_file, "r", encoding='utf-8')
# 周遊檔案行内容
for (num, line) in enumerate(file, 1):
line = str.replace(line,'\n','')
logger.info("正在檢測第[%s]行内容:[%s]" % (num, line))
xi2 = [line]
for i in xi2:
domain_port = i.split(' ')
domain = domain_port[0]
port = domain_port[1]
logger.info("第[%s]行擷取的域名:[%s]" % (num, domain))
logger.info("第[%s]行擷取的端口:[%s]\n" % (num, port))
Program = Test(frequency=frequency, port=port, timeout=timeout, host=domain)
Program.telnet()
file.close()
else:
exit("找不到檔案[%s]" %url_file)
def main():
#all_info :接收所有傳入的資訊
all_info = argparse.ArgumentParser(description="設定測試參數")
data = {'-f': '--file', '-n': '--frequency', '-t': '--time'}
for i in data:
parameter = i
parameters = data.get(i)
all_info.add_argument(parameter, parameters, required=True)
all = all_info.parse_args()
##下面開始拆分資訊,all.xxx中,xxx為上面定義的--後面的字元串
f = all.file
s = all.frequency
t = all.time
logger.info("\n檔案選擇:[%s]\n通路次數:[%s]次\n逾時時間:[%s]秒\n" %(f, s, t))
get_info(url_file=f, frequency=int(s), timeout=int(t))
if __name__ == '__main__':
main()