Ein Python Script welcher mit dem Parameter -u die betroffenen Benutzer auflistet und die Option bietet mit - root nur die offenen Ports bzw. deren Programm des Benutzers anzuzeigen. Der Script ist für Python >3.7 unter Ubuntu gedacht.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import subprocess
import re
import argparse
# ANSI Farbcodes
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
RESET = '\033[0m'
def colorize(text, color):
return f"{color}{text}{RESET}"
def get_listening_ports(filter_user=None):
# Ausführen des netstat-Befehls
result = subprocess.run(['netstat', '-tulnp'], stdout=subprocess.PIPE, text=True)
output = result.stdout
# Extrahieren von PID/Programmname/Port aus der netstat-Ausgabe
pattern = re.compile(r'tcp.*?:(\d+)\s+.*?(\d+)/([a-zA-Z0-9]+)')
ports_info = pattern.findall(output)
filtered_ports_info = []
for port, pid, program in ports_info:
try:
user = subprocess.run(['ps', '-o', 'user=', '-p', pid], stdout=subprocess.PIPE, text=True).stdout.strip()
if filter_user and user != filter_user:
continue
filtered_ports_info.append((pid, port, program, user))
except subprocess.CalledProcessError:
continue
return filtered_ports_info
def get_command_line(pid):
# Ausführen des ps-Befehls, um die Kommandozeile für die gegebene PID zu erhalten
result = subprocess.run(['ps', '-p', pid, '-o', 'cmd'], stdout=subprocess.PIPE, text=True)
output = result.stdout.strip().split('\n')
return output[1] if len(output) > 1 else output[0]
def main():
parser = argparse.ArgumentParser(description='List open ports and associated command lines.')
parser.add_argument('-u', '--user', help='Filter by user or list users with open ports')
args = parser.parse_args()
ports_info = get_listening_ports(filter_user=args.user)
for pid, port, program, user in ports_info:
cmd_line = get_command_line(pid)
print(f"{colorize('User:', YELLOW)} {user}, {colorize('Program:', GREEN)} {program}, {colorize('PID:', RED)} {pid}, {colorize('Port:', BLUE)} {port}, {colorize('Command Line:', MAGENTA)} {cmd_line}")
if __name__ == "__main__":
main()
Kommentare