Advertisement
EdmundC

PING

Oct 5th, 2024
20
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.80 KB | None | 0 0
  1. import os
  2. import platform
  3. import socket
  4. import subprocess
  5. import threading
  6. import time
  7.  
  8. # Set a port number for sending/receiving data (UDP)
  9. PORT = 8080
  10. BUFFER_SIZE = 1024  # Maximum size of data to be received
  11.  
  12. known_ips = []  # List to store known IPs
  13.  
  14. def get_local_ip():
  15.     """Get the local IP address of the machine."""
  16.     hostname = socket.gethostname()
  17.     local_ip = socket.gethostbyname(hostname)
  18.     return local_ip
  19.  
  20. def get_network_prefix():
  21.     """Get the network prefix and subnet mask."""
  22.     local_ip = get_local_ip()
  23.     # Automatically determine subnet (default to /24)
  24.     return '.'.join(local_ip.split('.')[:-1])
  25.  
  26. def ping_sweep():
  27.     """Perform a ping sweep across all IPs in the local network."""
  28.     network_prefix = get_network_prefix()
  29.    
  30.     param = '-n' if platform.system().lower() == 'windows' else '-c'
  31.     active_ips = []
  32.  
  33.     for i in range(1, 255):
  34.         ip = f"{network_prefix}.{i}"
  35.         command = ['ping', param, '1', ip]
  36.        
  37.         result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  38.        
  39.         if result.returncode == 0:
  40.             active_ips.append(ip)
  41.     return active_ips
  42.  
  43. def ping_specific_ip(ip_address):
  44.     """Ping a specific local IP address."""
  45.     param = '-n' if platform.system().lower() == 'windows' else '-c'
  46.     command = ['ping', param, '1', ip_address]
  47.    
  48.     result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  49.    
  50.     return result.returncode == 0  # Return True if the ping is successful
  51.  
  52. def beep_alert():
  53.     """Make a 1000 Hz beep for 1 second (on Windows) or a system beep for Unix."""
  54.     if platform.system().lower() == 'windows':
  55.         import winsound
  56.         winsound.Beep(1000, 1000)  # 1000 Hz for 1 second
  57.     else:
  58.         os.system('echo -e "\\a"')
  59.  
  60. def antihack():
  61.     """Run the antihack system to monitor for unknown IPs."""
  62.     while True:
  63.         active_ips = ping_sweep()
  64.         for ip in active_ips:
  65.             if ip not in known_ips:
  66.                 print(f"Unknown IP: {ip}!")
  67.                 beep_alert()  # Trigger the alert
  68.         time.sleep(5)  # Wait for 5 seconds before the next sweep
  69.  
  70. def send_data_to_ip(data, ip_address):
  71.     """Send the data to a specific IP address using UDP."""
  72.     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  73.     try:
  74.         sock.sendto(data.encode(), (ip_address, PORT))
  75.         print(f"Data sent to {ip_address}: {data}")
  76.     except Exception as e:
  77.         print(f"Failed to send data to {ip_address}: {e}")
  78.     finally:
  79.         sock.close()
  80.  
  81. def receive_data_from_ip(ip_address=None):
  82.     """Receive data from a specific IP address or listen to all."""
  83.     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  84.     try:
  85.         sock.bind((ip_address if ip_address else '', PORT))
  86.         print(f"Listening for data on IP {ip_address if ip_address else 'all local IPs'}...")
  87.         while True:
  88.             data, addr = sock.recvfrom(BUFFER_SIZE)
  89.             print(f"Received data from {addr}: {data.decode()}")
  90.     except Exception as e:
  91.         print(f"Failed to receive data: {e}")
  92.     finally:
  93.         sock.close()
  94.  
  95. def handle_command(command):
  96.     """Handle commands entered by the user."""
  97.     if command == '/ping local all':
  98.         active_ips = ping_sweep()
  99.         print(f"Active IPs: {', '.join(active_ips)}")
  100.    
  101.     elif command.startswith('/ping local'):
  102.         parts = command.split()
  103.         if len(parts) == 3:
  104.             ip_address = parts[2]
  105.             if ping_specific_ip(ip_address):
  106.                 print(f"Ping to {ip_address} was successful!")
  107.             else:
  108.                 print(f"Ping to {ip_address} failed.")
  109.         else:
  110.             print("Usage: /ping local x.x.x.x")
  111.    
  112.     elif command.startswith('/ping global'):
  113.         parts = command.split()
  114.         if len(parts) == 3:
  115.             ip_address = parts[2]
  116.             if ping_specific_ip(ip_address):
  117.                 print(f"Ping to {ip_address} was successful!")
  118.             else:
  119.                 print(f"Ping to {ip_address} failed.")
  120.         else:
  121.             print("Usage: /ping global x.x.x.x")
  122.    
  123.     elif command.startswith('/datasend local all'):
  124.         data = command.split('"')[1]  # Extract the data inside quotes
  125.         send_data_to_all_local(data)
  126.    
  127.     elif command.startswith('/datasend local'):
  128.         parts = command.split()
  129.         if len(parts) == 4:
  130.             data = parts[1].strip('"')
  131.             ip_address = parts[3]
  132.             send_data_to_ip(data, ip_address)
  133.         else:
  134.             print('Usage: /datasend local "data" x.x.x.x')
  135.    
  136.     elif command.startswith('/datasend global'):
  137.         parts = command.split()
  138.         if len(parts) == 4:
  139.             data = parts[1].strip('"')
  140.             ip_address = parts[3]
  141.             send_data_to_ip(data, ip_address)
  142.         else:
  143.             print('Usage: /datasend global "data" x.x.x.x')
  144.    
  145.     elif command == '/datareceive local all':
  146.         threading.Thread(target=receive_data_from_ip).start()
  147.    
  148.     elif command.startswith('/datareceive local'):
  149.         parts = command.split()
  150.         if len(parts) == 3:
  151.             ip_address = parts[2]
  152.             threading.Thread(target=receive_data_from_ip, args=(ip_address,)).start()
  153.         else:
  154.             print("Usage: /datareceive local x.x.x.x")
  155.    
  156.     elif command.startswith('/datareceive global'):
  157.         parts = command.split()
  158.         if len(parts) == 3:
  159.             ip_address = parts[2]
  160.             threading.Thread(target=receive_data_from_ip, args=(ip_address,)).start()
  161.         else:
  162.             print("Usage: /datareceive global x.x.x.x")
  163.    
  164.     elif command.startswith('/ahlist add'):
  165.         parts = command.split()
  166.         if len(parts) == 3:
  167.             ip_address = parts[2]
  168.             if ip_address not in known_ips:
  169.                 known_ips.append(ip_address)
  170.                 print(f"Added {ip_address} to known IP list.")
  171.             else:
  172.                 print(f"{ip_address} is already in the known IP list.")
  173.         else:
  174.             print("Usage: /ahlist add x.x.x.x")
  175.    
  176.     elif command == '/antihack':
  177.         print("Starting antihack monitoring...")
  178.         threading.Thread(target=antihack).start()
  179.    
  180.     else:
  181.         print("Unknown command. Try '/ping local all', '/ping local x.x.x.x', '/ping global x.x.x.x', '/datasend local', '/datasend global', '/datareceive local', '/datareceive global', '/ahlist add', or '/antihack'.")
  182.  
  183. if __name__ == "__main__":
  184.     while True:
  185.         # Get user input
  186.         user_input = input("Enter command: ").strip()
  187.        
  188.         # Handle exit command
  189.         if user_input.lower() in ['exit', 'quit']:
  190.             print("Exiting program.")
  191.             break
  192.        
  193.         # Handle the command
  194.         handle_command(user_input)
  195.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement