Python實現telnet命令測試防火牆
telnet
主要用於測試主機端口是否開通ping
主要是用來測試網絡是否暢通和主機是否正在使用
使用Python實現Telnet測試主機端口是否開通的功能。使用telnet命令是會出現以下集中情況:
通過Python的socket模塊來實現,根據上述三種情況進行不同的處理
Telnet協議是基於tcp協議實現的
主機和端口都是通的
這種情況,就會正常連接,正常發送和返回,socket沒有任何異常,不用管是否需要密碼這一情況,這種情況只需要socket連接主機ip和port,就肯定能鏈接目標主機ip和端口。
只需要連接自后斷開就ok
主機通端口不通
這種情況,連接過程中,socket會拋出ConnectionRefusedError
異常,這種情況只需要socket連接主機ip和port,然后捕獲對應的異常進行處理即可。
只需要針對連接過程中會拋出ConnectionRefusedError
異常進行處理
主機不通
這種情況,socket會一直嘗試連接,針對這種情況設置一個超時時間,會拋出socket.timeout
的異常,捕獲該異常進行處理即可
只需要針對連接過程中會拋出socket.timeout
異常進行處理
代碼邏輯如下:
#!/usr/bin/python3
# -*-encoding: utf8 -*-
import socket
Buffer_ = 1024
def write_ip_port(file_name, host, ports):
"""
文件操作,生成對應的記錄文件
:param file_name: 生成的文件名
:param host: 主機IP
:param ports: 主機端口
:return:
"""
with open('./%s' % file_name, mode='a+', encoding='utf8') as file_handler:
file_handler.write("%s\t%s\n" % (host, ports))
def connection_host(host, port):
"""
測試防火牆是否開通
:param host: 主機ip
:param port: 主機端口
:return:
"""
cli = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
cli.settimeout(1)
try:
"""
處理正常連接
"""
cli.connect((host, int(port)))
cli.close()
file = 'successful.txt'
write_ip_port(file, host, port)
except ConnectionRefusedError as cre:
"""
處理端口關閉
"""
# print(cre)
file = 'ConnectionRefusedError.txt'
write_ip_port(file, host, port)
except socket.timeout as scto:
"""
處理主機不通
"""
# print(scto)
file = "failed.txt"
write_ip_port(file, host, port)
def read_ip_list(file_name):
"""
讀取ipList.txt文件中的ip和端口,添加到ip_list列表中
"""
ip_list = []
with open('./%s' % file_name, mode='r', encoding='utf8') as file_handle:
for line in file_handle.readlines():
line = line.replace("\n", '').strip()
if line is '':
continue
line = line.split(' ')
ip_list.append(line)
return ip_list
def main(file):
"""
主程序入口
:param file: ip和端口的文件名,及其為路徑,默認是當前路徑
:return:
"""
ip_list = read_ip_list(file)
for ip_port in ip_list:
connection_host(ip_port[0], ip_port[1])
if __name__ == '__main__':
main("ipList.txt")