Advertisement
Python253

is_port_open

Apr 5th, 2024
521
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.21 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: is_port_open.py
  4. # Version: 1.00
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. This script enables users to check for open ports and listen on a specific port if desired.
  9.  
  10. Functions:
  11.    - get_ports_in_use(): Retrieves a dictionary of ports currently in use along with associated process information.
  12.    - list_ports_in_use(ports_in_use): Displays the list of ports in use along with their associated processes.
  13.    - prompt_user_to_save_data(ports_in_use): Prompts the user whether to save the ports in use data to a file named 'inuse.txt'.
  14.    - prompt_user_for_port(): Prompts the user to enter the port number they want to listen on.
  15.    - listen_on_port(selected_port): Listens on the selected port for incoming connections and displays received data.
  16.    - save_selected_port_data(selected_port, ports_in_use): Saves the data associated with the selected port to a file.
  17.  
  18. Features:
  19.    - Retrieves a list of ports currently in use on the local system along with associated process information.
  20.    - Displays the list of ports in use, providing process details for each port.
  21.    - Allows the user to save the ports in use data to a text file for further analysis.
  22.    - Prompts the user to select a port to listen on, then listens on that port for incoming connections.
  23.    - Saves data related to the selected port to a text file for reference.
  24.  
  25. Requirements:
  26.    - Python 3.x
  27.    - psutil library (install via pip: pip install psutil)
  28.  
  29. Usage:
  30.    1. Ensure Python 3.x is installed on your system.
  31.    2. Install the psutil library by running: pip install psutil
  32.    3. Save the script as 'is_port_open.py'.
  33.    4. Execute the script using the command: python is_port_open.py
  34.    5. Follow the prompts to view ports in use, select a port to listen on, and save data if desired.
  35.  
  36. Notes:
  37.    - This script retrieves information about ports in use and listens for incoming connections on the local system.
  38.    - It may require elevated privileges to gather process information depending on the system's security settings.
  39.    - The 'inuse.txt' file will be created in the same directory as the script if the user chooses to save data.
  40.    - Ensure to review the contents of the saved data files, as they may contain sensitive information.
  41. """
  42.  
  43. import psutil
  44. import socket
  45.  
  46. # Function to get the list of ports in use
  47. def get_ports_in_use():
  48.     """
  49.    Retrieves a dictionary of ports currently in use along with associated process information.
  50.  
  51.    Returns:
  52.        dict: A dictionary containing port numbers as keys and sets of process information tuples as values.
  53.    """
  54.     ports_in_use = {}
  55.     for conn in psutil.net_connections():
  56.         if conn.laddr.port not in ports_in_use:
  57.             ports_in_use[conn.laddr.port] = set()
  58.         if conn.pid is None:
  59.             process = {'pid': -1, 'name': 'UNKNOWN', 'program': 'UNKNOWN'}
  60.         else:
  61.             try:
  62.                 cmdline = psutil.Process(conn.pid).cmdline()
  63.                 program = ' '.join(cmdline) if cmdline else 'UNKNOWN'
  64.                 process = {'pid': conn.pid, 'name': psutil.Process(conn.pid).name(), 'program': program}
  65.             except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
  66.                 process = {'pid': conn.pid, 'name': 'UNKNOWN', 'program': 'UNKNOWN'}
  67.         ports_in_use[conn.laddr.port].add((process['pid'], process['name'], process['program']))
  68.     return ports_in_use
  69.  
  70. # Function to list ports in use
  71. def list_ports_in_use(ports_in_use):
  72.     """
  73.    Displays the list of ports in use along with their associated processes.
  74.  
  75.    Args:
  76.        ports_in_use (dict): A dictionary containing port numbers as keys and sets of process information tuples as values.
  77.    """
  78.     for port, processes in sorted(ports_in_use.items()):
  79.         print("\n" + "-" * 40)
  80.         for process in processes:
  81.             pid, name, program = process
  82.             if name == 'svchost.exe' and program == 'UNKNOWN':
  83.                 print(f"\n{name}")
  84.             else:
  85.                 print(f"\n{name}")
  86.                 print(f"Port: {port}, PID: {pid}    {program}")
  87.  
  88. # Function to prompt user to save data
  89. def prompt_user_to_save_data(ports_in_use):
  90.     """
  91.    Prompts the user whether to save the ports in use data to a file named 'inuse.txt'.
  92.  
  93.    Args:
  94.        ports_in_use (dict): A dictionary containing port numbers as keys and sets of process information tuples as values.
  95.    """
  96.     while True:
  97.         save_data = input("\nDo you want to save the ports in use data to 'inuse.txt'?\n1: YES\n2: NO\n(Enter your option number): ").strip().lower()
  98.         if save_data == '1':
  99.             with open('inuse.txt', 'w') as file:
  100.                 for port, processes in sorted(ports_in_use.items()):  
  101.                     for process in processes:
  102.                         pid, name, program = process
  103.                         file.write(f"\n{name}\n")
  104.                         file.write(f"Port: {port}, PID: {pid}    {program}\n")
  105.             print("Ports in use data saved to 'inuse.txt'.")
  106.             break
  107.         elif save_data == '2':
  108.             break
  109.         else:
  110.             print("Invalid input. Please enter '1' for YES or '2' for NO.")
  111.  
  112. # Function to prompt user for port to listen on
  113. def prompt_user_for_port():
  114.     """
  115.    Prompts the user to enter the port number they want to listen on.
  116.  
  117.    Returns:
  118.        int: The port number selected by the user.
  119.    """
  120.     while True:
  121.         selected_port = input("Enter the port number you want to listen on: ")
  122.         try:
  123.             selected_port = int(selected_port)
  124.             if selected_port < 1 or selected_port > 65535:
  125.                 raise ValueError("Invalid port number.")
  126.             return selected_port
  127.         except ValueError:
  128.             print("Invalid input. Please enter a valid port number.")
  129.  
  130. # Function to listen on the selected port
  131. def listen_on_port(selected_port):
  132.     """
  133.    Listens on the selected port for incoming connections and displays received data.
  134.  
  135.    Args:
  136.        selected_port (int): The port number to listen on.
  137.    """
  138.     try:
  139.         with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  140.             s.bind(('127.0.0.1', selected_port))
  141.             print(f"Listening on port {selected_port}...")
  142.             s.listen(1)
  143.             conn, addr = s.accept()
  144.             with conn:
  145.                 print('Connected by', addr)
  146.                 while True:
  147.                     data = conn.recv(1024)
  148.                     if not data:
  149.                         break
  150.                     print(f"Received data: {data.decode('utf-8')}")
  151.     except OSError as e:
  152.         print(f"Failed to listen on port {selected_port}: {e}")
  153.  
  154. # Function to save data for the selected port
  155. def save_selected_port_data(selected_port, ports_in_use):
  156.     """
  157.    Saves the data associated with the selected port to a file.
  158.  
  159.    Args:
  160.        selected_port (int): The port number selected by the user.
  161.        ports_in_use (dict): A dictionary containing port numbers as keys and sets of process information tuples as values.
  162.    """
  163.     try:
  164.         with open(f'port_{selected_port}_data.txt', 'w') as file:
  165.             file.write(f"Port {selected_port}:\n")
  166.             for process in ports_in_use.get(selected_port, []):
  167.                 pid, name, program = process
  168.                 file.write(f"PID: {pid}\nProcess: {name}\nProgram: {program}\n\n")
  169.         print(f"Data for port {selected_port} saved to 'port_{selected_port}_data.txt'.")
  170.     except Exception as e:
  171.         print(f"Failed to save data for port {selected_port}: {e}")
  172.  
  173. # Main function
  174. def main():
  175.     """
  176.    Main function to execute the script.
  177.    """
  178.     # Get ports in use
  179.     ports_in_use = get_ports_in_use()
  180.  
  181.     # List ports in use
  182.     list_ports_in_use(ports_in_use)
  183.  
  184.     # Prompt user to save ports in use data
  185.     prompt_user_to_save_data(ports_in_use)
  186.  
  187.     # Prompt user for port to listen on
  188.     selected_port = prompt_user_for_port()
  189.     print(f"Selected port: {selected_port}")
  190.  
  191.     # Save data for the selected port
  192.     save_selected_port_data(selected_port, ports_in_use)
  193.  
  194.     # Listen on the selected port
  195.     listen_on_port(selected_port)
  196.  
  197. if __name__ == "__main__":
  198.     main()
  199.  
  200.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement