def update_windows(): newline() print('notify~! Checking local execution policy...') execution_policy = pshell_decoder('Get-ExecutionPolicy') if 'Restricted' in execution_policy \ or 'AllSigned' in execution_policy: newline() print('error~! Your pshell execution policy is preventing '\ + 'this action. Try \'powershell policy ?\'') newline() else: print('notify~! Unblocking file path...') unblock = pshell_decoder('Unblock-File -Path \'C:\\Program Files'\ + ' (x86)\\igloo\\scripts\\updateWindows.ps1\' | Out-Null') error = "cannot be loaded" print('notify~! Searching for updates...') get_current_dir = pshell_decoder('Get-Location') clean_up = get_current_dir.replace('\r\n', '').replace(' ', '') split_it = clean_up.split('----') subprocess.call(['powershell.exe', 'Set-Location -Path \"C:\\Program Files'\ + ' (x86)\" | powershell .\\igloo\\scripts\\updateWindows.ps1']) subprocess.call(['powershell.exe', 'Set-Location -Path ' \ + split_it[1]] + ' | Out-Null')
def fwall_toggle(fwall_cmd): #Firewall configuration commands. fwall_profile_dictionary = { 'fwall on': 'Set-NetFirewallProfile -Profile Domain,Private,Public -Enabled True', 'fwall off': 'Set-NetFirewallProfile -Profile Domain,Private,Public -Enabled False', 'fwall dom on': 'Set-NetFirewallProfile -Profile Domain -Enabled True', 'fwall dom off': 'Set-NetFirewallProfile -Profile Domain -Enabled False', 'fwall pub on': 'Set-NetFirewallProfile -Profile Public -Enabled True', 'fwall pub off': 'Set-NetFirewallProfile -Profile Public -Enabled False', 'fwall priv on': 'Set-NetFirewallProfile -Profile Private -Enabled True', 'fwall priv off': 'Set-NetFirewallProfile -Profile Private -Enabled False' } for line in fwall_profile_dictionary: if line == fwall_cmd: pshell_decoder(fwall_profile_dictionary.get(line)) if fwall_cmd == 'fwall on': newline() print('notify~! Firewall enabled globally') newline() elif fwall_cmd == 'fwall off': newline() print('notify~! Firewall disabled globally') newline() elif fwall_cmd == 'fwall dom on': newline() print('notify~! Firewall enabled for domain networks') newline() elif fwall_cmd == 'fwall dom off': newline() print('notify~! Firewall disabled for domain networks') newline() elif fwall_cmd == 'fwall pub on': newline() print('notify~! Firewall enabled for public networks') newline() elif fwall_cmd == 'fwall pub off': newline() print('notify~! Firewall disabled for public networks') newline() elif fwall_cmd == 'fwall priv on': newline() print('notify~! Firewall enabled for private networks') newline() elif fwall_cmd == 'fwall priv off': newline() print('notify~! Firewall disabled for private networks') newline()
def ip_general(ip_arg): ip_general_dictionary = { 'ip icmp redirect enable':'Set-NetIpv4Protocol -IcmpRedirects Enabled', 'ip icmp redirect disable':'Set-NetIpv4Protocol -IcmpRedirects Disabled', 'ip igmp version 1':'Set-NetIpv4Protocol -IGMPVersion Version1', 'ip igmp version 2':'Set-NetIpv4Protocol -IGMPVersion Version2', 'ip igmp version 3':'Set-NetIpv4Protocol -IGMPVersion Version3', 'ip multicast enable':'Set-NetIpv4Protocol -MulticastForwarding Enabled', 'ip multicast disable':'Set-NetIpv4Protocol -MulticastForwarding Disabled', 'ip source-route forward':'Set-NetIpv4Protocol -SourceRoutingBehavior Forward', 'ip source-route receive-only':'Set-NetIpv4Protocol -SourceRoutingBehavior DontForward', 'ip source-route drop':'Set-NetIpv4Protocol -SourceRoutingBehavior Drop', 'ip tcp timestamp enable':'set-nettcpsetting -Timestamps Enabled', 'ip tcp timestamp disable':'set-nettcpsetting -Timestamps Disabled', 'ip tcp ecn enable':'set-nettcpsetting -ecncapability enabled', 'ip tcp ecn disable':'set-nettcpsetting -ecncapability disabled', 'ip tcp mpp enable':'set-nettcpsetting -MemoryPressureProtection Enabled', 'ip tcp mpp disable':'set-nettcpsetting -MemoryPressureProtection Disabled', 'ip tcp auto-tune disable':'set-nettcpsetting -AutoTuningLevelLocal Disabled', 'ip tcp auto-tune restrict':'set-nettcpsetting -AutoTuningLevelLocal Restricted', 'ip tcp auto-tune normal':'set-nettcpsetting -AutoTuningLevelLocal Normal' } ip_help_dictionary = { 'ip icmp redirect enable':'notify~! ICMP redirects are now enabled.', 'ip icmp redirect disable':'notify~! ICMP redirects are now disabled', 'ip igmp version 1':'notify~! IGMP has been set to version 1.', 'ip igmp version 2':'notify~! IGMP has been set to version 2.', 'ip igmp version 3':'notify~! IGMP has been set to version 3.', 'ip multicast enable':'notify~! Multicast forwarding has been enabled.', 'ip multicast disable':'notify~! Multicast forwarding has been disabled.', 'ip source-route forward':'notify~! Forwarding source-routed packets.', 'ip source-route receive-only':'notify~! Listening for source-routed packets.', 'ip source-route drop':'notify~! Dropping source-routed packets.', 'ip tcp timestamp enable':'notify~! TCP timestamps have been enabled.', 'ip tcp timestamp disable':'notify~! TCP timestamps have been disabled.', 'ip tcp ecn enable':'notify~! ECN has been enabled for the local host.', 'ip tcp ecn disable':'notify~! ECN has been disabled for the local host.', 'ip tcp mpp enable':'notify~! TCP Memory Pressure Protection has been enabled.', 'ip tcp mpp disable':'notify~! TCP Memory Pressure Protection has been disabled.', 'ip tcp auto-tune disable':'notify~! TCP auto-tuning has been disabled.', 'ip tcp auto-tune restrict':'notify~! TCP auto-tuning has been enabled. Rx wdw increased.', 'ip tcp auto-tune normal':'notify~! TCP auto-tuning has been enabled. Receive window size increased.' } for line in ip_general_dictionary: if line == ip_arg: pshell_decoder(ip_general_dictionary.get(line)) for line in ip_help_dictionary: if line == ip_arg: newline() print(ip_help_dictionary.get(line)) newline()
def ip_route(add_this_route): split_arg = add_this_route.split(' ') if len(split_arg) == 7 \ and 'metric' in split_arg: dest_prefix = split_arg[2] next_hop = split_arg[3] int_index = split_arg[4] route_metric = split_arg[6] add_route = pshell_decoder('new-netroute -DestinationPrefix '\ +dest_prefix+' -ifIndex ' +int_index + ' -NextHop '\ + next_hop +' -RouteMetric ' + route_metric) if 'Instance MSFT_NetRoute already exists' in add_route: newline() print('error~! Route to destination prefix %s already in table.'\ % dest_prefix) newline() else: newline() print('notify~! Route to prefix %s created. M=%s.'\ % (dest_prefix, route_metric)) newline() elif len(split_arg) == 5 \ and 'metric' not in split_arg: dest_prefix = split_arg[2] next_hop = split_arg[3] int_index = split_arg[4] add_route = pshell_decoder('new-netroute -DestinationPrefix '\ +dest_prefix+' -ifIndex '+int_index+' -NextHop '\ +next_hop+' | Out-Null') if 'Instance MSFT_NetRoute already exists' in add_route: newline() print('error~! Route to destination prefix %s already in table.'\ % dest_prefix) newline() else: newline() print('notify~! Route to destination prefix %s has been created.'\ % dest_prefix) newline()
def install_tree(install_command): # Search installlDict.py for relevant command. newline() split_command = install_command.split(' ') if len(split_command) == 3: feature = split_command[2] elif len(split_command) == 4: feature == split_command[2] + ' ' + split_command[3] else: pass for command in installDict.install: if command == install_command: print('notify~! Installing \'{}\'...'.format(feature)) install_feature = pshell_decoder(installDict.install.get(command)) if 'WARNING:' in install_feature: print( 'notify~! Installed \'{}\' successfully!'.format(feature)) print('notify~! Use \'win reboot\' to complete the install.') newline() elif 'NoChangeNeeded' in install_feature: print('notify~! Feature \'{}\' already installed.'.format( feature)) newline() elif 'ArgumentNotValid:' in install_feature: print('notify~! Feature is either unknown or '\ + 'has unmet dependencies.') newline() elif ('The target' in install_feature or 'is not recognized' in install_feature): print('notify~! This command is supported only on '\ + 'Windows Server machines') newline() else: newline() print('error~! An unknown exception occurred.') newline() else: pass
def no_ip_route(delete_this_route): split_arg = delete_this_route.split(' ') dest_prefix = split_arg[3] rm_route = pshell_decoder('Remove-NetRoute -DestinationPrefix '+dest_prefix +' -Confirm:$false') if 'No MSFT_NetRoute objects found' in rm_route: newline() print('error~! Route does not exist in table.') newline() else: newline() print('notify~! Route to prefix %s has been deleted.' \ % dest_prefix) newline()
def fwall_delete(delete_statement): # if firewall rule exists, delete. if not fwall_rule_name = delete_statement[3] newline() print('notify~! Attempting to delete firewall rule \'{}\'...'.format( fwall_rule_name)) not_found_error = "ObjectNotFound" remove_rule = pshell_decoder('Remove-NetFirewallRule -DisplayName ' + fwall_rule_name) if not_found_error in remove_rule: print("notify~! Rule does not exist.") newline() else: print('notify~! Firewall rule \'{}\' was deleted.'.format( fwall_rule_name)) newline()
def bgp_install(): print('notify~! Enabling BGP routing') install_routing_daemon = pshell_decoder( 'Install-RemoteAccess -VpnType RoutingOnly | Out-Null') if 'The term \'Install-RemoteAccess\' is not recognized as the name of a cmdlet' in install_routing_daemon: newline() print( 'notify~! RSAT features are not installed, or are not finished installing.' ) print( 'notify~! If you just installed RSAT, reload this server and run \'bgp enable\' again.' ) newline() else: newline() print('notify~! Dependencies installed successfully.'\ +' Use \'win reboot\' to enable BGP routing features.') newline() return
def fping_script(): newline() print('notify~! Your device list should be a .txt file with one'\ + ' hostname or IP address per line.') newline() try: loop_keepalive = 1 while loop_keepalive == 1: my_devices = input('input~! Specify the full path to your device list: ') strip_devices = my_devices.strip(' ') no_quotes = strip_devices.strip('\'"') if any(my_devices) == True: loop_keepalive = 0 break newline() print('notify~! Pinging device list...') except: newline() print('notify~! Terminating operation...') newline() with open(no_quotes,'r') as file: newline() for line in file: target = pshell_decoder('ping -n 1 ' + line) stripped_target = target.strip() split_target = stripped_target.split('\n') stripped_line = line.rstrip() try: if 'Reply' in split_target[1]: print('{} OK'.format(stripped_line)) else: print('{} FAIL'.format(stripped_line)) except: pass newline()
def crypto_delete(delete_this_vpn): # Split command arguments into an array. delete_this_vpn[2] should be # the vpn name. newline() try: print('notify~! Finding VPN adapter \'{}\'...'.format(delete_this_vpn)) delete_vpn = pshell_decoder('Remove-VpnConnection -Name ' + delete_this_vpn + ' -Force -PassThru') if 'ObjectNotFound' in delete_vpn: print('notify~! VPN adapter \'{}\' does not exist.'.format( delete_this_vpn)) newline() else: print('notify~! VPN profile \'{}\' was deleted.'.format( delete_this_vpn)) newline() except: newline() print('error~! Operation terminated unexpectedly.') newline() pass
def generate_rsa(): try: newline() print('notify~! Use commas to separate multiple entries') newline() cn = input('input~! DNS common name: ') ou = input('input~! Active Directory OU: ') san = input('input~! SAN: ') dc = input('input~! DC: ') strip_cn = cn.rstrip(' ') strip_ou = ou.rstrip(' ') strip_dc = dc.rstrip(' ') split_dc = strip_dc.split(',') strip_san = san.rstrip(' ') split_san = strip_san.split(',') dc_format, san_format = format_certificate(split_dc, split_san) create_cert = pshell_decoder('New-SelfSignedCertificate -Type Custom -Subject \ \"CN={},OU={},{}\" -TextExtension @(\"2.5.29.37={}1.3.6.1.5.5.7.3.2\"\ ,\"2.5.29.17={}{}\") -KeyUsage DigitalSignature -KeyAlgorithm\ RSA -KeyLength 2048 -CertStoreLocation \"Cert:\\LocalMachine\\My\"' .format(strip_cn, \ strip_ou, dc_format, '{text}', '{text}', san_format)) if ' PSParentPath:' in create_cert: newline() print('notify~! Self-signed certificate created and stored '\ + 'in \"Cert:\\LocalMachine\\My\" (Computer Certificates '\ + '> Personal)') newline() else: newline() print('error~! Failed to create certificate') newline() except: newline() print('error~! Operation terminated') newline()
def active_directory_deployment(command): try: domain_loop = 1 newline() while domain_loop == 1: domain = input('input~! Enter a domain name: ') if any(domain) == True: domain_loop = 0 break else: pass ip_loop = 1 newline() while ip_loop == 1: ip = input( 'input~! Enter a static IP address for the DNS server: ') if any(ip) == True \ and '.' in ip: octets = ip.split('.') for decimal in octets: integer = int(decimal) if integer < 0 \ or integer > 255: newline() print('error~! Invalid IP address.') newline() ip_loop = 0 return else: pass print('notify~! Checking static IP addresses for entry') check_ip = pshell_decoder( 'Get-NetIPAddress -AddressFamily IPv4 | Select-Object -Property IPAddress | Format-Table -HideTableHeaders' ) clean_output = check_ip.replace('\r', '') cleaner_output = clean_output.lstrip(' ') ip_address_list = cleaner_output.split('\n') ticker = 1 for ip_address in ip_address_list: ticker = ticker + 1 if ip == ip_address.strip(' '): print('notify~! Static IP validated') ip_loop = 0 break else: if len(ip_address_list) == ticker - 1: newline() print('error~! This IP address is not configured. '\ + 'Use \'show ip address\' for a list') newline() ip_loop = 0 return else: pass ip_loop = 0 else: pass pass_loop = 1 newline() try: while pass_loop == 1: smap = getpass( 'input~! Enter a Safemode Administrator Password: '******'input~! Confirm the Safemode '\ + 'Administrator Password: '******'error~! Your password must be at least 10 characters and contain uppercase, lowercase, symbols, and numbers' ) newline() pass_loop2 = 0 else: newline() print( 'error~! Your password must be at least 10 characters and contain uppercase, lowercase, symbols, and numbers' ) newline() pass_loop2 = 0 else: newline() print('error~! Password mismatch. Try again.') newline() pass_loop2 = 0 except: newline() print('error~! Operation has been terminated') newline() return except: newline() print('error~! Operation terminated unexpectedly') newline() return print('notify~! Checking for existing AD-DS installation') check_adds_install = pshell_decoder( 'Get-WindowsFeature -Name AD-Domain-Services | Format-Table -HideTableHeaders' ) if 'Get-WindowsFeature' in check_adds_install: newline() print('error~! This command requires Windows Server OS') newline() return else: clean_output = check_adds_install.replace('\r\n', '') split_output = clean_output.split() install_state = split_output[6] if install_state == 'Installed': print('notify~! AD-DS is installed. Skipping...') pass else: print('notify~! AD-DS not found. Installing...') subprocess.call([ 'powershell.exe', 'Install-WindowsFeature -Name AD-Domain-Services -IncludeAllSubFeature | Out-Null' ]) print('notify~! AD-DS installed successfully') print('notify~! Checking for existing DNS installation') check_dns_install = pshell_decoder( 'Get-WindowsFeature -Name DNS | Format-Table -HideTableHeaders') clean_output = check_dns_install.replace('\r\n', '') split_output = clean_output.split() if split_output[4] == 'Installed': print('notify~! DNS is installed. Skipping...') pass else: print('notify~! DNS not found. Installing...') pshell_decoder( 'Install-WindowsFeature -Name DNS -IncludeAllSubFeature | Out-Null' ) print('notify~! DNS installed successfully') # install the ADDSDeployment module print('notify~! Installing AD-DS deployment module') subprocess.call(['powershell.exe', 'Import-Module ADDSDeployment']) print('notify~! Configuring DNS forward lookup zone') create_fwd_zone = pshell_decoder( 'Add-DnsServerPrimaryZone -Name {} -ReplicationScope Forest -PassThru'. format(domain)) print('notify~! Creating AD-DS forest') install_forest = pshell_decoder( 'Install-ADDSForest -DomainName “{}” -SafemodeAdministratorPassword (ConvertTo-SecureString "{}" -AsPlainText -Force)' .format(domain, smap_confirmed)) newline() parse_output = install_forest.split('.') for item in parse_output: if item == ' Role change is in progress or this computer needs to be restarted': newline() print( 'error~! Incomplete installations detected. Use \'win reboot\' and run this command again.' ) newline() return
def deploy_bgp(): newline() input_loop = 1 while input_loop == 1: pre_reqs = input( 'notify~! RSAT and RRAS are required to enable BGP. Install now? (y/n) ' ) if pre_reqs in yes: input_loop = 0 elif pre_reqs in no: input_loop = 0 return routing_lookup = installDict.install.get('install feature routing') rsat_lookup = installDict.install.get('install feature rsat') print('notify~! Installing RRAS routing features') install_routing = pshell_decoder(routing_lookup) if 'The term \'Install-WindowsFeature\' is not recognized' in install_routing: print( 'notify~! This command is supported only on Windows Server machines' ) newline() return if 'NoChangeNeeded' in install_routing: print('notify~! Dependency already met: routing') pass print('notify~! Installing RSAT') install_rsat = pshell_decoder(rsat_lookup) if 'NoChangeNeeded' in install_rsat: print('notify~! Dependency already met: rsat') pass if 'ArgumentNotValid:' in install_routing\ or 'ArgumentNotValid' in install_rsat: print('notify~! Feature is either unknown or has unmet dependencies.') newline() input_loop = 1 while input_loop == 1: bgp_peer = input( 'notify~! Enter a name for the new BGP peer profile: ') if any(bgp_peer) == True: input_loop = 0 pass input_loop = 1 while input_loop == 1: bgp_local_ip = input( 'notify~! Enter the local IP address used for BGP peering: ') if any(bgp_local_ip) == True: split_ip = bgp_local_ip.split('.') if len(split_ip) == 4: for octet in split_ip: if int(octet) < 0 or int(octet) > 255: print('\nerror~! Invalid IP address.\n') else: input_loop = 0 pass input_loop = 1 while input_loop == 1: bgp_remote_ip = input( 'notify~! Enter the remote IP address used by your BGP peer: ') if any(bgp_remote_ip) == True: split_ip = bgp_remote_ip.split('.') if len(split_ip) == 4: for octet in split_ip: if int(octet) < 0 or int(octet) > 255: print('\nerror~! Invalid IP address.\n') else: input_loop = 0 pass else: print('\nerror~! Invalid IP address.\n') input_loop = 1 while input_loop == 1: bgp_local_asn = input( 'notify~! Enter the local autonomous system number: ') if any(bgp_local_asn) == True: input_loop = 0 pass input_loop = 1 while input_loop == 1: bgp_remote_asn = input('notify~! Enter the remote autonomous '\ + 'system number: ') if any(bgp_remote_asn) == True: input_loop = 0 pass print('notify~! Enabling BGP routing') subprocess.call([ 'powershell.exe', 'Install-RemoteAccess -VpnType RoutingOnly | Out-Null' ]) print('notify~! Dependencies installed successfully.') bgp_routing('bgp id {} {}'.format(bgp_local_ip, bgp_local_asn)) bgp_routing('bgp peer {} {} {} {}'.format(bgp_peer, bgp_remote_ip, bgp_remote_asn, bgp_local_ip))
def ip_tcp_config(ip_tcp_arg): if 'ip tcp port-range' in ip_tcp_arg: split_arg = ip_tcp_arg.split(' ') if split_arg[4] == 'to': range_begin = split_arg[3] range_end = split_arg[5] begin_integer = int(range_begin) end_integer = int(range_end) dif = end_integer - begin_integer str_dif = str(dif) subprocess.call(['powershell.exe','set-nettcpsetting '\ + '-DynamicPortRangeStartPort ' + range_begin \ + ' -DynamicPortRangeNumberOfPorts '+str_dif+' ']) newline() print('notify~! Ephemeral port range for client tcp connections'\ +' changed to %s - %s.' % (range_begin,range_end)) newline() else: pass elif ip_tcp_arg == 'ip tcp window-restart enable': set_tcp_provider = pshell_decoder('set-nettcpsetting -CwndRestart true') if 'Property CwndRestart is read-only' in set_tcp_provider: print('error~! Command not supported for this OS.'\ +' Enterprise or Server edition required.') else: print('notify~! TCP congestion window restart has'\ +' been enabled for the local host.') elif ip_tcp_arg == 'ip tcp window-restart disable': set_tcp_provider = pshell_decoder('set-nettcpsetting -CwndRestart false') if 'Property CwndRestart is read-only' in set_tcp_provider: os_error_message() else: newline() print('notify~! TCP congestion window restart has'\ +' been disabled for the local host.') newline() elif 'ip tcp provider' in ip_tcp_arg: split_arg = ip_tcp_arg.split(' ') provider_type = split_arg[3] if 'ctcp' in provider_type: newline() print('notify~! Checking provider compatibility') set_tcp_provider = pshell_decoder('set-nettcpsetting '\ +'-CongestionProvider CTCP') if 'Property CongestionProvider is read-only' in set_tcp_provider: os_error_message() else: provider_announcement('CTCP') elif 'dctcp' in provider_type: newline() print('notify~! Checking provider compatibility') set_tcp_provider = pshell_decoder('set-nettcpsetting -CongestionProvider DCTCP') if 'Property CongestionProvider is read-only' in set_tcp_provider: os_error_message() else: provider_announcement('DCTCP') elif 'new-reno' in provider_type: newline() print('notify~! Checking provider compatibility') set_tcp_provider = pshell_decoder('set-nettcpsetting -CongestionProvider Default') if 'Property CongestionProvider is read-only' in set_tcp_provider: os_error_message() else: provider_announcement('NewReno') else: pass
def ip_address_config(ip_address_arg): split_arg = ip_address_arg.split(' ') if len(split_arg) == 6: ip_address = split_arg[2] subnet_mask = split_arg[3] default_gateway = split_arg[4] interface_index = split_arg[5] cidr_lookup = cidr_dictionary.get(subnet_mask) check_status = pshell_decoder('Get-NetAdapter -InterfaceIndex {} | Format-Table -HideTableHeaders -AutoSize'.format(interface_index)) if 'Disconnected' in check_status.strip(): newline() print('error~! The specified interface is disabled.') newline() return print('notify~! Initializing route table lookup') route_lookup = pshell_decoder('get-netroute -addressfamily ipv4 | '\ +'select-object -property destinationprefix') print('notify~! Route lookup succeeded') if '0.0.0.0/0' in route_lookup.split('\n'): print('notify~! Flushing old default route from table') subprocess.call(['powershell', 'Remove-NetRoute -InterfaceIndex '\ + interface_index + '-destinationprefix 0.0.0.0/0 -Confirm:$False'\ + ' | Out-Null']) remove_address = pshell_decoder('Remove-NetIpAddress -InterfaceIndex '\ + interface_index +' -AddressFamily IPv4 -Confirm:$False | '\ + 'Out-Null') if 'Default loopback address cannot be deleted' in remove_address: newline() print('error~! Cannot change the default loopback address.') newline() else: print('notify~! Configuring address') subprocess.call(['powershell.exe','Set-NetIPInterface -InterfaceIndex'\ ' ' + interface_index + ' -Dhcp Disabled | Out-Null']) print('notify~! Disabling DHCP') gateway_config = pshell_decoder('New-NetIPAddress -InterfaceIndex '\ + interface_index +' -IPAddress '+ip_address \ + ' -PrefixLength '+ cidr_lookup +' -DefaultGateway '\ + default_gateway) print('notify~! Restarting adapter') get_int_list = pshell_decoder('Get-NetAdapter -InterfaceIndex {} | Select-Object Name | Format-Table -AutoSize'.format(interface_index)) split_list = get_int_list.split('----') get_name = split_list[1] int_name = '\'' + get_name.strip() + '\'' reset_adapter = pshell_decoder('Restart-NetAdapter -Name {}'.format(int_name)) if 'Instance DefaultGateway already exists' in gateway_config: assign_address = pshell_decoder('New-NetIPAddress -InterfaceIndex '\ + interface_index +' -IPAddress ' + ip_address + ' -PrefixLength ' \ + cidr_lookup + ' | Out-Null') if 'Inconsistent parameters PolicyStore' in assign_address: newline() print('error~! Interface \'{}\' is disabled. Please enable it and try again.'.format(interface_index)) newline() elif 'The object already exists.' in assign_address: newline() print('error~! Address overlaps with another interface.') newline() else: newline() print('notify~! IP address {}/{} has been configured for the interface. GW={}'.format(ip_address,cidr_lookup, default_gateway)) newline() else: pass elif len(split_arg) == 5 \ and '255' in split_arg[3]: ip_address = split_arg[2] subnet_mask = split_arg[3] interface_index = split_arg[4] cidr_lookup = cidr_dictionary.get(subnet_mask,\ '\nnotify~! Invalid subnet mask.\n') newline() print('notify~! Clearing interface IP config') subprocess.call(['powershell.exe', 'Remove-NetIpAddress'\ + ' -InterfaceIndex '+interface_index+' -AddressFamily '\ + 'IPv4 -Confirm:$False | Out-Null']) print('notify~! Configuring interface IP') assign_address = pshell_decoder('New-NetIPAddress '+ '-InterfaceIndex'\ + ' ' + interface_index + ' -IPAddress ' + ip_address + ' -PrefixLength'\ + ' ' + cidr_lookup + ' | Out-Null') if 'The object already exists.' in assign_address: newline() print('error~! Address overlaps with another interface.') newline() else: print('notify~! Restarting adapter') get_int_list = pshell_decoder('Get-NetAdapter -InterfaceIndex {} | Select-Object Name | Format-Table -AutoSize'.format(interface_index)) split_list = get_int_list.split('----') get_name = split_list[1] int_name = '\'' + get_name.strip() + '\'' reset_adapter = pshell_decoder('Restart-NetAdapter -Name {}'.format(int_name)) print('notify~! Address {}/{} has been configured.'.format(ip_address, cidr_dictionary.get(subnet_mask))) newline() elif len(split_arg) == 4 \ and '/' in split_arg[2]: prefix = split_arg[2] split_prefix = prefix.split('/') prefix_length = split_prefix[1] ip_address = split_prefix[0] interface_index = split_arg[3] if int(prefix_length) < 1 \ or int(prefix_length) > 32: newline() print('error~! Invalid prefix length. Range = 1 - 32') newline() pass else: newline() print('notify~! Clearing interface IP config') subprocess.call(['powershell.exe', 'Remove-NetIpAddress'\ + ' -InterfaceIndex '+interface_index+' -AddressFamily '\ + 'IPv4 -Confirm:$False | Out-Null']) print('notify~! Configuring interface IP') assign_address = pshell_decoder('New-NetIPAddress '+ '-InterfaceIndex'\ + ' ' + interface_index + ' -IPAddress ' + ip_address + ' -PrefixLength'\ + ' ' + prefix_length + ' | Out-Null') if 'The object already exists.' in assign_address: newline() print('error~! Address overlaps with another interface.') newline() else: print('notify~! Restarting adapter') get_int_list = pshell_decoder('Get-NetAdapter -InterfaceIndex {} | Select-Object Name | Format-Table -AutoSize'.format(interface_index)) split_list = get_int_list.split('----') get_name = split_list[1] int_name = '\'' + get_name.strip() + '\'' reset_adapter = pshell_decoder('Restart-NetAdapter -Name {}'.format(int_name)) print('notify~! Address {}/{} has been configured.'.format(ip_address, prefix_length)) newline() elif len(split_arg) == 5 \ and '/' in split_arg[2] \ and '.' in split_arg[3]: default_gateway = split_arg[3] interface_index = split_arg[4] prefix = split_arg[2] split_prefix = prefix.split('/') prefix_length = split_prefix[1] ip_address = split_prefix[0] if int(prefix_length) < 8 \ or int(prefix_length) > 32: newline() print('error~! Invalid prefix length. Range = 1 - 32') newline() pass else: check_status = pshell_decoder('Get-NetAdapter -InterfaceIndex {} | Format-Table -HideTableHeaders -AutoSize'.format(interface_index)) if 'Disconnected' in check_status.strip(): newline() print('error~! The specified interface is disabled.') newline() return newline() print('notify~! Initializing route table lookup') route_lookup = pshell_decoder('get-netroute -addressfamily ipv4 | '\ +'select-object -property destinationprefix') print('notify~! Route lookup succeeded') if '0.0.0.0/0' in route_lookup.split('\n'): print('notify~! Flushing old default route from table') subprocess.call(['powershell', 'Remove-NetRoute -InterfaceIndex '\ +interface_index+' -destinationprefix 0.0.0.0/0 -Confirm:$False'\ + ' | Out-Null']) remove_address = pshell_decoder('Remove-NetIpAddress -InterfaceIndex '\ +interface_index+' -AddressFamily IPv4 -Confirm:$False | '\ + 'Out-Null') if 'Default loopback address cannot be deleted' in remove_address: newline() print('error~! Cannot change the default loopback address.') newline() else: print('notify~! Disabling DHCP') subprocess.call(['powershell.exe','Set-NetIPInterface -InterfaceIndex'\ ' ' + interface_index + ' -Dhcp Disabled | Out-Null']) print('notify~! Configuring address') gateway_config = pshell_decoder('New-NetIPAddress -InterfaceIndex '\ + interface_index +' -IPAddress '+ip_address \ +' -PrefixLength '+ prefix_length +' -DefaultGateway '\ + default_gateway) print('notify~! Restarting adapter') get_int_list = pshell_decoder('Get-NetAdapter -InterfaceIndex {} | Select-Object Name | Format-Table -AutoSize'.format(interface_index)) split_list = get_int_list.split('----') get_name = split_list[1] int_name = '\'' + get_name.strip() + '\'' reset_adapter = pshell_decoder('Restart-NetAdapter -Name {}'.format(int_name)) if 'Instance DefaultGateway already exists' in gateway_config: assign_address = pshell_decoder('New-NetIPAddress -InterfaceIndex '\ + interface_index +' -IPAddress ' + ip_address + ' -PrefixLength ' \ + prefix_length + ' | Out-Null') if 'Inconsistent parameters PolicyStore' in assign_address: newline() print('error~! Interface \'{}\' is disabled. Please enable it and try again.'.format(interface_index)) newline() elif 'The object already exists.' in assign_address: newline() print('error~! Address overlaps with another interface.') newline() else: newline() print('notify~! IP address {}/{} has been configured for the interface. GW={}'.format(ip_address,prefix_length, default_gateway)) newline() else: pass
def bgp_routing(bgp_command): split_cmd = bgp_command.split(' ') if split_cmd[1] == 'hold-time'\ and len(split_cmd) == 4: peer_name = split_cmd[3] hold_time = split_cmd[2] set_holdtime = pshell_decoder( 'Set-BgpPeer -Name {} -HoldTimeSec {}'.format( peer_name, hold_time)) if 'Set-BgpPeer' in set_holdtime: newline() print('notify~! Peer does not exist. Use \'bgp peer\'') newline() else: newline() print('notify~! BGP hold timer for peer {} set to {}s'.format( peer_name, hold_time)) newline() elif split_cmd[1] == 'weight'\ and len(split_cmd) == 4: peer_name = split_cmd[3] weight = split_cmd[2] input_loop = 1 newline() while input_loop == 1: reset_accept = input('notify~! Adjusting BGP metrics will cause a'\ +' BGP session reset. Continue? (y/n) ') if reset_accept in yes: input_loop = 0 pshell_cmd = 'Set-BgpPeer -Name {} -Weight {} -Force '.format( peer_name, weight) set_metric = pshell_decoder(pshell_cmd) if 'Set-BgpPeer' in set_metric: newline() print('notify~! Peer does not exist. Use \'bgp peer\'') newline() else: newline() print('notify~! Peer {} configured with weight {}'.format( peer_name, weight)) newline() elif reset_accept in no: newline() print('Terminating operation...') newline() else: pass # BGP initialization script elif split_cmd[1] == 'enable': newline() input_loop = 1 while input_loop == 1: pre_reqs = input('notify~! RSAT and RRAS are required to enable BGP.'\ + ' Install now? (y/n) ') if pre_reqs in yes: input_loop = 0 routing_lookup = installDict.install.get( 'install feature routing') rsat_lookup = installDict.install.get('install feature rsat') print('notify~! Installing RRAS routing features') install_routing = pshell_decoder(routing_lookup) if 'The term \'Install-WindowsFeature\' is not recognized' in install_routing: print( 'notify~! This command is supported only on Windows Server machines' ) newline() return if 'NoChangeNeeded' in install_routing: print('notify~! Dependency already met: routing') pass print('notify~! Installing RSAT') install_rsat = pshell_decoder(rsat_lookup) if 'NoChangeNeeded' in install_rsat: print('notify~! Dependency already met: rsat') pass if 'ArgumentNotValid:' in install_routing\ or 'ArgumentNotValid' in install_rsat: print( 'notify~! Feature is either unknown or has unmet dependencies.' ) newline() else: bgp_install() elif pre_reqs in no: input_loop = 0 bgp_install() else: pass elif split_cmd[1] == 'advertise'\ and '.' in split_cmd[2]\ and '/' in split_cmd [2]: # Add-BgpCustomRoute advertise_route = pshell_decoder( 'Add-BgpCustomRoute -Network {}'.format(split_cmd[2])) if 'The term \'Add-BgpCustomRoute\' is not recognized' in advertise_route: newline() print( 'notify~! BGP is not enabled on this machine. Use \'bgp enable\' and \'bgp id\' first.' ) newline() elif 'Add-BgpCustomRoute' in advertise_route: newline() print('error~! Invalid prefix.') newline() else: pass elif split_cmd[1] == 'advertise'\ and '.' in split_cmd[2]\ and '.' in split_cmd[3]: # Add-BgpCustomRoute network_address = split_cmd[2] subnet_mask = split_cmd[3] split_net = network_address.split('.') split_mask = subnet_mask.split('.') for octet in split_net: numberize = Decimal(octet) if numberize < 0 \ or numberize > 255: newline() print('error~! Invalid network address') newline() return else: pass for octet in split_mask: numberize = Decimal(octet) if numberize < 0 \ or numberize > 255: newline() print('error~! Invalid subnet mask') newline() return else: pass mask_to_prefix_lookup = conversion.cidr_dictionary.get(subnet_mask) advertise_route = pshell_decoder( 'Add-BgpCustomRoute -Network {}/{}'.format(network_address, mask_to_prefix_lookup)) if 'The term \'Add-BgpCustomRoute\' is not recognized' in advertise_route: newline() print( 'notify~! BGP is not enabled on this machine. Use \'bgp enable\' and \'bgp id\' first.' ) newline() else: pass elif split_cmd[2] == 'advertise'\ and '.' in split_cmd[3]\ and '/' in split_cmd [3]\ and split_cmd[0] == 'no': # Add-BgpCustomRoute remove_route = pshell_decoder( 'Remove-BgpCustomRoute -Network {} -Force'.format(split_cmd[3])) if 'The term \'Remove-BgpCustomRoute\' is not recognized' in remove_route: newline() print( 'notify~! BGP is not enabled on this machine. Use \'bgp enable\' and \'bgp id\' first.' ) newline() elif 'Remove-BgpCustomRoute' in remove_route: newline() print('error~! Invalid prefix.') newline() else: pass elif split_cmd[2] == 'advertise'\ and '.' in split_cmd[3]\ and '.' in split_cmd[4]\ and split_cmd[0] == 'no': # Add-BgpCustomRoute network_address = split_cmd[3] subnet_mask = split_cmd[4] split_net = network_address.split('.') split_mask = subnet_mask.split('.') for octet in split_net: numberize = Decimal(octet) if numberize < 0 \ or numberize > 255: newline() print('error~! Invalid network address') newline() return else: pass for octet in split_mask: numberize = Decimal(octet) if numberize < 0 \ or numberize > 255: newline() print('error~! Invalid subnet mask') newline() return else: pass mask_to_prefix_lookup = conversion.cidr_dictionary.get(subnet_mask) remove_route = pshell_decoder( 'Remove-BgpCustomRoute -Network {}/{} -Force'.format( network_address, mask_to_prefix_lookup)) if 'The term \'Remove-BgpCustomRoute\' is not recognized' in advertise_route: newline() print( 'notify~! BGP is not enabled on this machine. Use \'bgp enable\' and \'bgp id\' first.' ) newline() else: pass elif split_cmd[1] == 'aggregate' \ and '.' in split_cmd[2]: # bgp aggregate 172.16.1.0/24 prefix = split_cmd[2] if len(split_cmd) == 3: advertise_prefix = pshell_decoder( 'Add-BgpRouteAggregate -Prefix {} -SummaryOnly Disabled -Force' .format(prefix)) elif len(split_cmd) == 4 \ and split_cmd[3] == 'summary-only': advertise_prefix = pshell_decoder( 'Add-BgpRouteAggregate -Prefix {} -SummaryOnly Enabled -Force'. format(prefix)) if ' A More or Less specific prefix' in advertise_prefix: newline() print('notify~! Prefix is already advertised.') newline() elif ' The parameter is incorrect.' in advertise_prefix: newline() print( 'notify~! Invalid prefix. Use CIDR notation (e.g. \'172.16.1.0/24\') and' ) print( 'notify~! keep the entered network address on bit boundaries.') newline() elif ' BGP is not configured' in advertise_prefix: newline() print( 'notify~! BGP is not enabled for this machine. Use \'bgp id\'') newline() elif 'Add-BgpRouteAggregate' in advertise_prefix: newline() print( 'notify~! This machine has unmet dependencies for BGP routing. Use \'bgp enable\'' ) newline() else: newline() print('notify~! Route to prefix {} is being advertised to peers'. format(prefix)) newline() # Option for removal of BGP router id ("no bgp id x.x.x.x") elif split_cmd[2] == 'id' \ and split_cmd[0] == 'no': remove_router = pshell_decoder('Remove-BgpRouter -Force') if 'Remove-BgpRouter' in remove_router: newline() print('notify~! BGP is not enabled for this machine') newline() else: newline() print('notify~! The local BGP routing instance has been deleted') newline() # Configure local BGP identity elif split_cmd[1] == 'id'\ and '.' in split_cmd[2]: # bgp id 10.0.0.33 64512 router_id = split_cmd[2] local_as = split_cmd[3] if int(local_as) > 65535\ or int(local_as) < 1: print('notify~! Invalid autonomous system number') newline() else: check_for_bgp = pshell_decoder('Get-BgpRouter | Out-Null') if 'Get-BgpRouter ' in check_for_bgp: newline() print('notify~! Creating BGP routing instance') pshell_cmd = 'Add-BgpRouter -BgpIdentifier {} -LocalASN {}'.format( router_id, local_as) init_bgp = pshell_decoder(pshell_cmd) if ' LAN Routing not configured.' in init_bgp: print('error~! Missing dependencies. Use \'bgp enable\'') newline() return else: with open('.\\miscellaneous\\asn.txt', 'w') as file: file.write(local_as) print( 'notify~! BGP routing identity created. RID={} AS={}'. format(router_id, local_as)) newline() else: newline() print('notify~! Modifying BGP routing instance') pshell_cmd = 'Set-BgpRouter -BgpIdentifier {} -LocalASN {}'.format( router_id, local_as) init_bgp = pshell_decoder(pshell_cmd) with open('.\\miscellaneous\\asn.txt', 'w') as file: file.write(local_as) print( 'notify~! BGP routing identity has been modifed. RID={} AS={}' .format(router_id, local_as)) newline() elif split_cmd[2] == 'aggregate' \ and split_cmd[0] == 'no' \ and '.' in split_cmd[3]: # no bgp network 172.16.1.0/24 prefix = split_cmd[3] remove_prefix = pshell_decoder( 'Remove-BgpRouteAggregate -Prefix {} -Force'.format(prefix)) if ' The parameter is incorrect.' in remove_prefix: newline() print( 'notify~! Invalid prefix. Use CIDR notation (e.g. \'172.16.1.0/24\') and' ) print( 'notify~! keep the entered network address on bit boundaries.') newline() elif ' BGP is not configured.' in remove_prefix: newline() print( 'notify~! BGP is not enabled for this machine. Use \'bgp id\'') newline() elif ' Aggregate' in remove_prefix: newline() print('notify~! This prefix is not being advertised') newline() elif 'Remove-BgpRouteAggregate' in remove_prefix: newline() print( 'notify~! This machine has unmet dependencies for BGP routing. Use \'bgp enable\'' ) newline() else: newline() print('notify~! Aggregate {} no longer advertised'.format(prefix)) newline() elif split_cmd[2] == 'peer' \ and split_cmd[0] == 'no': peer_name = split_cmd[3] rm_peer = pshell_decoder( 'Remove-BgpPeer -Name {} -Force'.format(peer_name)) if 'Remove-BgpPeer' in rm_peer: newline() print('notify~! Peer {} does not exist.'.format(peer_name)) newline() else: newline() print('notify~! Peer profile {} was deleted'.format(peer_name)) newline() elif split_cmd[1] == 'peer' \ and len(split_cmd) <= 6: check_for_id = pshell_decoder('Get-BgpRouter | Out-Null') if 'Get-BgpRouter' in check_for_id: newline() print( 'notify~! You must create a BGP identity first. Use \'bgp id\'' ) newline() pass # bgp peer OK-Site 10.0.0.1 64512 192.168.1.1 # bgp peer mypeer 10.0.0.254 else: if len(split_cmd) == 6 \ and '.' in split_cmd[3]: peer_name = split_cmd[2] peer_address = split_cmd[3] remote_as = split_cmd[4] local_address = split_cmd[5] if int(remote_as) > 65535 \ or int(remote_as) < 1: newline() print('notify~! Invalid autonomous system number') newline() else: try: with open('.\\miscellaneous\\asn.txt', 'r') as file: read_asn = file.read() newline() print('notify~! Configuring BGP peer...') pshell_cmd = 'Add-BgpPeer -Name {} -PeerIPAddress {} -PeerASN {} -LocalIPAddress {} -LocalASN {}'.format( peer_name, peer_address, remote_as, local_address, read_asn) add_peer = pshell_decoder(pshell_cmd) print( 'notify~! BGP peering with {} (AS {}) has been enabled' .format(peer_address, remote_as)) newline() except: newline() print( 'error~! Local ASN has not been configured. Use \'bgp id\'' ) newline() elif len(split_cmd) == 4 \ and '.' in split_cmd[3]: peer_name = split_cmd[2] peer_address = split_cmd[3] set_peer_ip = pshell_decoder( 'Set-BgpPeer -Name {} -PeerIPAddress {} -Force'.format( peer_name, peer_address)) if 'Set-BgpPeer' in set_peer_ip: newline() print('notify~! Peer does not exist. Use \'bgp peer\'') newline() else: newline() print('notify~! Address for peer {} set to {}'.format( peer_name, peer_address)) newline() elif len(split_cmd) == 4 \ and '.' not in split_cmd[3]: peer_name = split_cmd[2] remote_as = split_cmd[3] set_peer_as = pshell_decoder( 'Set-BgpPeer -Name {} -PeerASN {} -Force'.format( peer_name, remote_as)) if 'Set-BgpPeer' in set_peer_ip: newline() print('notify~! Peer does not exist. Use \'bgp peer\'') newline() else: newline() print('notify~! ASN for peer {} set to {}'.format( peer_name, remote_as)) newline() elif len(split_cmd) == 5 \ and '.' in split_cmd[3] \ and split_cmd[4] == 'local': # bgp peer mypeer 10.0.0.1 local peer_name = split_cmd[2] local_ip = split_cmd[3] set_local_ip = pshell_decoder( 'Set-BgpPeer -Name {} -LocalIPAddress {} -Force'.format( peer_name, local_ip)) if 'Set-BgpPeer' in set_local_ip: newline() print('notify~! Peer does not exist. Use \'bgp peer\'') newline() else: newline() print('notify~! Local IP set to {} for peer {}'.format( local_ip, peer_name)) newline() else: newline() print('error~! Invalid command.') newline()