Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # Filename: is_port_open.py
- # Version: 1.00
- # Author: Jeoi Reqi
- """
- This script enables users to check for open ports and listen on a specific port if desired.
- Functions:
- - get_ports_in_use(): Retrieves a dictionary of ports currently in use along with associated process information.
- - list_ports_in_use(ports_in_use): Displays the list of ports in use along with their associated processes.
- - 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'.
- - prompt_user_for_port(): Prompts the user to enter the port number they want to listen on.
- - listen_on_port(selected_port): Listens on the selected port for incoming connections and displays received data.
- - save_selected_port_data(selected_port, ports_in_use): Saves the data associated with the selected port to a file.
- Features:
- - Retrieves a list of ports currently in use on the local system along with associated process information.
- - Displays the list of ports in use, providing process details for each port.
- - Allows the user to save the ports in use data to a text file for further analysis.
- - Prompts the user to select a port to listen on, then listens on that port for incoming connections.
- - Saves data related to the selected port to a text file for reference.
- 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 'is_port_open.py'.
- 4. Execute the script using the command: python is_port_open.py
- 5. Follow the prompts to view ports in use, select a port to listen on, and save data if desired.
- Notes:
- - This script retrieves information about ports in use and listens for incoming connections on the local system.
- - It may require elevated privileges to gather process information depending on the system's security settings.
- - The 'inuse.txt' file will be created in the same directory as the script if the user chooses to save data.
- - Ensure to review the contents of the saved data files, as they may contain sensitive information.
- """
- import psutil
- import socket
- # Function to get the list of ports in use
- def get_ports_in_use():
- """
- Retrieves a dictionary of ports currently in use along with associated process information.
- Returns:
- dict: A dictionary containing port numbers as keys and sets of process information tuples as values.
- """
- ports_in_use = {}
- for conn in psutil.net_connections():
- if conn.laddr.port not in ports_in_use:
- ports_in_use[conn.laddr.port] = set()
- if conn.pid is None:
- process = {'pid': -1, 'name': 'UNKNOWN', 'program': 'UNKNOWN'}
- else:
- try:
- cmdline = psutil.Process(conn.pid).cmdline()
- program = ' '.join(cmdline) if cmdline else 'UNKNOWN'
- process = {'pid': conn.pid, 'name': psutil.Process(conn.pid).name(), 'program': program}
- except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
- process = {'pid': conn.pid, 'name': 'UNKNOWN', 'program': 'UNKNOWN'}
- ports_in_use[conn.laddr.port].add((process['pid'], process['name'], process['program']))
- return ports_in_use
- # Function to list ports in use
- def list_ports_in_use(ports_in_use):
- """
- Displays the list of ports in use along with their associated processes.
- Args:
- ports_in_use (dict): A dictionary containing port numbers as keys and sets of process information tuples as values.
- """
- for port, processes in sorted(ports_in_use.items()):
- print("\n" + "-" * 40)
- for process in processes:
- pid, name, program = process
- if name == 'svchost.exe' and program == 'UNKNOWN':
- print(f"\n{name}")
- else:
- print(f"\n{name}")
- print(f"Port: {port}, PID: {pid} {program}")
- # Function to prompt user to save data
- def 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'.
- Args:
- ports_in_use (dict): A dictionary containing port numbers as keys and sets of process information tuples as values.
- """
- while True:
- 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()
- if save_data == '1':
- with open('inuse.txt', 'w') as file:
- for port, processes in sorted(ports_in_use.items()):
- for process in processes:
- pid, name, program = process
- file.write(f"\n{name}\n")
- file.write(f"Port: {port}, PID: {pid} {program}\n")
- print("Ports in use data saved to 'inuse.txt'.")
- break
- elif save_data == '2':
- break
- else:
- print("Invalid input. Please enter '1' for YES or '2' for NO.")
- # Function to prompt user for port to listen on
- def prompt_user_for_port():
- """
- Prompts the user to enter the port number they want to listen on.
- Returns:
- int: The port number selected by the user.
- """
- while True:
- selected_port = input("Enter the port number you want to listen on: ")
- try:
- selected_port = int(selected_port)
- if selected_port < 1 or selected_port > 65535:
- raise ValueError("Invalid port number.")
- return selected_port
- except ValueError:
- print("Invalid input. Please enter a valid port number.")
- # Function to listen on the selected port
- def listen_on_port(selected_port):
- """
- Listens on the selected port for incoming connections and displays received data.
- Args:
- selected_port (int): The port number to listen on.
- """
- try:
- with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
- s.bind(('127.0.0.1', selected_port))
- print(f"Listening on port {selected_port}...")
- s.listen(1)
- conn, addr = s.accept()
- with conn:
- print('Connected by', addr)
- while True:
- data = conn.recv(1024)
- if not data:
- break
- print(f"Received data: {data.decode('utf-8')}")
- except OSError as e:
- print(f"Failed to listen on port {selected_port}: {e}")
- # Function to save data for the selected port
- def save_selected_port_data(selected_port, ports_in_use):
- """
- Saves the data associated with the selected port to a file.
- Args:
- selected_port (int): The port number selected by the user.
- ports_in_use (dict): A dictionary containing port numbers as keys and sets of process information tuples as values.
- """
- try:
- with open(f'port_{selected_port}_data.txt', 'w') as file:
- file.write(f"Port {selected_port}:\n")
- for process in ports_in_use.get(selected_port, []):
- pid, name, program = process
- file.write(f"PID: {pid}\nProcess: {name}\nProgram: {program}\n\n")
- print(f"Data for port {selected_port} saved to 'port_{selected_port}_data.txt'.")
- except Exception as e:
- print(f"Failed to save data for port {selected_port}: {e}")
- # Main function
- def main():
- """
- Main function to execute the script.
- """
- # Get ports in use
- ports_in_use = get_ports_in_use()
- # List ports in use
- list_ports_in_use(ports_in_use)
- # Prompt user to save ports in use data
- prompt_user_to_save_data(ports_in_use)
- # Prompt user for port to listen on
- selected_port = prompt_user_for_port()
- print(f"Selected port: {selected_port}")
- # Save data for the selected port
- save_selected_port_data(selected_port, ports_in_use)
- # Listen on the selected port
- listen_on_port(selected_port)
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement