1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| import socket import time
def telnet_check(host, port, timeout=1): """ 基于socket检测主机端口是否可通(替代telnetlib) :param host: 目标主机(IP或域名) :param port: 目标端口(整数) :param timeout: 超时时间(秒),默认1秒 :return: 布尔值 -> True(通)/ False(不通) """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.settimeout(timeout) sock.connect((host, port)) return True except (socket.timeout, ConnectionRefusedError, socket.gaierror, OSError): return False finally: sock.close()
def batch_scan(targets, timeout=1): """ 批量探测目标列表,不通则继续下一个 :param targets: 目标列表,格式为 [(host1, port1), (host2, port2), ...] :param timeout: 单个目标超时时间(秒) """ print(f"=== Telnet端口批量探测(超时{timeout}秒)===\n") total = len(targets) for index, (host, port) in enumerate(targets, 1): print(f"[{index}/{total}] 探测中:{host}:{port}") start_time = time.time() is_open = telnet_check(host, port, timeout) cost_time = round(time.time() - start_time, 4) status = "通" if is_open else "不通" print(f"[{index}/{total}] 结果:{host}:{port} {status}(耗时:{cost_time}秒)\n")
if __name__ == "__main__": target_list = [ ("192.168.1.1", 443), ("192.168.1.2", 443), ("192.168.1.3", 443), ] batch_scan(target_list, timeout=1) print("=== 所有目标探测完成 ===")
|