python3 版- import socket
- import pathlib
- import subprocess
-
-
- class IpTest(object):
-
- def __init__(self, ip_address_file:pathlib.Path, res_file:pathlib.Path) -> None:
-
- self.ip_address_file = ip_address_file
- self.ping_res_file = res_file
- self.ip_address_list = []
-
- def load_ip_address(self) -> None:
-
- self.ip_address_list.clear()
- with self.ip_address_file.open() as f:
- for ip in f.readlines():
- self.ip_address_list.append(ip.strip())
-
- def run_ip_test(self) -> None:
-
- pass
-
-
- class PingIP(IpTest):
-
- def __init__(self, ip_address_file: pathlib.Path, res_file: pathlib.Path) -> None:
- super().__init__(ip_address_file, res_file)
-
- def run_ip_test(self) -> None:
-
- res_file = self.ping_res_file.name
- if self.ping_res_file.exists():
- self.ping_res_file.unlink()
- for ip in self.ip_address_list:
-
- print(f"start: ping {ip} -n 2 >> {res_file}")
- subprocess.run(f"ping {ip} -n 2 >> {res_file}", shell=True)
- print(f"done: ping {ip} -n 2 >> {res_file}")
-
-
- class Telnent(IpTest):
-
- def __init__(self, ip_address_file: pathlib.Path, res_file: pathlib.Path) -> None:
- super().__init__(ip_address_file, res_file)
-
- @staticmethod
- def connect_ip(ip:str, port:int) -> bool:
-
- sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- sck.settimeout(2) # 2 second
- try:
- sck.connect((ip,port))
- except:
- return False
- finally:
- sck.close()
- return True
-
-
- def run_ip_test(self) -> None:
-
- ip_ino:str
- with self.ping_res_file.open("w") as f:
- for ip_ino in self.ip_address_list:
- print(f"正在连接:{ip_ino}")
- ip,port = ip_ino.split(" ")
- if self.connect_ip(ip,int(port)):
- f.write(f"{ip_ino}端口正常\n")
- else:
- f.write(f"{ip_ino}端口异常\n")
-
-
-
- if __name__ == "__main__":
-
-
- p_set = []
- p_set.append(PingIP(pathlib.Path("ip_list.txt"), pathlib.Path("ping_result.txt")))
- p_set.append(Telnent(pathlib.Path("port_list.txt"), pathlib.Path("Telnent_result.txt")))
- for p in p_set:
- p.load_ip_address()
- p.run_ip_test()
复制代码
|