netadm/scripts/check_available_ports.py

55 lines
1.5 KiB
Python
Raw Normal View History

2024-10-01 11:29:39 +00:00
import socket
import re
from typing import List, Dict, Union
import logging
def check_conn(ip: str, port: int) -> bool:
logging.info("")
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn.settimeout(3)
try:
conn.connect((ip, port))
logging.info(f"{ip}:{port} - True")
return True
except TimeoutError:
logging.warning(f"{ip}:{port} - Timeout")
return False
def parse_input(text: str) -> List[Dict[str, Union[int, str]]]:
logging.info("")
pattern = r"Error;.*?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d+)/(\w+)"
matches = re.findall(pattern, text)
result = [
{"ip": match[0], "port": int(match[1]), "protocol": match[2]}
for match in matches
]
return result
2024-10-01 14:09:19 +00:00
def start_check(
2024-10-01 15:06:04 +00:00
text: str,
result_type: str = "json",
2024-10-01 14:09:19 +00:00
) -> List[Dict[str, Union[int, str, bool]]] | List[str]:
2024-10-01 11:29:39 +00:00
logging.info("")
result = []
for i in parse_input(text):
if i["protocol"] == "tcp":
if check_conn(i["ip"], i["port"]):
i["result"] = True
result.append(i)
else:
i["result"] = False
result.append(i)
2024-10-01 14:09:19 +00:00
2024-10-01 15:08:22 +00:00
if result_type == "text":
2024-10-01 14:09:19 +00:00
results = []
for i in result:
if i["result"]:
results.append(f"{i['ip']}:{i['port']}/{i['protocol']} - OK")
else:
results.append(f"{i['ip']}:{i['port']}/{i['protocol']} - FAIL")
return results
2024-10-01 11:29:39 +00:00
return result