Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # Filename: win_netsh_all.py
- # Author: Jeoi Reqi
- # This script is a command-line tool for Windows network management using netsh commands, featuring a menu-driven interface for tasks like firewall settings and Wi-Fi management, providing a user-friendly solution for network operations on Windows systems.
- import sys
- import subprocess
- ''' ::UTILITY FUNCTIONS::'''
- # Utility function to run netsh commands
- def run_netsh_command(command, trace_file_path=None, max_size=None):
- try:
- args = command + (['tracefile=' + trace_file_path, 'persistent=yes', f'maxsize={max_size}'] if trace_file_path and max_size else [])
- result = subprocess.run(args, capture_output=True, text=True, check=True)
- output = result.stdout.strip()
- if output:
- print(output)
- save_option_data(command[-1] if trace_file_path else ' '.join(command), output)
- else:
- print(f"No data found for '{command[-1]}'. Not saved to file (Value: None).\n")
- except subprocess.CalledProcessError as e:
- print("Error:", e.stderr)
- # Utility function to save data to a file
- def save_option_data(option_name, data):
- if data is not None:
- print("\nData:")
- print(data)
- valid_choices = {'yes', 'y', 'no', 'n', '1', '2'}
- save_choice = input(
- f"Do you want to save the data from '{option_name}'?\n1. Yes (y)\n2. No (n)\nEnter your choice: ").lower()
- if save_choice in valid_choices:
- if save_choice in {'yes', 'y', '1'}:
- sanitized_option_name = ''.join(c for c in option_name if c.isalnum() or c in ('_', ' '))
- filename = f"{sanitized_option_name}.txt"
- with open(filename, 'w', encoding='utf-8') as file:
- file.write(data)
- print(f"Data saved to '{filename}'\n")
- else:
- print("Data not saved.\n")
- else:
- print("Invalid choice. Data not saved.\n")
- # Wait for user input before proceeding
- input("Press Enter to continue...")
- else:
- print(f"No data found for '{option_name}'. Not saved to file (Value: None).\n")
- ''' ::OPTION MENU FUNCTIONS::'''
- # OPTION 0
- def display_firewall_settings():
- run_netsh_command(['netsh', 'advfirewall', 'show', 'allprofiles'])
- # OPTION 1
- def check_firewall_rules():
- run_netsh_command(['netsh', 'advfirewall', 'firewall', 'show', 'rule', 'name=all'])
- # OPTION 2
- def check_network_interface_status():
- try:
- result = subprocess.check_output(['netsh', 'interface', 'show', 'interface'], text=True)
- return result
- except subprocess.CalledProcessError as e:
- print(f"Error checking network interface status: {e}")
- return None
- # OPTION 3
- def get_wifi_profiles_and_passwords(): # Show Known Wi-Fi Network/Profiles Passwords
- # Get the Wi-Fi profiles
- command = 'netsh wlan show profiles'
- result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, text=True)
- # Extract profile names from the result
- profile_names = [line.split(":")[1].strip() for line in result.stdout.splitlines() if "All User Profile" in line]
- # Collect data to be displayed and saved
- output_data = ""
- # Iterate through profile names and display their names and passwords
- for profile_name in profile_names:
- profile_command = f'netsh wlan show profile name="{profile_name}" key=clear'
- profile_result = subprocess.run(profile_command, shell=True, stdout=subprocess.PIPE, text=True)
- # Extract and collect only relevant information
- password_line = [line.strip() for line in profile_result.stdout.splitlines() if "Key Content" in line]
- if password_line:
- output_data += f"\nProfile: {profile_name}, Password: {password_line[0].split(':')[1].strip()}\n"
- else:
- output_data += f"Profile: {profile_name}, Password not found.\n"
- return output_data
- # Display the list to the user
- def show_wifi_profiles():
- profiles_output = get_wifi_profiles_and_passwords()
- # Print the collected data
- print(profiles_output)
- # Prompt the user to save the file
- save_option_data("Wi-Fi Profiles", profiles_output)
- # OPTION 4
- def get_current_wifi_info():
- try:
- result = subprocess.check_output(["netsh", "wlan", "show", "interfaces"], text=True)
- return result
- except subprocess.CalledProcessError as e:
- print(f"Error getting current Wi-Fi information: {e}")
- return None
- # OPTION 5
- def check_available_wireless_connections():
- try:
- result = subprocess.check_output(['netsh', 'wlan', 'show', 'network'], text=True)
- return result
- except subprocess.CalledProcessError as e:
- print(f"Error checking available wireless connections: {e}")
- return None
- # Function to extract available networks
- def extract_available_wireless_networks(output):
- networks = []
- lines = output.splitlines()
- for line in lines:
- if "SSID" in line:
- ssid = line.split(":")[1].strip()
- networks.append(ssid)
- return networks
- # Function to display available wireless networks
- def display_available_wireless_networks(networks):
- print("\nAvailable Wireless Networks:\n")
- for i, ssid in enumerate(networks, start=1):
- print(f"{i}. {ssid}")
- # OPTION 6
- def check_wireless_interface_details():
- try:
- result = subprocess.check_output(['netsh', 'wlan', 'show', 'interfaces'], text=True)
- return result
- except subprocess.CalledProcessError as e:
- print(f"Error checking wireless interface details: {e}")
- return None
- # OPTION 7
- def disconnect_wireless_device():
- run_netsh_command(['netsh', 'wlan', 'disconnect'])
- # OPTION 8
- def connect_to_wireless_device(selected_network):
- try:
- # Use the selected_network variable to connect to the chosen Wi-Fi network
- result = subprocess.run(['netsh', 'wlan', 'connect', f'name="{selected_network}"'], capture_output=True, text=True, check=True)
- print(result.stdout)
- # Ask the user if they want to save the data
- save_choice = input("\nDo you want to save the output of the connection attempt?\n1. Yes (y)\n2. No (n)\nEnter your choice: ").lower()
- if save_choice in {'yes', 'y', '1'}:
- # Generate a filename based on the function name
- filename = f"connect_to_wireless_device_output.txt"
- with open(filename, 'w', encoding='utf-8') as file:
- file.write(result.stdout)
- print(f"Data saved to '{filename}'\n")
- else:
- print("Data not saved.\n")
- return result.stdout # Return the result
- except subprocess.CalledProcessError as e:
- print("Error connecting to the wireless network:", e.stderr)
- # Wait for user input before proceeding to the menu
- input("Press Enter to continue...")
- return None # Return None in case of an error
- # Display List Of Available Networks
- def select_wifi_network(networks):
- print("\nAvailable Wireless Networks:")
- print("{:<5} {:<}".format("Num", "SSID"))
- for i, network in enumerate(networks, start=1):
- print("{:<5} {:<}".format(i, network))
- while True:
- try:
- choice = input("\nEnter the number of the network to connect to (or press Enter to cancel): ").strip()
- if not choice:
- return None # User pressed Enter to cancel
- else:
- choice = int(choice)
- if 1 <= choice <= len(networks):
- return networks[choice - 1] # Return the selected network
- else:
- print("Invalid choice. Please enter a valid number.")
- except ValueError:
- print("Invalid input. Please enter a valid number.")
- # OPTION 9
- def show_all_wireless_interfaces():
- run_netsh_command(['netsh', 'wlan', 'show', 'interfaces'])
- # OPTION 10
- def show_wireless_drivers():
- run_netsh_command(['netsh', 'wlan', 'show', 'drivers'])
- # OPTION 11
- def show_proxy_settings():
- run_netsh_command(['netsh', 'winhttp', 'show', 'proxy'])
- # OPTION 12
- def show_tcp_global_parameters():
- run_netsh_command(['netsh', 'interface', 'tcp', 'show', 'global'])
- # OPTION 13
- def show_udp_global_parameters():
- run_netsh_command(['netsh', 'interface', 'udp', 'show', 'global'])
- # OPTION 14
- def disable_tcp_rss():
- run_netsh_command(['netsh', 'interface', 'tcp', 'set', 'global', 'rss=disabled'])
- # OPTION 15
- def enable_tcp_rss():
- run_netsh_command(['netsh', 'interface', 'tcp', 'set', 'global', 'rss=enabled'])
- # OPTION 16
- def list_defined_aliases():
- run_netsh_command(['netsh', 'show', 'alias'])
- # OPTION 17
- def reset_winsock_entries():
- run_netsh_command(['netsh', 'winsock', 'reset', 'catalog'])
- # OPTION 18
- def reset_tcp_ip_stack():
- run_netsh_command(['netsh', 'int', 'ip', 'reset', 'reset.log'])
- # OPTION 19
- def set_proxy():
- proxy_address = input("Enter the proxy address (e.g., myproxy.proxyaddress.com:8484): ")
- exceptions = input("Enter proxy exceptions (e.g., <local>;*.proxyaddress.com): ")
- run_netsh_command(['netsh', 'winhttp', 'set', 'proxy', f'"{proxy_address}"', f'"{exceptions}"'])
- # OPTION 20
- def show_multicast_joins():
- run_netsh_command(['netsh', 'interface', 'ip', 'show', 'joins'])
- # OPTION 21
- def allow_port_firewall():
- rule_name = input("Enter the name of the firewall rule: ")
- protocol = input("Enter the protocol (TCP/UDP): ")
- direction = input("Enter the direction (in/out): ")
- local_port = input("Enter the local port: ")
- run_netsh_command(['netsh', 'advfirewall', 'firewall', 'add', 'rule', f'name="{rule_name}"', f'protocol={protocol}', f'dir={direction}', f'localport={local_port}', 'action=allow'])
- # OPTION 22
- def add_primary_dns_server():
- interface_name_dns = input("Enter the name of the network interface: ")
- dns_server_address = input("Enter the Primary DNS Server address: ")
- run_netsh_command(['netsh', 'interface', 'ip', 'add', 'dns', f'name="{interface_name_dns}"', f'addr={dns_server_address}'])
- # OPTION 23
- def allow_ping_requests():
- run_netsh_command(['netsh', 'advfirewall', 'firewall', 'add', 'rule', 'name="All ICMP V4"', 'dir=in', 'action=allow', 'protocol=icmpv4'])
- # OPTION 24
- def block_ping_requests():
- run_netsh_command(['netsh', 'advfirewall', 'firewall', 'add', 'rule', 'name="All ICMP V4"', 'dir=in', 'action=block', 'protocol=icmpv4'])
- # OPTION 25
- def disable_windows_firewall():
- run_netsh_command(['netsh', 'advfirewall', 'set', 'allprofiles', 'state', 'off'])
- # OPTION 26
- def reset_firewall_settings():
- run_netsh_command(['netsh', 'advfirewall', 'reset'])
- # OPTION 27
- def stop_network_trace():
- run_netsh_command(['netsh', 'trace', 'stop'])
- # OPTION 28
- def capture_packets():
- try:
- # Ask the user to choose the duration for the ping test
- print("Choose the duration for the ping test:")
- print("1. Quick Ping Test (15 sec.)")
- print("2. Standard Ping Test (30 sec.)")
- print("3. Long Ping Test (60 sec.)")
- choice = input("Enter the option number: ")
- if choice == '1':
- duration_seconds = 15
- elif choice == '2':
- duration_seconds = 30
- elif choice == '3':
- duration_seconds = 60
- else:
- print("Invalid choice. Defaulting to Standard Ping Test (30 sec.)")
- duration_seconds = 30
- # Inform the user about the test
- print(f"Capturing packets for {duration_seconds} seconds. Please wait...")
- # Run ping test (change 'example.com' to the desired target)
- result = subprocess.run(['ping', '-n', str(duration_seconds), 'example.com'], capture_output=True, text=True, check=True)
- # Display completion message
- print("Packet capture completed.")
- # Save data
- save_option_data('Capture Packets', result.stdout)
- except subprocess.CalledProcessError as e:
- # Handle error if the command fails
- print("Error:", e.stderr)
- # OPTION 29
- def change_interface_ip_address():
- interface_name = input("Enter the name of the network interface: ")
- ip_address = input("Enter the new IP address: ")
- subnet_mask = input("Enter the subnet mask: ")
- gateway = input("Enter the gateway address: ")
- run_netsh_command(['netsh', 'int', 'ip', 'set', 'address', interface_name, 'static', ip_address, subnet_mask, gateway])
- # OPTION 30
- # PLACEHOLDER SCRIPT FOR NOW
- def placeholder():
- print("\nPLACEHOLDER\n")
- ''' ::IPV4::'''
- # OPTION 31
- def view_current_ipv4_configuration():
- print("\n\t\t\t\t::IPV4::\n")
- try:
- command = ['netsh', 'interface', 'ipv4', 'show', 'config']
- result = subprocess.run(command, capture_output=True, text=True, check=True)
- output = result.stdout.strip()
- if output:
- print("\nCurrent IPv4 Configuration:")
- print(output)
- save_option_data('View_Current_IPV4_Configuration', output)
- else:
- print("No data found for IPv4 configuration.")
- except subprocess.CalledProcessError as e:
- print("Error:", e.stderr)
- ''' ::IPV6:: [BROKEN]'''
- # OPTION 32
- def view_current_ipv6_configuration(interfaces):
- print("\n\t\t\t\t::IPV6::\n")
- if not interfaces:
- print("No network interfaces available.")
- input("\nPress Enter to continue...")
- return
- selected_interface = get_interface_number(interfaces)
- if selected_interface is not None:
- try:
- # Display IPv6 information using the provided netsh commands
- run_netsh_command(['netsh', 'interface', 'ipv6', 'show', 'interfaces'], trace_file_path=None, max_size=None)
- run_netsh_command(['netsh', 'interface', 'ipv6', 'show', 'addresses'], trace_file_path=None, max_size=None)
- except subprocess.CalledProcessError as e:
- print("Error displaying IPv6 configuration:", e.stderr)
- # OPTION 33 (EXIT)
- ''' ::OPTIONS MENU::'''
- def display_menu():
- options = [
- "Display Firewall Settings",
- "Check Firewall Rules",
- "Check Network Interface Status",
- "Show Wi-Fi Network/Profiles & Passwords",
- "Get Current Wi-Fi Information",
- "Check all the Available Wireless Connections",
- "Check the State & Strength of all the Available Wireless Connections",
- "Disconnect from Currently Connected Wireless Device",
- "Connect to an Available Wireless Device",
- "Show all the Wireless Interfaces",
- "Show Drivers of Wireless Interfaces",
- "Check Current Proxy Setting in Windows",
- "Check TCP Global Parameters Status",
- "Check UDP Global Parameters Status",
- "Disable TCP RSS Global Parameter",
- "Enable TCP RSS Global Parameter",
- "List all the defined Aliases",
- "Reset Winsock entries to default",
- "Reset TCP/IP Stack to Installation Default",
- "Set Proxy in Windows using netsh command",
- "Show Multicast Joins for all Network Interfaces",
- "Allow a Port from Windows Firewall using netsh command",
- "Add a Primary DNS Server to an Interface",
- "Allow Ping requests through Windows Firewall",
- "Block Ping requests through Windows Firewall",
- "Disable Windows Firewall in all Profiles",
- "Reset Windows Firewall Settings to Default",
- "Stop Trace using netsh command",
- "[PING] Capture Packets using netsh command",
- "Change Interface IP Address",
- "--[PLACEHOLDER OPTION]--",
- "View Current IPV4 Configuration",
- "View Current IPV6 Configuration --[BROKEN]--",
- "Exit the program"
- ]
- for i, option in enumerate(options):
- print(f"{i}. {option}")
- ''' ::MAIN PROGRAM::'''
- def main():
- interfaces = [] # Initialize an empty list of interfaces
- while True:
- display_menu()
- # Get user choice
- choice = input("Enter the option number: ")
- if choice.isdigit() and 0 <= int(choice) <= 33:
- if choice == '0':
- last_command_output = display_firewall_settings()
- save_option_data('Display_firewall_settings', last_command_output)
- elif choice == '1':
- try:
- result = subprocess.run(['netsh', 'advfirewall', 'firewall', 'show', 'rule', 'name=all'],
- capture_output=True, text=True, check=True)
- last_command_output = result.stdout
- if last_command_output:
- print("\nCurrent Firewall Rules for the Profile:")
- print(last_command_output)
- save_option_data('Show_all_Firewall_rules_for_Current_Profile', last_command_output)
- else:
- print("No firewall rules found.")
- except subprocess.CalledProcessError as e:
- print("Error:", e.stderr)
- elif choice == '2':
- last_command_output = check_network_interface_status()
- save_option_data('Check Network Interface Status', last_command_output)
- elif choice == '3':
- last_command_output = view_current_ipv4_configuration()
- save_option_data('View_Current_IPV4_Configuration', last_command_output)
- elif choice == '4':
- last_command_output = get_current_wifi_info()
- save_option_data('Get Current Wi-Fi Information', last_command_output)
- elif choice == '5':
- last_command_output = check_available_wireless_connections()
- save_option_data('Check_Available_Wireless_Connections', last_command_output)
- elif choice == '6':
- last_command_output = check_wireless_interface_details()
- save_option_data('Check_Wireless_Interface_Details', last_command_output)
- elif choice == '7': #Disconnect From Current Wi-Fi
- last_command_output = disconnect_wireless_device()
- save_option_data('Disconnect_from_Currently_Connected_Wireless_Device', last_command_output)
- elif choice == '8': #Reconnect To Stored Wi-Fi Network
- wireless_networks_output = check_available_wireless_connections()
- networks = extract_available_wireless_networks(wireless_networks_output)
- selected_network = select_wifi_network(networks)
- if selected_network:
- last_command_output = connect_to_wireless_device(selected_network)
- elif choice == '9':
- last_command_output = show_all_wireless_interfaces()
- save_option_data('Show_all_Wireless_Interfaces', last_command_output)
- elif choice == '10':
- last_command_output = show_wireless_drivers()
- save_option_data('Show_Wireless_Drivers', last_command_output)
- elif choice == '11':
- last_command_output = show_proxy_settings()
- save_option_data('Show_Current_Proxy_Setting_in_Windows', last_command_output)
- elif choice == '12':
- last_command_output = show_tcp_global_parameters()
- save_option_data('Check_TCP_Global_Parameters_Status', last_command_output)
- elif choice == '13':
- last_command_output = show_udp_global_parameters()
- save_option_data('Check_UDP_Global_Parameters_Status', last_command_output)
- elif choice == '14':
- last_command_output = disable_tcp_rss()
- save_option_data('Disable_TCP_RSS_Global_Parameter', last_command_output)
- elif choice == '15':
- last_command_output = enable_tcp_rss()
- save_option_data('Enable_TCP_RSS_Global_Parameter', last_command_output)
- elif choice == '16':
- last_command_output = list_defined_aliases()
- save_option_data('List_All_Defined_Aliases', last_command_output)
- elif choice == '17':
- last_command_output = reset_winsock_entries()
- save_option_data('Reset_Winsock_Entries_to_Default', last_command_output)
- elif choice == '18':
- last_command_output = reset_tcp_ip_stack()
- save_option_data('Reset_TCP_IP_Stack_to_Installation_Default', last_command_output)
- elif choice == '19':
- last_command_output = set_proxy()
- save_option_data('Set_Proxy_in_Windows_using_netsh_command', last_command_output)
- elif choice == '20':
- last_command_output = show_multicast_joins()
- save_option_data('Show_Multicast_Joins_for_All_Network_Interfaces', last_command_output)
- elif choice == '21':
- last_command_output = allow_port_firewall()
- save_option_data('Allow_a_Port_from_Windows_Firewall_using_netsh_command', last_command_output)
- elif choice == '22':
- last_command_output = add_primary_dns_server()
- save_option_data('Add_Primary_DNS_Server_to_an_Interface', last_command_output)
- elif choice == '23':
- last_command_output = allow_ping_requests()
- save_option_data('Allow_Ping_Requests_through_Windows_Firewall', last_command_output)
- elif choice == '24':
- last_command_output = block_ping_requests()
- save_option_data('Block_Ping_Requests_through_Windows_Firewall', last_command_output)
- elif choice == '25':
- last_command_output = disable_windows_firewall()
- save_option_data('Disable_Windows_Firewall_in_All_Profiles', last_command_output)
- elif choice == '26':
- last_command_output = reset_firewall_settings()
- save_option_data('Reset_Windows_Firewall_Settings_to_Default', last_command_output)
- elif choice == '27':
- last_command_output = stop_network_trace()
- save_option_data('Stop_Trace_using_netsh_command', last_command_output)
- elif choice == '28':
- last_command_output = capture_packets()
- save_option_data('[PING]Capture_Packets_using_netsh_command', last_command_output)
- elif choice == '29':
- last_command_output = change_interface_ip_address()
- save_option_data('Change_Interface_IP_Address', last_command_output)
- elif choice == '30':
- last_command_output = placeholder()
- save_option_data('PLACEHOLDER FOR OPTION', last_command_output)
- elif choice == '31':
- last_command_output = view_current_ipv4_configuration()
- save_option_data('View_Current_IPV4_Configuration', last_command_output)
- elif choice == '32':
- interfaces = display_network_interfaces()
- last_command_output = view_current_ipv6_configuration_wrapper(interfaces, display_list=False)
- save_option_data('View_Current_IPV6_Configuration', last_command_output)
- elif choice == '33': # [BROKEN]
- print("Exiting the program. Goodbye!")
- sys.exit(0)
- else:
- print("\nInput Invalid!\n\tPlease enter a valid option number between 0 and 33.\n\t\tOr... type '34' to exit the program.\n")
- input("\nPress Enter to continue...\n")
- else:
- print("\nInput Invalid!\n\tPlease enter a valid option number between 0 and 33.\n\t\tOr... type '34' to exit the program\n")
- input("\nPress Enter to continue...\n")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement