Created
October 23, 2025 04:43
-
-
Save nopeless/258a2f9df1114086baedca8072bbc3c4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # courtesy of chatgpt | |
| import csv | |
| from tabulate import tabulate | |
| import re | |
| # you need to download this file from the official iana website | |
| CSV_FILE = "service-names-port-numbers.csv" | |
| MAX_WIDTH = 80 # maximum width for displayed fields | |
| def clean_text(text): | |
| """Replace newlines with '. ', collapse spaces, and truncate.""" | |
| if text is None: | |
| return "" | |
| # Normalize whitespace and replace newlines | |
| text = re.sub(r'[\r\n]+', '. ', str(text)) | |
| text = re.sub(r'\s+', ' ', text).strip() | |
| # Truncate if needed | |
| return text if len(text) <= MAX_WIDTH else text[:MAX_WIDTH - 3] + "..." | |
| def load_ports(filename): | |
| ports = [] | |
| with open(filename, newline='', encoding='utf-8') as f: | |
| reader = csv.DictReader(f) | |
| for row in reader: | |
| try: | |
| row['Port Number'] = int(row['Port Number']) | |
| except ValueError: | |
| continue | |
| ports.append(row) | |
| return ports | |
| def query_ports(ports, query): | |
| query = query.strip() | |
| if '-' in query: | |
| try: | |
| start, end = map(int, query.split('-', 1)) | |
| except ValueError: | |
| print("❌ Invalid range format. Use e.g. 20-25.") | |
| return [] | |
| result = {} | |
| for p in ports: | |
| num = p['Port Number'] | |
| if start <= num <= end and num not in result: | |
| result[num] = p | |
| return list(result.values()) | |
| else: | |
| try: | |
| port = int(query) | |
| except ValueError: | |
| print("❌ Invalid port number.") | |
| return [] | |
| return [p for p in ports if p['Port Number'] == port] | |
| def display_results(results): | |
| if not results: | |
| print("No matches found.") | |
| return | |
| table = [ | |
| [ | |
| r['Port Number'], | |
| clean_text(r['Service Name']), | |
| clean_text(r['Description']), | |
| clean_text(r['Assignment Notes']) | |
| ] | |
| for r in results | |
| ] | |
| print(tabulate( | |
| table, | |
| headers=["Port", "Service Name", "Description", "Assignment Notes"], | |
| tablefmt="github" | |
| )) | |
| def main(): | |
| print("Loading port data...") | |
| ports = load_ports(CSV_FILE) | |
| print(f"Loaded {len(ports)} entries.") | |
| print("Enter a port number (e.g., 80) or range (e.g., 20-25). Type 'exit' to quit.") | |
| while True: | |
| query = input("Query> ").strip() | |
| if query.lower() in ('exit', 'quit'): | |
| break | |
| results = query_ports(ports, query) | |
| display_results(results) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment