Advertisement
Python253

portscan

Apr 5th, 2024
536
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.69 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: portscan.py
  4. # Version: 1.00
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. This script provides functionality to scan for ports currently in use on the local system along with associated process details.
  9.  
  10. Functions:
  11.    - get_ports_in_use(): Retrieves a list of ports currently in use along with associated process details.
  12.    - get_process_name(pid): Retrieves the process name associated with a given process ID (PID).
  13.    - display_ports_in_use(ports_in_use): Displays the list of ports currently in use along with their associated processes and programs.
  14.  
  15. Features:
  16.    - Uses the 'netstat' command-line utility to retrieve a list of ports in use with process details.
  17.    - Parses the output of 'netstat' to extract port numbers, PIDs, and process names.
  18.    - Utilizes the psutil library to retrieve process names based on PIDs for enhanced process details.
  19.    - Displays the list of ports currently in use with detailed process and program information in a formatted table.
  20.  
  21. Requirements:
  22.    - Python 3.x
  23.    - psutil library (install via pip: pip install psutil)
  24.  
  25. Usage:
  26.    1. Ensure Python 3.x is installed on your system.
  27.    2. Install the psutil library by running: pip install psutil
  28.    3. Save the script as 'portscan.py'.
  29.    4. Execute the script using the command: python portscan.py
  30.    5. The script will display the ports currently in use along with associated process details.
  31.  
  32. Notes:
  33.    - This script relies on the 'netstat' command-line utility to retrieve information about ports in use.
  34.    - It may require elevated privileges to execute certain commands, depending on the system's security settings.
  35.    - The psutil library is used to retrieve process names based on process IDs (PIDs) for enhanced process details.
  36.    - Ensure to review the output carefully, as it may contain sensitive information about processes and network connections.
  37. """
  38.  
  39. import subprocess
  40. import psutil
  41. import logging
  42.  
  43. # Configure logging
  44. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  45.  
  46. # Function to get ports currently in use along with process details
  47. def get_ports_in_use():
  48.     """
  49.    Retrieves a list of ports currently in use along with associated process details.
  50.  
  51.    Returns:
  52.        list: A list of tuples containing port numbers, process IDs (PIDs), and process names.
  53.    """
  54.     try:
  55.         # Use netstat command to get list of ports in use with process details
  56.         result = subprocess.run(['netstat', '-a', '-n', '-o', '-p', 'TCP'], capture_output=True, text=True)
  57.         output = result.stdout
  58.         lines = output.split('\n')
  59.  
  60.         # Parse output to extract ports in use along with process details
  61.         ports_in_use = []
  62.         for line in lines[4:]:
  63.             parts = line.split()
  64.             if len(parts) >= 5:
  65.                 local_address = parts[1]
  66.                 port = local_address.split(':')[-1]
  67.                 pid = parts[-1]
  68.                 process_name = parts[-2]
  69.                 ports_in_use.append((int(port), int(pid), process_name))
  70.         return ports_in_use
  71.     except Exception as e:
  72.         logging.error(f"Error retrieving ports in use: {e}")
  73.         return []
  74.  
  75. # Function to get process name from PID
  76. def get_process_name(pid):
  77.     """
  78.    Retrieves the process name associated with a given process ID (PID).
  79.  
  80.    Args:
  81.        pid (int): The process ID (PID) of the target process.
  82.  
  83.    Returns:
  84.        str: The name of the process associated with the given PID, or 'N/A' if not found.
  85.    """
  86.     try:
  87.         process = psutil.Process(pid)
  88.         return process.name()
  89.     except psutil.NoSuchProcess:
  90.         return "N/A"
  91.     except Exception as e:
  92.         logging.error(f"Error retrieving process name for PID {pid}: {e}")
  93.         return "N/A"
  94.  
  95. # Display ports in use with process details
  96. def display_ports_in_use(ports_in_use):
  97.     """
  98.    Displays the list of ports currently in use along with their associated processes and programs.
  99.  
  100.    Args:
  101.        ports_in_use (list): A list of tuples containing port numbers, process IDs (PIDs), and process names.
  102.    """
  103.     if ports_in_use:
  104.         print("Ports currently in use:")
  105.         print("{:<10} {:<10} {:<20} {:<30}".format("Port #", "PID", "Process", "Program"))
  106.         for port, pid, process_name in ports_in_use:
  107.             program_name = get_process_name(pid)
  108.             print("{:<10} {:<10} {:<20} {:<30}".format(port, pid, process_name, program_name))
  109.     else:
  110.         print("No ports currently in use.")
  111.  
  112. # Get ports currently in use with process details
  113. used_ports = get_ports_in_use()
  114.  
  115. # Display ports in use with process details
  116. display_ports_in_use(used_ports)
  117.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement