Advertisement
Python253

is_listening

Apr 5th, 2024
604
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.24 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: is_listening.py
  4. # Version: 1.00
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. This script retrieves information about listening ports and their associated processes on a local system.
  9. It utilizes the psutil library to gather network connection data and process information.
  10.  
  11. Functions:
  12.    - get_listening_ports(): Retrieves information about listening ports and their associated processes.
  13.    
  14. Features:
  15.    - Retrieves listening ports and their associated process information (PID, user, command, start time, memory usage, CPU usage).
  16.    - Handles cases where process information cannot be retrieved due to permissions or non-existent processes.
  17.    - Groups the retrieved data with a space between each group for better readability.
  18.    - Prompts the user whether to save the data to a file named 'listening_ports.txt'.
  19.    - Provides error handling for file writing operations.
  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 'is_listening.py'.
  29.    4. Execute the script using the command: python is_listening.py
  30.    5. Follow the prompts to view the listening ports and optionally save the data to a file.
  31.  
  32. Notes:
  33.    - This script retrieves information about listening ports and associated processes on the local system only.
  34.    - It may require elevated privileges to gather process information depending on the system's security settings.
  35.    - The 'listening_ports.txt' file will be created in the same directory as the script.
  36.    - Ensure to review the contents of the 'listening_ports.txt' file, as it may contain sensitive information.
  37.  
  38. """
  39.  
  40. import psutil
  41.  
  42. # Define a function to get the list of listening ports with additional process information
  43. def get_listening_ports():
  44.     # Get all connections
  45.     connections = psutil.net_connections(kind='inet')
  46.     listening_ports = []
  47.     grouped_data = []
  48.  
  49.     # Iterate over the connections
  50.     for conn in connections:
  51.         # Check if the connection is listening
  52.         if conn.status == 'LISTEN':
  53.             # Extract port number and process ID (PID)
  54.             port = conn.laddr.port
  55.             pid = conn.pid
  56.  
  57.             # Fetch process information
  58.             try:
  59.                 process = psutil.Process(pid)
  60.                 user = process.username()
  61.                 command = process.cmdline()
  62.                 start_time = process.create_time()
  63.                 memory_percent = process.memory_percent()
  64.                 cpu_percent = process.cpu_percent()
  65.  
  66.                 # Append the collected information to the list
  67.                 listening_ports.append(
  68.                     f"Port: {port}\nPID: {pid}\nUser: {user}\nCommand: {command}\nStart Time: {start_time}\nMemory Usage: {memory_percent}%\nCPU Usage: {cpu_percent}%\n")
  69.             except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
  70.                 # If process information cannot be retrieved, append N/A
  71.                 listening_ports.append(
  72.                     f"Port: {port}\nPID: {pid}\nUser: N/A\nCommand: N/A\nStart Time: N/A\nMemory Usage: N/A\nCPU Usage: N/A\n")
  73.  
  74.     # Group the data with a space between each group
  75.     for i in range(0, len(listening_ports), 2):
  76.         grouped_data.append('\n'.join(listening_ports[i:i+2]))
  77.  
  78.     # Print the grouped data
  79.     print('\n\n'.join(grouped_data))
  80.  
  81.     # Prompt the user whether to save the data to a file
  82.     save_to_file = input("\nDo you want to save the data to 'listening_ports.txt'?\nOPTIONS:\n1: YES\n2: NO\nMake Your Selection (1 or 2): ").strip().lower()
  83.     if save_to_file == '1':
  84.         try:
  85.             with open('listening_ports.txt', 'w') as file:
  86.                 file.write('\n\n'.join(grouped_data))
  87.             print("Data saved to 'listening_ports.txt'.")
  88.         except Exception as e:
  89.             print(f"Failed to save data: {e}")
  90.     elif save_to_file == '2':
  91.         print("Data not saved.")
  92.     else:
  93.         print("Invalid input. Data not saved.")
  94.  
  95. # Call the function to print the listening ports and prompt the user to save the data to a file
  96. get_listening_ports()
  97.  
  98.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement