Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # Filename: portscan.py
- # Version: 1.00
- # Author: Jeoi Reqi
- """
- This script provides functionality to scan for ports currently in use on the local system along with associated process details.
- Functions:
- - get_ports_in_use(): Retrieves a list of ports currently in use along with associated process details.
- - get_process_name(pid): Retrieves the process name associated with a given process ID (PID).
- - display_ports_in_use(ports_in_use): Displays the list of ports currently in use along with their associated processes and programs.
- Features:
- - Uses the 'netstat' command-line utility to retrieve a list of ports in use with process details.
- - Parses the output of 'netstat' to extract port numbers, PIDs, and process names.
- - Utilizes the psutil library to retrieve process names based on PIDs for enhanced process details.
- - Displays the list of ports currently in use with detailed process and program information in a formatted table.
- Requirements:
- - Python 3.x
- - psutil library (install via pip: pip install psutil)
- Usage:
- 1. Ensure Python 3.x is installed on your system.
- 2. Install the psutil library by running: pip install psutil
- 3. Save the script as 'portscan.py'.
- 4. Execute the script using the command: python portscan.py
- 5. The script will display the ports currently in use along with associated process details.
- Notes:
- - This script relies on the 'netstat' command-line utility to retrieve information about ports in use.
- - It may require elevated privileges to execute certain commands, depending on the system's security settings.
- - The psutil library is used to retrieve process names based on process IDs (PIDs) for enhanced process details.
- - Ensure to review the output carefully, as it may contain sensitive information about processes and network connections.
- """
- import subprocess
- import psutil
- import logging
- # Configure logging
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
- # Function to get ports currently in use along with process details
- def get_ports_in_use():
- """
- Retrieves a list of ports currently in use along with associated process details.
- Returns:
- list: A list of tuples containing port numbers, process IDs (PIDs), and process names.
- """
- try:
- # Use netstat command to get list of ports in use with process details
- result = subprocess.run(['netstat', '-a', '-n', '-o', '-p', 'TCP'], capture_output=True, text=True)
- output = result.stdout
- lines = output.split('\n')
- # Parse output to extract ports in use along with process details
- ports_in_use = []
- for line in lines[4:]:
- parts = line.split()
- if len(parts) >= 5:
- local_address = parts[1]
- port = local_address.split(':')[-1]
- pid = parts[-1]
- process_name = parts[-2]
- ports_in_use.append((int(port), int(pid), process_name))
- return ports_in_use
- except Exception as e:
- logging.error(f"Error retrieving ports in use: {e}")
- return []
- # Function to get process name from PID
- def get_process_name(pid):
- """
- Retrieves the process name associated with a given process ID (PID).
- Args:
- pid (int): The process ID (PID) of the target process.
- Returns:
- str: The name of the process associated with the given PID, or 'N/A' if not found.
- """
- try:
- process = psutil.Process(pid)
- return process.name()
- except psutil.NoSuchProcess:
- return "N/A"
- except Exception as e:
- logging.error(f"Error retrieving process name for PID {pid}: {e}")
- return "N/A"
- # Display ports in use with process details
- def display_ports_in_use(ports_in_use):
- """
- Displays the list of ports currently in use along with their associated processes and programs.
- Args:
- ports_in_use (list): A list of tuples containing port numbers, process IDs (PIDs), and process names.
- """
- if ports_in_use:
- print("Ports currently in use:")
- print("{:<10} {:<10} {:<20} {:<30}".format("Port #", "PID", "Process", "Program"))
- for port, pid, process_name in ports_in_use:
- program_name = get_process_name(pid)
- print("{:<10} {:<10} {:<20} {:<30}".format(port, pid, process_name, program_name))
- else:
- print("No ports currently in use.")
- # Get ports currently in use with process details
- used_ports = get_ports_in_use()
- # Display ports in use with process details
- display_ports_in_use(used_ports)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement