Advertisement
DrAungWinHtut

network_basic.py

Feb 2nd, 2024
939
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.83 KB | None | 0 0
  1. import socket
  2. import requests
  3. import subprocess
  4.  
  5. def get_local_ip():
  6.     try:
  7.         # Get the hostname of the local machine
  8.         host_name = socket.gethostname()        
  9.         # Get the IP address corresponding to the hostname
  10.         ip_address = socket.gethostbyname(host_name)
  11.         print(f"IP Address of {host_name}: {ip_address}")
  12.     except socket.error as e:
  13.         print(f"Error: {e}")
  14.  
  15.  
  16.  
  17. def get_public_ip():
  18.     try:
  19.         # Use an external service to get the public IP address
  20.         response = requests.get('https://api64.ipify.org?format=json')
  21.         ip_data = response.json()
  22.         public_ip = ip_data['ip']
  23.         print(f"Your public IP address is: {public_ip}")
  24.     except requests.RequestException as e:
  25.         print(f"Error: {e}")
  26.  
  27.  
  28. def scan_ports(target, start_port, end_port):
  29.     open_ports = []
  30.  
  31.     for port in range(start_port, end_port + 1):
  32.         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  33.         sock.settimeout(1)
  34.  
  35.         # Attempt to connect to the target's port
  36.         result = sock.connect_ex((target, port))
  37.  
  38.         # If the connection is successful, the port is open
  39.         if result == 0:
  40.             open_ports.append(port)
  41.             print(port)
  42.  
  43.         # Close the socket
  44.         sock.close()
  45.  
  46.     return open_ports
  47.  
  48.  
  49. def find_open_port_in_range():
  50.     target_host = input("Enter the target host (e.g., 'localhost' or an IP address): ")
  51.     start_port = int(input("Enter the start port: "))
  52.     end_port = int(input("Enter the end port: "))
  53.  
  54.     open_ports = scan_ports(target_host, start_port, end_port)
  55.  
  56.     if open_ports:
  57.         print("Open ports:")
  58.         for port in open_ports:
  59.             print(f"Port {port} is open.")
  60.     else:
  61.         print("No open ports found.")
  62.  
  63.    
  64.  
  65.  
  66. def get_open_ports():
  67.     try:
  68.         # Run the netstat command and capture the output
  69.         result = subprocess.run(['netstat', '-an'], capture_output=True, text=True)
  70.  
  71.         # Split the output into lines and filter for lines containing "LISTENING"
  72.         listening_lines = [line for line in result.stdout.split('\n') if 'LISTENING' in line]
  73.  
  74.         # Extract the local address and port from each listening line
  75.         open_ports = [line.split()[1] for line in listening_lines]
  76.  
  77.         return open_ports
  78.     except subprocess.CalledProcessError as e:
  79.         print(f"Error: {e}")
  80.         return None
  81.  
  82. def find_open_port_by_command():
  83.     open_ports = get_open_ports()
  84.  
  85.     if open_ports:
  86.         print("Open ports:")
  87.         for port in open_ports:
  88.             print(port)
  89.     else:
  90.         print("Error retrieving open ports.")
  91.  
  92.  
  93. def get_connected_ips_and_ports():
  94.     try:
  95.         # Run the netstat command and capture the output
  96.         result = subprocess.run(['netstat', '-an'], capture_output=True, text=True)
  97.  
  98.         # Split the output into lines and filter for lines containing "ESTABLISHED"
  99.         established_lines = [line for line in result.stdout.split('\n') if 'ESTABLISHED' in line]
  100.  
  101.         # Extract the remote address and port from each established connection
  102.         connected_ips_and_ports = [(line.split()[1], line.split()[2].split(':')[1]) for line in established_lines]
  103.  
  104.         return connected_ips_and_ports
  105.     except subprocess.CalledProcessError as e:
  106.         print(f"Error: {e}")
  107.         return None
  108.  
  109. def get_connected_ips_and_ports_by_command():
  110.     connected_ips_and_ports = get_connected_ips_and_ports()
  111.  
  112.     if connected_ips_and_ports:
  113.         print("Connected IPs and Ports:")
  114.         for ip, port in connected_ips_and_ports:
  115.             print(f"IP: {ip}, Port: {port}")
  116.     else:
  117.         print("Error retrieving connected IPs and Ports.")
  118.  
  119.  
  120.  
  121. if __name__ == "__main__":
  122.     get_local_ip()
  123.     get_public_ip()
  124.     find_open_port_by_command()
  125.     get_connected_ips_and_ports_by_command()
  126.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement