Advertisement
MeKLiN2

python 3 network monitor meklin2 github

Mar 17th, 2024
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. import psutil
  2. import time
  3. import os
  4. from colorama import Fore, Style
  5.  
  6. ACTIVE_CONNECTIONS = set()
  7.  
  8. def update_connections(output_file):
  9. global ACTIVE_CONNECTIONS
  10.  
  11. # Get the current set of active connections
  12. new_active_connections = set()
  13. for conn in psutil.net_connections():
  14. if conn.raddr and conn.status == 'ESTABLISHED':
  15. ip_address = conn.raddr.ip
  16. new_active_connections.add(ip_address)
  17.  
  18. # Find new connections
  19. new_connections = new_active_connections - ACTIVE_CONNECTIONS
  20. # Find removed connections
  21. removed_connections = ACTIVE_CONNECTIONS - new_active_connections
  22.  
  23. # Update active connections set
  24. ACTIVE_CONNECTIONS = new_active_connections
  25.  
  26. # Open the output file in append mode
  27. with open(output_file, 'a') as file:
  28. # Add new connections to the file with an asterisk marker
  29. for ip in new_connections:
  30. file.write(f"* {ip}\n")
  31. # Add removed connections to the file with a strikethrough marker
  32. for ip in removed_connections:
  33. file.write(f"~ {ip}\n")
  34.  
  35. def display_connections(output_file):
  36. # Clear the terminal before printing to avoid clutter
  37. os.system('cls' if os.name == 'nt' else 'clear')
  38.  
  39. # Read and display the contents of the output file
  40. print(f"{Fore.YELLOW}Current Connections:\n{Style.RESET_ALL}")
  41. with open(output_file, 'r') as file:
  42. for line in file:
  43. # Highlight new connections in green and removed connections in red
  44. if line.startswith('*'):
  45. print(Fore.GREEN + line.strip() + Style.RESET_ALL)
  46. elif line.startswith('~'):
  47. print(Fore.RED + line.strip() + Style.RESET_ALL)
  48. else:
  49. print(line.strip())
  50.  
  51. print("\n")
  52.  
  53. def monitor_connections(output_file, interval):
  54. while True:
  55. # Update the connections file
  56. update_connections(output_file)
  57. # Display the connections in the terminal
  58. display_connections(output_file)
  59. # Sleep for the specified interval
  60. time.sleep(interval)
  61.  
  62. if __name__ == "__main__":
  63. output_file = "connections.txt"
  64.  
  65. # Initial monitoring interval
  66. interval = int(input("Enter the initial monitoring interval in seconds: "))
  67.  
  68. # Start monitoring connections
  69. monitor_connections(output_file, interval)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement