├── nordvpn_switcher ├── nordvpn_switcher │ ├── NordVPN_options │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ └── __init__.cpython-38.pyc │ │ ├── options_linux.txt │ │ └── countrylist.txt │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ └── nordvpn_switch.cpython-38.pyc │ ├── demo.py │ └── nordvpn_switch.py ├── NordVPN_options │ ├── options_linux.txt │ └── countrylist.txt ├── demo.py └── nordvpn_switch.py ├── .idea ├── .gitignore ├── vcs.xml ├── misc.xml ├── inspectionProfiles │ └── profiles_settings.xml ├── rSettings.xml ├── modules.xml ├── rGraphicsSettings.xml └── nordvpn switcher.iml ├── README.md └── nordvpn_switch.py /nordvpn_switcher/nordvpn_switcher/NordVPN_options/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /nordvpn_switcher/nordvpn_switcher/__init__.py: -------------------------------------------------------------------------------- 1 | from .nordvpn_switch import initialize_VPN,rotate_VPN,terminate_VPN 2 | from .nordvpn_switch import NordVPN_options -------------------------------------------------------------------------------- /nordvpn_switcher/nordvpn_switcher/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kboghe/NordVPN-switcher/HEAD/nordvpn_switcher/nordvpn_switcher/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /nordvpn_switcher/nordvpn_switcher/__pycache__/nordvpn_switch.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kboghe/NordVPN-switcher/HEAD/nordvpn_switcher/nordvpn_switcher/__pycache__/nordvpn_switch.cpython-38.pyc -------------------------------------------------------------------------------- /nordvpn_switcher/nordvpn_switcher/NordVPN_options/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kboghe/NordVPN-switcher/HEAD/nordvpn_switcher/nordvpn_switcher/NordVPN_options/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /.idea/rSettings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/rGraphicsSettings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | -------------------------------------------------------------------------------- /.idea/nordvpn switcher.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /nordvpn_switcher/NordVPN_options/options_linux.txt: -------------------------------------------------------------------------------- 1 | Available options: 2 | nordvpn set cybersec on or off - Enable or disable CyberSec 3 | nordvpn set killswitch on or off - Enable or disable Kill Switch 4 | nordvpn set autoconnect on or off - Enable or disable auto-connect. Example: nordvpn set autoconnect on us2435. 5 | 6 | nordvpn set notify on or off - Enable or disable notifications 7 | nordvpn set dns 1.1.1.1 1.0.0.1 - Set custom DNS (you can set up a single DNS or two like shown in this command). 8 | nordvpn set protocol udp or tcp - Switch between UDP and TCP protocols 9 | nordvpn set obfuscate on or off - Enable or disable Obfuscated Servers. 10 | nordvpn set technology - Set connection technology (OpenVPN or NordLynx) 11 | 12 | nordvpn whitelist add port 22 - Add a rule to whitelist a specified incoming port. (separate multiple ports with a space) 13 | nordvpn whitelist remove port 22 - Remove the rule to whitelist a specified port. 14 | nordvpn whitelist add subnet 192.168.0.0/16 - Add a rule to whitelist a specified subnet. 15 | nordvpn whitelist remove subnet 192.168.0.0/16 - Remove the rule to whitelist a specified subnet. -------------------------------------------------------------------------------- /nordvpn_switcher/nordvpn_switcher/NordVPN_options/options_linux.txt: -------------------------------------------------------------------------------- 1 | Available options: 2 | nordvpn set cybersec on or off - Enable or disable CyberSec 3 | nordvpn set killswitch on or off - Enable or disable Kill Switch 4 | nordvpn set autoconnect on or off - Enable or disable auto-connect. Example: nordvpn set autoconnect on us2435. 5 | 6 | nordvpn set notify on or off - Enable or disable notifications 7 | nordvpn set dns 1.1.1.1 1.0.0.1 - Set custom DNS (you can set up a single DNS or two like shown in this command). 8 | nordvpn set protocol udp or tcp - Switch between UDP and TCP protocols 9 | nordvpn set obfuscate on or off - Enable or disable Obfuscated Servers. 10 | nordvpn set technology - Set connection technology (OpenVPN or NordLynx) 11 | 12 | nordvpn whitelist add port 22 - Add a rule to whitelist a specified incoming port. (separate multiple ports with a space) 13 | nordvpn whitelist remove port 22 - Remove the rule to whitelist a specified port. 14 | nordvpn whitelist add subnet 192.168.0.0/16 - Add a rule to whitelist a specified subnet. 15 | nordvpn whitelist remove subnet 192.168.0.0/16 - Remove the rule to whitelist a specified subnet. -------------------------------------------------------------------------------- /nordvpn_switcher/NordVPN_options/countrylist.txt: -------------------------------------------------------------------------------- 1 | United Kingdom 2 | Germany 3 | France 4 | Netherlands 5 | Sweden 6 | Switzerland 7 | Denmark 8 | Italy 9 | Norway 10 | Spain 11 | Belgium 12 | Poland 13 | Ireland 14 | Czech Republic 15 | Austria 16 | Finland 17 | Portugal 18 | Ukraine 19 | Serbia 20 | Hungary 21 | Greece 22 | Latvia 23 | Luxembourg 24 | Romania 25 | Bulgaria 26 | Estonia 27 | Slovakia 28 | Iceland 29 | Albania 30 | Cyprus 31 | Croatia 32 | Slovenia 33 | Bosnia and Herzegovina 34 | Georgia 35 | Moldova 36 | North Macedonia 37 | United States 38 | Canada 39 | Brazil 40 | Argentina 41 | Mexico 42 | Chile 43 | Costa Rica 44 | Australia 45 | South Africa 46 | India 47 | United Arab Emirates 48 | Israel 49 | Turkey 50 | Australia 51 | Singapore 52 | Taiwan 53 | Japan 54 | Hong Kong 55 | New Zealand 56 | Indonesia 57 | Malaysia 58 | Vietnam 59 | South Korea 60 | Thailand 61 | Sydney 62 | Adelaide 63 | Brisbane 64 | Perth 65 | Melbourne 66 | Vancouver 67 | Toronto 68 | Montreal 69 | Frankfurt 70 | Berlin 71 | Mumbai 72 | Chennai 73 | Dallas 74 | Chicago 75 | Atlanta 76 | Miami 77 | Los Angeles 78 | New York 79 | San Francisco 80 | Seattle 81 | Buffalo 82 | Saint Louis 83 | Denver 84 | Manassas 85 | Charlotte 86 | Salk Lake City 87 | Phoenix 88 | Africa The Middle East And India 89 | Onion Over VPN 90 | Asia Pacific 91 | P2P 92 | Dedicated IP 93 | Standard VPN Servers 94 | Double VPN 95 | The Americas 96 | Europe -------------------------------------------------------------------------------- /nordvpn_switcher/nordvpn_switcher/NordVPN_options/countrylist.txt: -------------------------------------------------------------------------------- 1 | United Kingdom 2 | Germany 3 | France 4 | Netherlands 5 | Sweden 6 | Switzerland 7 | Denmark 8 | Italy 9 | Norway 10 | Spain 11 | Belgium 12 | Poland 13 | Ireland 14 | Czech Republic 15 | Austria 16 | Finland 17 | Portugal 18 | Ukraine 19 | Serbia 20 | Hungary 21 | Greece 22 | Latvia 23 | Luxembourg 24 | Romania 25 | Bulgaria 26 | Estonia 27 | Slovakia 28 | Iceland 29 | Albania 30 | Cyprus 31 | Croatia 32 | Slovenia 33 | Bosnia and Herzegovina 34 | Georgia 35 | Moldova 36 | North Macedonia 37 | United States 38 | Canada 39 | Brazil 40 | Argentina 41 | Mexico 42 | Chile 43 | Costa Rica 44 | Australia 45 | South Africa 46 | India 47 | United Arab Emirates 48 | Israel 49 | Turkey 50 | Australia 51 | Singapore 52 | Taiwan 53 | Japan 54 | Hong Kong 55 | New Zealand 56 | Indonesia 57 | Malaysia 58 | Vietnam 59 | South Korea 60 | Thailand 61 | Sydney 62 | Adelaide 63 | Brisbane 64 | Perth 65 | Melbourne 66 | Vancouver 67 | Toronto 68 | Montreal 69 | Frankfurt 70 | Berlin 71 | Mumbai 72 | Chennai 73 | Dallas 74 | Chicago 75 | Atlanta 76 | Miami 77 | Los Angeles 78 | New York 79 | San Francisco 80 | Seattle 81 | Buffalo 82 | Saint Louis 83 | Denver 84 | Manassas 85 | Charlotte 86 | Salt Lake City 87 | Phoenix 88 | Africa The Middle East And India 89 | Onion Over VPN 90 | Asia Pacific 91 | P2P 92 | Dedicated IP 93 | Standard VPN Servers 94 | Double VPN 95 | The Americas 96 | Europe -------------------------------------------------------------------------------- /nordvpn_switcher/demo.py: -------------------------------------------------------------------------------- 1 | from nordvpn_switcher import initialize_VPN,rotate_VPN 2 | import time 3 | 4 | ############## 5 | ## WINDOWS ### 6 | ############## 7 | 8 | # [1] save settings file as a variable 9 | 10 | instructions = initialize_VPN() #this will guide you through a step-by-step guide, including a help-menu with connection options 11 | 12 | for i in range(3): 13 | rotate_VPN(instructions) #refer to the instructions variable here 14 | print('\nDo whatever you want here (e.g.scraping). Pausing for 10 seconds...\n') 15 | time.sleep(10) 16 | 17 | # [2] if you'd like to skip the step-by-step menu (because you want to automate your script fully without any required human intervention, use the area_input parameter 18 | 19 | instructions = initialize_VPN(area_input=['Belgium,France,Netherlands']) # <-- Be aware: the area_input parameter expects a list, not a string 20 | 21 | for i in range(3): 22 | rotate_VPN(instructions) #refer to the instructions variable here 23 | print('\nDo whatever you want here (e.g.scraping). Pausing for 10 seconds...\n') 24 | time.sleep(10) 25 | 26 | # [3] of course, you can try one of the built-in randomizers if you can't be bothered with selecting specific regions 27 | 28 | #The following options are avilable: 29 | #random countries X 30 | #random countries europe X 31 | #random countries americas X 32 | #random countries africa east india X 33 | #random countries asia pacific X 34 | #random regions australia X 35 | #random regions canada X 36 | #random regions germany X 37 | #random regions india X 38 | #random regions united states X 39 | 40 | instructions = initialize_VPN(area_input=['random countries europe 8']) 41 | 42 | for i in range(3): 43 | rotate_VPN(instructions) #refer to the instructions variable here 44 | print('\nDo whatever you want here (e.g.scraping). Pausing for 10 seconds...\n') 45 | time.sleep(10) 46 | 47 | # [4] instead of saving the instructions as a variable, you could save your settings in your work directory. Just set the save parameter to 1 48 | 49 | initialize_VPN(save=1) 50 | 51 | for i in range(3): 52 | rotate_VPN() #Call the rotate_VPN without any parameter. It will look for a settings file in your work directory 53 | print('\nDo whatever you want here (e.g.scraping). Pausing for 10 seconds...\n') 54 | time.sleep(10) 55 | 56 | # [5] If you'd like to use an already saved settings file in your work directory (for example: a colleague/friend has sent you his/her settings file), 57 | # use the stored settings parameter 58 | 59 | initialize_VPN(save=1,area_input = ['random countries 20']) #save settings file to work directory 60 | print('Imagine you close your python environment and run your script on a later date. Just load your saved settings by running the following line of code:\n') 61 | time.sleep(7) 62 | initialize_VPN(stored_settings=1) #the function will look for a settingsfile in your work directory, launch NordVPN, disconnect if necessary and validate the stored settings file. 63 | 64 | for i in range(3): 65 | rotate_VPN() 66 | print('\nDo whatever you want here (e.g.scraping). Pausing for 10 seconds...\n') 67 | time.sleep(10) 68 | 69 | 70 | # [6] save settings file to work directory and perform a 'complete rotation' 71 | 72 | # --> a complete rotation will fetch a list of the currently 4000+ active available servers of NordVPN. 73 | # The rotation will rotate between all the available servers completely by random. 74 | # The difference with picking particular regions is that NordVPN will NOT pick the 'most appropriate' (fastest) server within a particular region when rotating. 75 | # Instead, complete rotation will pick a specific server at random, which mens you're unlikely to revisit the same server twice in a row. 76 | # Because of this, the 'complete rotation' option is ideal for webscraping purposes 77 | 78 | initialize_VPN(save=1,area_input=['complete rotation']) 79 | 80 | for i in range(3): 81 | rotate_VPN() 82 | print('\nDo whatever you want here (e.g.scraping). Pausing for 10 seconds...\n') 83 | time.sleep(10) 84 | 85 | # [7] You can be as creative as you like. For example, the following code will perform an infinite loop of picking a random server every hour 86 | 87 | instructions = initialize_VPN(area_input=['complete rotation']) 88 | 89 | while True: 90 | rotate_VPN(instructions) 91 | time.sleep(3600) 92 | 93 | # [8] To implement the google and youtube captcha-check, use the google_check parameter 94 | 95 | instructions = initialize_VPN(area_input=['random regions united states 8']) 96 | 97 | for i in range(3): 98 | rotate_VPN(google_check = 1) 99 | print('\nDo whatever you want here (e.g.scraping). Pausing for 10 seconds...\n') 100 | time.sleep(10) 101 | 102 | ############## 103 | ## LINUX ##### 104 | ############## 105 | 106 | # [1] Perform a complete rotation and skip the settings menu for complete automation 107 | # the 'skip settings' parameter is only available for Linux users (since setting additional settings such as whitelisting ports is only available on Linux) 108 | 109 | instr = initialize_VPN(area_input=['complete rotation'],skip_settings=1) 110 | 111 | for i in range(3): 112 | rotate_VPN(instr) 113 | print('\nDo whatever you want here (e.g. scraping). Pausing for 10 seconds...\n') 114 | time.sleep(10) -------------------------------------------------------------------------------- /nordvpn_switcher/nordvpn_switcher/demo.py: -------------------------------------------------------------------------------- 1 | from nordvpn_switcher import initialize_VPN,rotate_VPN 2 | import time 3 | 4 | ############## 5 | ## WINDOWS ### 6 | ############## 7 | 8 | # [1] save settings file as a variable 9 | 10 | instructions = initialize_VPN() #this will guide you through a step-by-step guide, including a help-menu with connection options 11 | 12 | for i in range(3): 13 | rotate_VPN(instructions) #refer to the instructions variable here 14 | print('\nDo whatever you want here (e.g.scraping). Pausing for 10 seconds...\n') 15 | time.sleep(10) 16 | 17 | # [2] if you'd like to skip the step-by-step menu (because you want to automate your script fully without any required human intervention, use the area_input parameter 18 | 19 | instructions = initialize_VPN(area_input=['Belgium,France,Netherlands']) # <-- Be aware: the area_input parameter expects a list, not a string 20 | 21 | for i in range(3): 22 | rotate_VPN(instructions) #refer to the instructions variable here 23 | print('\nDo whatever you want here (e.g.scraping). Pausing for 10 seconds...\n') 24 | time.sleep(10) 25 | 26 | # [3] of course, you can try one of the built-in randomizers if you can't be bothered with selecting specific regions 27 | 28 | #The following options are avilable: 29 | #random countries X 30 | #random countries europe X 31 | #random countries americas X 32 | #random countries africa east india X 33 | #random countries asia pacific X 34 | #random regions australia X 35 | #random regions canada X 36 | #random regions germany X 37 | #random regions india X 38 | #random regions united states X 39 | 40 | instructions = initialize_VPN(area_input=['random countries europe 8']) 41 | 42 | for i in range(3): 43 | rotate_VPN(instructions) #refer to the instructions variable here 44 | print('\nDo whatever you want here (e.g.scraping). Pausing for 10 seconds...\n') 45 | time.sleep(10) 46 | 47 | # [4] instead of saving the instructions as a variable, you could save your settings in your work directory. Just set the save parameter to 1 48 | 49 | initialize_VPN(save=1) 50 | 51 | for i in range(3): 52 | rotate_VPN() #Call the rotate_VPN without any parameter. It will look for a settings file in your work directory 53 | print('\nDo whatever you want here (e.g.scraping). Pausing for 10 seconds...\n') 54 | time.sleep(10) 55 | 56 | # [5] If you'd like to use an already saved settings file in your work directory (for example: a colleague/friend has sent you his/her settings file), 57 | # use the stored settings parameter 58 | 59 | initialize_VPN(save=1,area_input = ['random countries 20']) #save settings file to work directory 60 | print('Imagine you close your python environment and run your script on a later date. Just load your saved settings by running the following line of code:\n') 61 | time.sleep(7) 62 | initialize_VPN(stored_settings=1) #the function will look for a settingsfile in your work directory, launch NordVPN, disconnect if necessary and validate the stored settings file. 63 | 64 | for i in range(3): 65 | rotate_VPN() 66 | print('\nDo whatever you want here (e.g.scraping). Pausing for 10 seconds...\n') 67 | time.sleep(10) 68 | 69 | 70 | # [6] save settings file to work directory and perform a 'complete rotation' 71 | 72 | # --> a complete rotation will fetch a list of the currently 4000+ active available servers of NordVPN. 73 | # The rotation will rotate between all the available servers completely by random. 74 | # The difference with picking particular regions is that NordVPN will NOT pick the 'most appropriate' (fastest) server within a particular region when rotating. 75 | # Instead, complete rotation will pick a specific server at random, which mens you're unlikely to revisit the same server twice in a row. 76 | # Because of this, the 'complete rotation' option is ideal for webscraping purposes 77 | 78 | initialize_VPN(save=1,area_input=['complete rotation']) 79 | 80 | for i in range(3): 81 | rotate_VPN() 82 | print('\nDo whatever you want here (e.g.scraping). Pausing for 10 seconds...\n') 83 | time.sleep(10) 84 | 85 | # [7] You can be as creative as you like. For example, the following code will perform an infinite loop of picking a random server every hour 86 | 87 | instructions = initialize_VPN(area_input=['complete rotation']) 88 | 89 | while True: 90 | rotate_VPN(instructions) 91 | time.sleep(3600) 92 | 93 | # [8] To implement the google and youtube captcha-check, use the google_check parameter 94 | 95 | instructions = initialize_VPN(area_input=['random regions united states 8']) 96 | 97 | for i in range(3): 98 | rotate_VPN(google_check = 1) 99 | print('\nDo whatever you want here (e.g.scraping). Pausing for 10 seconds...\n') 100 | time.sleep(10) 101 | 102 | ############## 103 | ## LINUX ##### 104 | ############## 105 | 106 | # [1] Perform a complete rotation and skip the settings menu for complete automation 107 | # the 'skip settings' parameter is only available for Linux users (since setting additional settings such as whitelisting ports is only available on Linux) 108 | 109 | instr = initialize_VPN(area_input=['complete rotation'],skip_settings=1) 110 | 111 | for i in range(3): 112 | rotate_VPN(instr) 113 | print('\nDo whatever you want here (e.g. scraping). Pausing for 10 seconds...\n') 114 | time.sleep(10) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### New version: 0.3.0 2 | ***(11/06/2022)*** 3 | 4 | 5 | Updates for version 0.3.0: 6 | * **IP check - regex fix**: website used for IP check has changed; old regex pattern is unable to capture new IP. 7 | * **Spelling error**: 'Salk Late City' connection option has been changed to 'Salt Lake City'. 8 | 9 | Updates for version 0.2.9: 10 | * **Fix in nordvpn account check**: only relevant if you'd like to login through NordVPN switcher 11 | 12 | Updates for version 0.2.8: 13 | * **Fixed ip check bug** : script was unable to detect current ip due to an SSL cert. error. on ident.me. To remedy this, the list of websites used for the ip check has been updated. This should fix most of the connection error issues. 14 | * **Changes in login procedure in newer NordVPN app versions (for Linux users only)**: Login command has been altered for newer NordVPN app versions. 15 | 16 | Updates for version 0.2.7: 17 | * **Fixed quick connect bug**: the script got stuck in an infinite loop if the quick-connect option was chosen using the area_input parameter. 18 | 19 | Updates for version 0.2.6: 20 | * **Fixed ip leakage issue**: to avoid ip leakage (e.g. while scraping), the script saves your original ip when using the initialize_VPN() function in the instructions dict/file. After rotation and thus when using the rotate_VPN() function, it checks whether your new ip is different from not only the previous ip, _but also_ your original ip. 21 | 22 | Updates for version 0.2.5: 23 | * **Added a 'complete rotation' functionality**: allows you to rotate between the 4000+ available servers at random. This is different from connecting to a specific region (e.g. country, state), since NordVPN automatically opts for the 'best' server in that particular area. This means you're often connecting to the same small subset of fast servers. When the 'complete rotation' parameter is set to 1, server rotation is truly random. This is a neat function for webscraping purposes. 24 | 25 | * **Added a 'skip settings' functionality (for Linux users only)**: Linux users are asked whether they'd like to execute additional settings (such as whitelisting ports) whenever they run the initialize_VPN() function. When the skip_settings parameter is set to 1, nordvpn-switcher will assume the user does not wish to execute additional settings. When the user combines this with the area_input parameter, it is possible to run NordVPN switcher right from the get-go without any required user-input on Linux (see demo.py for example code). 26 | 27 | * **The script uses the fake_useragent package** for improved header-input 28 | 29 | * **Added an additional pause to slow the script down on Windows.** Some users - especially if they run the NordVPN app on slow machines - are unable to rotate between servers because the app takes a while to start up. 30 | 31 | * **Added more example code** in the demo.py file (see files on Github) 32 | 33 | 34 | 35 | To all of those who've sent me feedback and/or reported bugs: thank you! 36 | 37 | ### 38 | 39 | # NordVPN-switcher 40 | Rotate between different NordVPN servers with ease. Works both on Linux and Windows without any required changes to your code. 41 | 42 | `pip install nordvpn-switcher` and you're all set! 43 | 44 | Created by Kristof Boghe 45 | 46 | # But...why? 47 | 48 | I realize there are multiple NordVPN-related packages available, but they only work for Linux and/or are not exactly user-friendly. 49 | 50 | **NordVPN-switcher is:** 51 | 52 | **1. Able to run both on Windows and Linux** 53 | 54 | * You don't need to perform any changes to your script. NordVPN-switcher automatically detects your OS and executes the appropriate code automatically. 55 | This means you're able to share your code with your colleagues without having to worry about the OS they use. 56 | 57 | **2. User-friendly** 58 | 59 | * NordVPN-switcher includes a step-by-step menu that takes you through the entire setup. You don't need to construct some chaotic .txt files; you don't even need to know how to run a terminal/cmd command at all! 60 | * Before attempting any VPN connection, it performs a system-checkup and checks whether the NordVPN app is installed, running and whether you are logged in. 61 | * If you're not logged in and you're on Linux, you can log in through the Python terminal with ease 62 | * If you're on Linux, it's possible to run whatever additional setting through the NordVPN app (such as setting the killswitch value, whitelisting ports, etc.). You can replicate these settings every time you run your script with ease by saving these commands into a JSON-file (simply by setting the `save` parameter to 1). 63 | * On Windows, it checks multiple installation directories for the NordVPN app. When the script is unable to locate the installation folder, the menu will ask you for the folder location. The script is able to save this installation folder so you'll never have to worry about it again. 64 | * It even includes a spelling checker (So any attempt to connect to - let's say - "Flance" won't cause any trouble) 65 | * A dictionary of world regions (e.g. Europe) and local regions (e.g. Cities in the US) is included as well. Especially on windows, taking a random pick within a wider region (e.g. asia pacific) is a real drag. NordVPN-switcher handles these kind of random-pick use-cases with ease. 66 | 67 | **3. Forgiving** 68 | 69 | * We all like to run our script and ignore it for the next couple of days without worrying about random connectivity hiccups. NordVPN-switcher retries and connects to a different server when it is unable to fetch your new ip. 70 | * If requested, it also switches servers when Google and/or Youtube throws a captcha (see further). 71 | 72 | **4. Able to check for captcha's on Google and/or YouTube** 73 | 74 | * Especially on busy servers, captcha checks can disrupt your webscraper (e.g. when scraping Google) or overall browsing experience. If requested (by setting the `google_check` parameter to 1), captcha-checks are performed after each server rotation. If a captcha pops up, the script will automatically try a new server. 75 | 76 | **5. Flexible** 77 | * You can ask NordVPN-switcher to hold your hand or go rogue and feed it your own settings-file in JSON-format. if a collaborator wants to share his or her unique settings, he or she can simply send you its settings-file and that's about it! 78 | 79 | # Install 80 | 81 | 1. Make sure NordVPN is installed. 82 | 83 | * On Linux, run: 84 | ``` 85 | wget -qnc https://repo.nordvpn.com/deb/nordvpn/debian/pool/main/nordvpn-release_1.0.0_all.deb 86 | sudo dpkg -i /pathToFile/nordvpn-release_1.0.0_all.deb #replace pathToFile to location download folder 87 | sudo apt update 88 | sudo apt install nordvpn 89 | ``` 90 | (From the NordVPN FAQ) 91 | 92 | * On Windows 93 | 94 | Download the app here --> https://bit.ly/3ig2lU5 95 | 96 | 2. Install the package 97 | 98 | * Execute in terminal: 99 | ``` 100 | pip install nordvpn-switcher 101 | ``` 102 | 103 | OR, for the ones who don't use pip for some reason: 104 | * Download/clone this repository 105 | * Run `pip install -r requirements.txt` to install dependencies 106 | 107 | 3. Import functions`from nordvpn_switcher import initialize_VPN,rotate_VPN,terminate_VPN 108 | 109 | 4. Rotate between servers, for example: 110 | 111 | ``` 112 | import time 113 | 114 | initialize_VPN(save=1,area_input=['complete rotation']) 115 | 116 | for i in range(3): 117 | rotate_VPN() 118 | print('\nDo whatever you want here (e.g.scraping). Pausing for 10 seconds...\n') 119 | time.sleep(10) 120 | ``` 121 | will perform a truly random rotation between all available NordVPN servers. 122 | 123 | That's it! 124 | 125 | # The building blocks 126 | 127 | * In essence, you'll just use the following three functions: 128 | 129 | **1. Setting up your NordVPN settings** 130 | - save: if you want to save these settings for later 131 | - stored_settings: if you want to execute particular settings already saved in your project folder 132 | - area_input: if you want to feed a list of connection options (not necessary). Useful when you want to automate the formulation of a server list (see option 5 in the 'some features and options' section). If you want to rotate truly at random between the 4000+ available NordVPN servers, just set this parameter to `['complete rotation']`. If you'd like to rotate between 10 random European countries, set this parameter to `['random countries europe 10']` etc. See the demo.py file for more examples. 133 | - skip_settings: only relevant for Linux users, since they are able to execute additional settings. Set this parameter to 1 if you'd like to skip the settings-input. If Linux users combine the this with an area_input, they simply skip entire the step-by-step menu initiated by the initalize_VPN() function. 134 | 135 | `initialize_VPN(stored_settings=0,save=0,area_input=None,skip_settings=None)` 136 | 137 | **2. Rotating between servers.** 138 | - instructions: the instructions saved from the initialize_VPN function. If none is provided, the script looks for a nordvpn_settings.txt file in your project folder (which you can create by setting the `save` parameter in the first function to 1). 139 | - google_check: if you want to perform a google and Youtube captcha-check 140 | 141 | `rotate_VPN(instructions=None,google_check = 0)` 142 | 143 | **3. Disconnecting from the VPN service** 144 | - Execute this function at the end of your script (not (!) while you're hopping from server to server in a loop) 145 | 146 | `terminate_VPN(instructions=None)` 147 | 148 | # How to use 149 | 150 | ***--> Please check out the demo.py file on GitHub (https://github.com/kboghe/NordVPN-switcher/) for more examples <--*** 151 | 152 | **Option 1: save settings in environment** 153 | The easiest and most user-friendly (although least automated) way of using NordVPN switcher is by saving the instructions into a new variable and feeding it to the rotate_VPN() function. 154 | 155 | ``` 156 | from nordvpn_switcher import initialize_VPN,rotate_VPN,terminate_VPN 157 | 158 | settings = initialize_VPN() 159 | rotate_VPN(settings) 160 | rotate_VPN(settings,google_check=1) 161 | terminate_VPN(settings) 162 | ``` 163 | ![resulting output option 1](https://static.wixstatic.com/media/707176_04d56aed046e4c1abe960f98a39d6fba~mv2.gif) 164 | 165 | 166 | In practice, you'll usually execute the rotate_VPN() function within some kind of loop. 167 | 168 | ``` 169 | settings = initialize_VPN() #initialize VPN and save settings variable 170 | for i in range(3): (e.g. you'd like to loop over 10.000 urls) 171 | rotate_VPN(settings) 172 | *perform some other code, e.g. scraping* 173 | rotate_VPN(settings,google_check=1) #with google and youtube captcha check 174 | 175 | terminate_VPN(settings) 176 | ``` 177 | if you want to rotate between servers in an infinite loop, you can use the while true statement: 178 | 179 | ``` 180 | while True: 181 | rotate_VPN(settings) 182 | time.sleep(3600) #e.g. rotate servers every hour 183 | ``` 184 | 185 | Thanks to the area_input parameter and the 'complete rotation' functionality, you don't have to provide any input at all. NordVPN will simply hop from server to server in a truly random fashion. 186 | 187 | ``` 188 | initialize_VPN(save=1,area_input=['complete rotation']) 189 | 190 | for i in range(3): 191 | rotate_VPN() 192 | *perform some other code, e.g. scraping* 193 | 194 | terminate_VPN() 195 | ``` 196 | 197 | **Option 2: save settings and execute on each run** 198 | 199 | If you want to make sure that certain NordVPN setting commands are executed (e.g. killswitch, whitelisting ports, etc.) on each run, save the instructions into your project folder once by setting the `save` parameter to 1 and execute the `initialize_VPN` and `rotate_VPN` function every time you run the script. NordVPN-switcher will alert you what kind of additional settings are pulled from the settings-file. 200 | 201 | ``` 202 | #do this once 203 | initialize_VPN(save=1) 204 | ``` 205 | 206 | If `save=1`, the script will write a .txt file in JSON format to your project folder. It contains all the necessary information needed to execute the `rotate_VPN` function. Again, when the instructions parameter is missing in `rotate_VPN`, it will automatically look for the settings file in your project folder. 207 | 208 | --On Windows, the contents of the nordvpn_settings.txt file look something like this (random example): 209 | 210 | `{'opsys': 'Windows', 'command': ['nordvpn', '-c', '-g'], 'settings': ['belgium', 'netherlands', 'germany', 'spain', 'france'], 'original_ip': '82.169.108.182', 'cwd_path': 'C:/Program Files/NordVPN'} 211 | 212 | -- On Linux, the file looks slightly different (different random example): 213 | 214 | `{'opsys': 'Linux','original_ip': '82.169.108.182','command': ['nordvpn', 'c'], 'settings': ['United_States', 'Canada', 'Brazil', 'Argentina', 'Mexico', 'Chile', 'Costa_Rica', 'Australia'], 'additional_settings': [['nordvpn', 'set', 'killswitch', 'disable'], ['nordvpn', 'whitelist', 'add', 'port', '23']],'credentials':[['name@gmail.com'],['coolpassword]]}` 215 | 216 | Thanks to the saved .txt file, you never need to go through the menu options of `initialize_VPN()` again. So, some time later, you simply perform: 217 | 218 | ``` 219 | initialize_VPN(stored_settings=1) 220 | rotate_VPN() 221 | #do stuff 222 | terminate_VPN() 223 | ``` 224 | ![resulting output option 2](https://static.wixstatic.com/media/707176_006e832eae5f48c7bb3fabdefd18b61c~mv2.gif) 225 | 226 | This option is only relevant for Linux users who wish to execute additional settings such as enabling killswitch etc. Executing these additional settings is not an available option on Windows machines. 227 | 228 | **Option 3: save settings and just use rotate on each run** 229 | 230 | This is similar to option 2, but without executing the `initialize_VPN` function on each run. 231 | This is relevant for all Windows machines or Linux machines who do not wish to execute additional settings. 232 | 233 | ``` 234 | #do this once 235 | initialize_VPN(save=1) 236 | 237 | #open project on a later date and just use the following two lines of code: 238 | rotate_VPN() 239 | #do stuff 240 | terminate_VPN() 241 | ``` 242 | ![resulting output option 3](https://static.wixstatic.com/media/707176_996821904d1a4f8cac71d943dca58d83~mv2.gif) 243 | 244 | **Option 4: manual option** 245 | 246 | Create or obtain your own settings_nordvpn.txt file, place it in your project folder and use the rotate function# 247 | For example, share particular settings with colleagues/friends who work on the same project by sending them your .txt settings file. Place it in your project folder and just use the `rotate_VPN` function. 248 | 249 | ``` 250 | rotate_VPN() 251 | #do stuff 252 | terminate_VPN() 253 | ``` 254 | 255 | **> See the demo.py file for a summary** 256 | 257 | # Some features and options 258 | 259 | **1. Rotate between all available NordVPN servers at random.** 260 | This differs from any other connection method since NordVPN automatically picks the most 'appropriate' (as in fastest) server in a particular region. This means that connecting to, let's say, the Netherlands means you'll often end up with the same server time and time again. The 'complete rotation' functionality allows you to completely randomize server selection. 261 | 262 | ``` 263 | initialize_VPN(area_input=['complete rotation']) 264 | rotate_VPN() 265 | #do stuff 266 | terminate_VPN() 267 | ``` 268 | 269 | **2. Provide additional settings and save these for later use, if so desired (only on Linux)** 270 | 271 | ![additional settings gif](https://static.wixstatic.com/media/707176_f419292769834df5bb1e3e4883353ef6~mv2.gif) 272 | 273 | **3. Login to NordVPN if logged out (only on Linux)** 274 | 275 | ![login nordvpn](https://static.wixstatic.com/media/707176_594ed7b6b8044dbfbf260d969a5b50a6~mv2.gif) 276 | 277 | **4. Take a random sample from a larger region** 278 | 279 | ![random sample gif](https://static.wixstatic.com/media/707176_9dcaa96814c44a99a33a9732e13fe490~mv2.gif) 280 | 281 | **5.Spellchecker** 282 | 283 | ![spellchecker gif](https://static.wixstatic.com/media/707176_2e40511ea0b0493f8f95889613b22f1a~mv2.gif) 284 | 285 | **6. Provide a list of connection options, which will be automatically incorporated into the nordvpn_settings.txt file** 286 | 287 | ``` 288 | range_servers = range(800,837) 289 | server_list = ["nl"+str(number) for number in range_servers] 290 | instructions = initialize_VPN(area_input = server_list) 291 | rotate_VPN(instructions) 292 | ``` 293 | 294 | ![server list gif](https://static.wixstatic.com/media/707176_8ea7e75a73024faca7a739a8e732cc7a~mv2.gif) 295 | 296 | 297 | **6. NordVPN app starts automatically (if closed) on Windows. Connection process can also be monitored by checking the NordVPN app** 298 | 299 | ![windows app gif](https://static.wixstatic.com/media/707176_e79bcbe217e44d519a245abae28c360b~mv2.gif) 300 | 301 | # Windows vs Linux 302 | 303 | * The script runs slower on Windows. This can be explained by the fact that the script communicates directly with NordVPN.exe, which means it inherits the poor speed performance of the Windows app by definition. Compare the speed of the previous gifs (all executed on a Linux machine) with the following gif, executed on Windows: 304 | 305 | ![windows slowness gif](https://static.wixstatic.com/media/707176_9fc88bae04ad4bf7ab98c1f20ac5bd85~mv2.gif) 306 | 307 | * Linux users have a couple of additional options at their disposal, namely: 308 | 309 | 1.Being able to log in through the Python interface. Windows users need to make sure they're already logged into the NordVPN app. The Windows app remembers your log in by default though, so this shouldn't cause too much trouble. So even when the app is closed, NordVPN-switcher should work. 310 | 311 | 2.Executing additional settings (e.g. killswitch etc.) 312 | 313 | * Settings files can't be directly shared between Windows and Linux machines (see option 4 - how to use). Of course, with a little tweaking, separate Windows and Linux settings-files can easily be constructed for your specific project. 314 | 315 | # Possible applications 316 | 317 | * To circumvent ip-blocks from certain websites (e.g. while scraping particular platforms) 318 | 319 | In this case, the VPN switcher basically serves the same function as the often-used proxy lists while scraping the web (e.g. with BeauitfulSoup), but without the common disadvantages associated with the latter. 320 | 321 | * To automate a particular task that benefits from being performed by many ip-addresses 322 | 323 | * For security reasons 324 | 325 | I'm pretty sure there are plenty of other viable applications out there. NordVPN-switcher is extremely easy to implement, no matter the particular problem/project at hand. 326 | 327 | # Questions, problems, nasty bugs to report? 328 | 329 | kboghe@gmail.com 330 | 331 | Have fun! 332 | -------------------------------------------------------------------------------- /nordvpn_switcher/nordvpn_switch.py: -------------------------------------------------------------------------------- 1 | ################# 2 | #import packages# 3 | ################# 4 | #1.system and terminal/cmd 5 | import os 6 | from os import path 7 | import platform 8 | import subprocess 9 | from subprocess import check_output,DEVNULL 10 | #2.utilities (randomisations etc) 11 | import psutil 12 | import random 13 | import re 14 | import time 15 | #3.scraping 16 | import urllib 17 | from bs4 import BeautifulSoup 18 | from random_user_agent.user_agent import UserAgent 19 | from random_user_agent.params import SoftwareName, OperatingSystem 20 | import requests 21 | #4.file formats 22 | import json 23 | #5.package dependencies 24 | import importlib.resources as pkg_resources 25 | from nordvpn_switcher import NordVPN_options 26 | 27 | ################################## 28 | #retrieve useragents for scraping# 29 | ################################## 30 | software_names = [SoftwareName.CHROME.value] 31 | operating_systems = [OperatingSystem.WINDOWS.value, OperatingSystem.LINUX.value] 32 | user_agent_rotator = UserAgent(software_names=software_names, operating_systems=operating_systems, limit=100) 33 | 34 | ################## 35 | #helper functions# 36 | ################## 37 | def additional_settings_linux(additional_settings): 38 | try: 39 | additional_setting_execute = str(check_output(additional_settings)) 40 | except: 41 | additional_setting_execute = "error" 42 | else: 43 | pass 44 | 45 | if "successfully" in additional_setting_execute: 46 | settings_input_message = "\nDone! Anything else?\n" 47 | elif additional_setting_execute == "error": 48 | settings_input_message = "\n\x1b[93mSomething went wrong. Please consult some examples by typing 'help'\x1b[0m\n" 49 | elif "already" in additional_setting_execute: 50 | settings_input_message = "\nThis setting has already been executed! Anything else?\n" 51 | else: 52 | settings_input_message = "\n\x1b[93mNordVPN throws an unexpected message, namely:\n" + additional_setting_execute + "\nTry something different.\x1b[0m\n" 53 | return settings_input_message 54 | 55 | def saved_settings_check(): 56 | print("\33[33mTrying to load saved settings...\33[0m") 57 | try: 58 | instructions = json.load(open("settings_nordvpn.txt")) 59 | except FileNotFoundError: 60 | raise Exception("\n\nSaved settings not found.\n" 61 | "Run initialize_VPN() first and save the settings on your hard drive or store it into a Python variable.") 62 | else: 63 | print("\33[33mSaved settings loaded!\n\33[0m") 64 | return instructions 65 | 66 | def set_headers(user_agent_rotator): 67 | useragent_pick = user_agent_rotator.get_random_user_agent() 68 | headers = {'User-Agent': useragent_pick, 69 | 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 70 | 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 71 | 'Accept-Encoding': 'none', 72 | 'Accept-Language': 'en-US,en;q=0.8', 73 | 'Connection': 'keep-alive'} 74 | return headers 75 | 76 | def get_ip(): 77 | headers = set_headers(user_agent_rotator) 78 | ip_check_websites = ['http://ip4only.me/api/',"https://api64.ipify.org/"] 79 | website_pick = random.choice(ip_check_websites) 80 | request_currentip = urllib.request.Request(url=website_pick, headers=headers) 81 | ip = urllib.request.urlopen(request_currentip).read().decode('utf-8') 82 | if website_pick == 'http://ip4only.me/api/': 83 | ip = re.search("IPv4,(.*?),Remaining", ip).group(1) 84 | return ip 85 | 86 | def get_nordvpn_servers(): 87 | serverlist = BeautifulSoup(requests.get("https://nordvpn.com/api/server").content,"html.parser") 88 | site_json=json.loads(serverlist.text) 89 | 90 | filtered_servers = {key: [] for key in ['windows_names','linux_names']} 91 | for specific_dict in site_json: 92 | try: 93 | if specific_dict['categories'][0]['name'] == 'Standard VPN servers': 94 | filtered_servers['windows_names'].append(specific_dict['name']) 95 | filtered_servers['linux_names'].append(specific_dict['domain'].split('.')[0]) 96 | except IndexError: 97 | pass 98 | return filtered_servers 99 | 100 | ############### 101 | #intialize vpn# 102 | ############### 103 | def initialize_VPN(stored_settings=0,save=0,area_input=None,skip_settings=0): 104 | 105 | ###load stored settings if needed and set input_needed variables to zero if settings are provided### 106 | windows_pause = 3 107 | additional_settings_needed = 1 108 | additional_settings_list = list() 109 | if stored_settings == 1: 110 | instructions = saved_settings_check() 111 | additional_settings_needed = 0 112 | input_needed = 0 113 | elif area_input is not None: 114 | input_needed = 2 115 | windows_pause = 8 116 | else: 117 | input_needed = 1 118 | 119 | ###performing system check### 120 | opsys = platform.system() 121 | 122 | ##windows## 123 | if opsys == "Windows": 124 | print("\33[33mYou're using Windows.\n" 125 | "Performing system check...\n" 126 | "###########################\n\33[0m") 127 | #seek and set windows installation path# 128 | option_1_path = 'C:/Program Files/NordVPN' 129 | option_2_path = 'C:/Program Files (x86)/NordVPN' 130 | custom_path = str() 131 | if path.exists(option_1_path) == True: 132 | cwd_path = option_1_path 133 | elif path.exists(option_2_path) == True: 134 | cwd_path = option_2_path 135 | else: 136 | custom_path = input("\x1b[93mIt looks like you've installed NordVPN in an uncommon folder. Would you mind telling me which folder? (e.g. D:/customfolder/nordvpn)\x1b[0m") 137 | while path.exists(custom_path) == False: 138 | custom_path = input("\x1b[93mI'm sorry, but this folder doesn't exist. Please double-check your input.\x1b[0m") 139 | while os.path.isfile(custom_path+"/NordVPN.exe") == False: 140 | custom_path = input("\x1b[93mI'm sorry, but the NordVPN application is not located in this folder. Please double-check your input.\x1b[0m") 141 | cwd_path = custom_path 142 | print("NordVPN installation check: \33[92m\N{check mark}\33[0m") 143 | 144 | #check if nordvpn service is already running in the background 145 | check_service = "nordvpn-service.exe" in (p.name() for p in psutil.process_iter()) 146 | if check_service is False: 147 | raise Exception("NordVPN service hasn't been initialized, please start this service in [task manager] --> [services] and restart your script") 148 | print("NordVPN service check: \33[92m\N{check mark}\33[0m") 149 | 150 | # start NordVPN app and disconnect from VPN service if necessary# 151 | print("Opening NordVPN app and disconnecting if necessary...") 152 | open_nord_win = subprocess.Popen(["nordvpn", "-d"],shell=True,cwd=cwd_path,stdout=DEVNULL) 153 | while ("NordVPN.exe" in (p.name() for p in psutil.process_iter())) == False: 154 | time.sleep(windows_pause) 155 | open_nord_win.kill() 156 | print("NordVPN app launched: \33[92m\N{check mark}\33[0m") 157 | print("#####################################") 158 | 159 | ##linux## 160 | elif opsys == "Linux": 161 | print("\n\33[33mYou're using Linux.\n" 162 | "Performing system check...\n" 163 | "###########################\n\33[0m") 164 | 165 | #check if nordvpn is installed on linux# 166 | check_nord_linux = check_output(["nordvpn"]) 167 | if len(check_nord_linux) > 0: 168 | print("NordVPN installation check: \33[92m\N{check mark}\33[0m") 169 | else: 170 | raise Exception("NordVPN is not installed on your Linux machine.\n" 171 | "Follow instructions on shorturl.at/ioDQ2 to install the NordVpn app.") 172 | 173 | #check if user is logged in. If not, ask for credentials and log in or use credentials from stored settings if available.# 174 | try: 175 | check_output(["nordvpn", "account"]) 176 | except: 177 | login_needed = 1 178 | while login_needed == 1: 179 | login_message = input("\n\033[34mYou are not logged in. Please provide your credentials in the form of LOGIN/PASSWORD\n\033[0m") 180 | try: 181 | if instructions['credentials'] in locals(): 182 | credentials = stored_settings['credentials'] 183 | else: 184 | credentials = login_message 185 | except: 186 | credentials = login_message 187 | finally: 188 | try: 189 | login = credentials.split("/")[0] 190 | password = credentials.split("/")[1] 191 | except IndexError: 192 | error_login = input("\n\033[34mYou have provided your credentials in the wrong format. Press enter and please try again.\n" 193 | "Your input should look something like this: name@gmail.com/password\033[0m") 194 | else: 195 | login_needed = 0 196 | try: 197 | login_nordvpn = check_output(["nordvpn","login","-username",login,"-password",password]) 198 | except subprocess.CalledProcessError: 199 | raise Exception("\nSorry,something went wrong while trying to log in\n") 200 | if "Welcome" in str(login_nordvpn): 201 | print("\n\n\033[34mLogin successful!\n\033[0m\n") 202 | pass 203 | else: 204 | raise Exception("\nSorry, NordVPN throws an unexpected message, namely:\n"+str(login_nordvpn)) 205 | else: 206 | print("NordVPN login check: \33[92m\N{check mark}\33[0m") 207 | 208 | #disconnect from VPN if necessary 209 | terminate = subprocess.Popen(["nordvpn", "d"],stdout=DEVNULL) 210 | 211 | #provide opportunity to execute additional settings.# 212 | settings_input_message = "\n\033[34mDo you want to execute additional settings?\033[0m" 213 | while additional_settings_needed == 1 and skip_settings == 0: 214 | additional_settings = input(settings_input_message+ 215 | "\n_________________________\n\n" 216 | "Press enter to continue\n" 217 | "Type 'help' for available options\n").strip() 218 | if additional_settings == "help": 219 | options_linux = pkg_resources.open_text(NordVPN_options, 'options_linux.txt').read().split('\n') 220 | for line in options_linux: 221 | print(line) 222 | additional_settings = input("").strip() 223 | 224 | additional_settings = str(additional_settings).split(" ") 225 | if len(additional_settings[0]) > 0: 226 | settings_input_message = additional_settings_linux(additional_settings) 227 | if any(re.findall(r'done|already been executed', settings_input_message,re.IGNORECASE)): 228 | additional_settings_list.append(additional_settings) 229 | else: 230 | additional_settings_needed = 0 231 | 232 | #however, if provided, just skip the additional settings option and execute the stored settings.# 233 | if 'instructions' in locals(): 234 | if len(instructions['additional_settings'][0][0]) > 0: 235 | print("Executing stored additional settings....\n") 236 | for count,instruction in enumerate(instructions['additional_settings']): 237 | print("Executing stored setting #"+str(count+1)+": "+str(instruction)) 238 | additional_settings_linux(instruction) 239 | else: 240 | pass 241 | 242 | else: 243 | raise Exception("I'm sorry, NordVPN switcher only works for Windows and Linux machines.") 244 | 245 | ###provide settings for VPN rotation### 246 | 247 | ##open available options and store these in a dict## 248 | areas_list = pkg_resources.open_text(NordVPN_options, 'countrylist.txt').read().split('\n') 249 | country_dict = {'countries':areas_list[0:60],'europe': areas_list[0:36], 'americas': areas_list[36:44], 250 | 'africa east india': areas_list[49:60],'asia pacific': areas_list[49:60], 251 | 'regions australia': areas_list[60:65],'regions canada': areas_list[65:68], 252 | 'regions germany': areas_list[68:70], 'regions india': areas_list[70:72], 253 | 'regions united states': areas_list[72:87],'special groups':areas_list[87:len(areas_list)]} 254 | 255 | ##provide input if needed## 256 | while input_needed > 0: 257 | if input_needed == 2: 258 | print("\nYou've entered a list of connection options. Checking list...\n") 259 | try: 260 | settings_servers = [area.lower() for area in area_input] 261 | settings_servers = ",".join(settings_servers) 262 | except TypeError: 263 | raise Exception("I expected a list here. Are you sure you've not entered a string or some other object?\n ") 264 | 265 | else: 266 | settings_servers = input("\n\033[34mI want to connect to...\n" 267 | "_________________________\n" 268 | "Type 'help' for available options\n\033[0m").strip().lower() 269 | #define help menu# 270 | if settings_servers.lower().strip() == 'help': 271 | #notation for specific servers differs between Windows and Linux.# 272 | if opsys == "Windows": 273 | notation_specific_server = " (e.g. Netherlands #742,Belgium #166)\n" 274 | else: 275 | notation_specific_server = " (e.g. nl742,be166)\n" 276 | 277 | settings_servers = input("\nOptions:\n" 278 | "##########\n" 279 | "* type 'quick' to choose quickconnect \n" 280 | "* type 'complete rotation' to rotate between all available NordVPN servers\n" 281 | "* Single country or local region (e.g.Germany)\n" 282 | "* Regions within country (e.g. regions united states')\n" 283 | "* World regions (europe/americas/africa east india/asia pacific)\n" 284 | "* Random multiple countries and/or local regions (e.g.France,Netherlands,Chicago)\n" 285 | "* Random n countries (e.g. random countries 10)\n" 286 | "* Random n countries within larger region (e.g. random countries europe 5)\n" 287 | "* Random n regions in country (e.g. random regions United States 6)\n"\ 288 | "* Specialty group name (e.g. Dedicated IP,Double VPN)\n" 289 | "* Specific list of servers"+notation_specific_server).strip().lower() 290 | 291 | #set base command according to running os# 292 | if opsys == "Windows": 293 | nordvpn_command = ["nordvpn", "-c"] 294 | if opsys == "Linux": 295 | nordvpn_command = ["nordvpn", "c"] 296 | 297 | #create sample of regions from input.# 298 | #1. if quick connect# 299 | if settings_servers == "quick": 300 | if input_needed == 1: 301 | quickconnect_check = input("\nYou are choosing for the quick connect option. Are you sure? (y/n)\n") 302 | if 'y' in quickconnect_check: 303 | sample_countries = [""] 304 | input_needed = 0 305 | pass 306 | if input_needed == 2: 307 | sample_countries = [""] 308 | input_needed = 0 309 | else: 310 | print("\nYou are choosing for the quick connect option.\n") 311 | #2. if completely random rotation 312 | elif settings_servers == 'complete rotation': 313 | print("\nFetching list of all current NordVPN servers...\n") 314 | for i in range(120): 315 | try: 316 | filtered_servers = get_nordvpn_servers() 317 | if opsys == "Windows": 318 | nordvpn_command.append("-n") 319 | sample_countries = filtered_servers['windows_names'] 320 | else: 321 | sample_countries = filtered_servers['linux_names'] 322 | except: 323 | time.sleep(0.5) 324 | continue 325 | else: 326 | input_needed = 0 327 | break 328 | else: 329 | raise Exception("\nI'm unable to fetch the current NordVPN serverlist. Check your internet connection.\n") 330 | #3. if provided specific servers. Notation differs for Windows and Linux machines, so two options are checked (first is Windows, second is Linux# 331 | elif "#" in settings_servers or re.compile(r'^[a-zA-Z]+[0-9]+').search(settings_servers.split(',')[0]) is not None: 332 | if opsys == "Windows": 333 | nordvpn_command.append("-n") 334 | sample_countries = [area.strip() for area in settings_servers.split(',')] 335 | input_needed = 0 336 | else: 337 | #3. If connecting to some specific group of servers# 338 | if opsys == "Windows": 339 | nordvpn_command.append("-g") 340 | #3.1 if asked for random sample, pull a sample.# 341 | if "random" in settings_servers: 342 | #determine sample size# 343 | samplesize = int(re.sub("[^0-9]", "", settings_servers).strip()) 344 | #3.1.1 if asked for random regions within country (e.g. random regions from United States,Australia,...)# 345 | if "regions" in settings_servers: 346 | try: 347 | sample_countries = country_dict[re.sub("random", "", settings_servers).rstrip('0123456789.- ').lower().strip()] 348 | input_needed = 0 349 | except: 350 | input("\n\nThere are no specific regions available in this country, please try again.\nPress enter to continue.\n") 351 | if input_needed == 2: 352 | input_needed = 1 353 | continue 354 | if re.compile(r'[^0-9]').search(settings_servers.strip()): 355 | sample_countries = random.sample(sample_countries, samplesize) 356 | #3.1.2 if asked for random countries within larger region# 357 | elif any(re.findall(r'europe|americas|africa east india|asia pacific', settings_servers)): 358 | larger_region = country_dict[re.sub("random|countries", "", settings_servers).rstrip('0123456789.- ').lower().strip()] 359 | sample_countries = random.sample(larger_region,samplesize) 360 | input_needed = 0 361 | #3.1.3 if asked for random countries globally# 362 | else: 363 | if re.compile(r'[^0-9]').search(settings_servers.strip()): 364 | sample_countries = random.sample(country_dict['countries'], samplesize) 365 | input_needed = 0 366 | else: 367 | sample_countries = country_dict['countries'] 368 | input_needed = 0 369 | #4. If asked for specific region (e.g. europe)# 370 | elif settings_servers in country_dict.keys(): 371 | sample_countries = country_dict[settings_servers] 372 | input_needed = 0 373 | #5. If asked for specific countries or regions (e.g.netherlands)# 374 | else: 375 | #check for empty input first.# 376 | if settings_servers == "": 377 | input("\n\nYou must provide some kind of input.\nPress enter to continue and then type 'help' to view the available options.\n") 378 | if input_needed == 2: 379 | input_needed = 1 380 | continue 381 | else: 382 | sample_countries = [area.strip() for area in settings_servers.split(',')] #take into account possible superfluous spaces# 383 | approved_regions = 0 384 | for region in sample_countries: 385 | if region in [area.lower() for area in areas_list]: 386 | approved_regions = approved_regions + 1 387 | pass 388 | else: 389 | input("\n\nThe region/group " + region + " is not available. Please check for spelling errors.\nPress enter to continue.\n") 390 | if input_needed == 2: 391 | input_needed = 1 392 | continue 393 | if approved_regions == len(sample_countries): 394 | input_needed = 0 395 | 396 | ##fetch current ip to prevent ip leakage when rotating VPN## 397 | for i in range(59): 398 | try: 399 | og_ip = get_ip() 400 | except ConnectionAbortedError: 401 | time.sleep(1) 402 | continue 403 | else: 404 | break 405 | else: 406 | raise Exception("Can't fetch current ip, even after retrying... Check your internet connection.") 407 | 408 | ##if user does not use preloaded settings## 409 | if "instructions" not in locals(): 410 | #1.add underscore if spaces are present on Linux os# 411 | for number,element in enumerate(sample_countries): 412 | if element.count(" ") > 0 and opsys == "Linux": 413 | sample_countries[number] = re.sub(" ","_",element) 414 | else: 415 | pass 416 | #2.create instructions dict object# 417 | instructions = {'opsys':opsys,'command':nordvpn_command,'settings':sample_countries,'original_ip':og_ip} 418 | if opsys == "Windows": 419 | instructions['cwd_path'] = cwd_path 420 | if opsys == "Linux": 421 | instructions['additional_settings'] = additional_settings_list 422 | if 'credentials' in locals(): 423 | instructions['credentials'] = credentials 424 | #3.save the settings if requested into .txt file in project folder# 425 | if save == 1: 426 | print("\nSaving settings in project folder...\n") 427 | try: 428 | os.remove("settings_nordvpn.txt") 429 | except FileNotFoundError: 430 | pass 431 | instructions_write = json.dumps(instructions) 432 | f = open("settings_nordvpn.txt", "w") 433 | f.write(instructions_write) 434 | f.close() 435 | 436 | print("\nDone!\n") 437 | return instructions 438 | 439 | ########################## 440 | #rotate and terminate VPN# 441 | ########################## 442 | #1.rotate 443 | def rotate_VPN(instructions=None,google_check = 0): 444 | if instructions is None: 445 | instructions = saved_settings_check() 446 | 447 | opsys = instructions['opsys'] 448 | command = instructions['command'] 449 | settings = instructions['settings'] 450 | og_ip = instructions['original_ip'] 451 | 452 | if opsys == "Windows": 453 | cwd_path = instructions['cwd_path'] 454 | 455 | for i in range(2): 456 | try: 457 | current_ip = new_ip = get_ip() 458 | except urllib.error.URLError: 459 | print("Can't fetch current ip. Retrying...") 460 | time.sleep(10) 461 | continue 462 | else: 463 | print("\nYour current ip-address is:", current_ip) 464 | break 465 | else: 466 | raise Exception("Can't fetch current ip, even after retrying... Check your internet connection.") 467 | 468 | for i in range(4): 469 | if len(settings) > 1: 470 | settings_pick = list([random.choice(settings)]) 471 | else: 472 | settings_pick = settings 473 | 474 | input = command + settings_pick 475 | 476 | if settings[0] == "": 477 | print("\nConnecting you to the best possible server (quick connect option)...") 478 | else: 479 | print("\n\33[34mConnecting you to", settings_pick[0], "...\n\33[0m") 480 | 481 | try: 482 | if opsys == "Windows": 483 | new_connection = subprocess.Popen(input, shell=True, cwd=cwd_path) 484 | new_connection.wait(50) 485 | else: 486 | new_connection = check_output(input) 487 | print("Found a server! You're now on "+re.search('(?<=You are connected to )(.*)(?=\()', str(new_connection))[0].strip()) 488 | except: 489 | print("\n An unknown error occurred while connecting to a different server! Retrying with a different server...\n") 490 | time.sleep(15) 491 | continue 492 | 493 | for i in range(12): 494 | try: 495 | new_ip = get_ip() 496 | except: 497 | time.sleep(5) 498 | continue 499 | else: 500 | if new_ip in [current_ip,og_ip]: 501 | time.sleep(5) 502 | continue 503 | else: 504 | break 505 | else: 506 | pass 507 | 508 | if new_ip in [current_ip,og_ip]: 509 | print("ip-address hasn't changed. Retrying...\n") 510 | time.sleep(10) 511 | continue 512 | else: 513 | print("your new ip-address is:", new_ip) 514 | 515 | if google_check == 1: 516 | print("\n\33[33mPerforming captcha-check on Google search and Youtube...\n" 517 | "---------------------------\33[0m") 518 | try: 519 | google_search_check = BeautifulSoup( 520 | requests.get("https://www.google.be/search?q=why+is+python+so+hard").content,"html.parser") 521 | youtube_video_check = BeautifulSoup( 522 | requests.get("https://www.youtube.com/watch?v=dQw4w9WgXcQ").content,"html.parser") 523 | 524 | google_captcha = google_search_check.find('div',id="recaptcha") 525 | youtube_captcha = youtube_video_check.find('div', id = "recaptcha") 526 | 527 | if None not in (google_captcha,youtube_captcha): 528 | print("Google throws a captcha. I'll pick a different server...") 529 | time.sleep(5) 530 | continue 531 | except: 532 | print("Can't load Google page. I'll pick a different server...") 533 | time.sleep(5) 534 | continue 535 | else: 536 | print("Google and YouTube don't throw any Captcha's: \33[92m\N{check mark}\33[0m") 537 | break 538 | else: 539 | break 540 | 541 | else: 542 | raise Exception("Unable to connect to a new server. Please check your internet connection.\n") 543 | 544 | print("\nDone! Enjoy your new server.\n") 545 | #2.terminate 546 | def terminate_VPN(instructions=None): 547 | if instructions is None: 548 | instructions = saved_settings_check() 549 | 550 | opsys = instructions['opsys'] 551 | if opsys == "Windows": 552 | cwd_path = instructions['cwd_path'] 553 | 554 | print("\nDisconnecting...") 555 | if opsys == "Windows": 556 | terminate = subprocess.Popen(["nordvpn", "-d"],shell=True,cwd=cwd_path,stdout=DEVNULL) 557 | else: 558 | terminate = subprocess.Popen(["nordvpn", "d"],stdout=DEVNULL) 559 | 560 | terminate.wait() 561 | print("Done!") -------------------------------------------------------------------------------- /nordvpn_switch.py: -------------------------------------------------------------------------------- 1 | ################# 2 | #import packages# 3 | ################# 4 | #1.system and terminal/cmd 5 | import os 6 | from os import path 7 | import platform 8 | import subprocess 9 | from subprocess import check_output,DEVNULL 10 | #2.utilities (randomisations etc) 11 | import psutil 12 | import random 13 | import re 14 | import time 15 | #3.scraping 16 | import urllib 17 | from bs4 import BeautifulSoup 18 | from random_user_agent.user_agent import UserAgent 19 | from random_user_agent.params import SoftwareName, OperatingSystem 20 | import requests 21 | #4.file formats 22 | import json 23 | #5.package dependencies 24 | import importlib.resources as pkg_resources 25 | from nordvpn_switcher import NordVPN_options 26 | 27 | ################################## 28 | #retrieve useragents for scraping# 29 | ################################## 30 | software_names = [SoftwareName.CHROME.value] 31 | operating_systems = [OperatingSystem.WINDOWS.value, OperatingSystem.LINUX.value] 32 | user_agent_rotator = UserAgent(software_names=software_names, operating_systems=operating_systems, limit=100) 33 | 34 | ################## 35 | #helper functions# 36 | ################## 37 | def additional_settings_linux(additional_settings): 38 | try: 39 | additional_setting_execute = str(check_output(additional_settings)) 40 | except: 41 | additional_setting_execute = "error" 42 | else: 43 | pass 44 | 45 | if "successfully" in additional_setting_execute: 46 | settings_input_message = "\nDone! Anything else?\n" 47 | elif additional_setting_execute == "error": 48 | settings_input_message = "\n\x1b[93mSomething went wrong. Please consult some examples by typing 'help'\x1b[0m\n" 49 | elif "already" in additional_setting_execute: 50 | settings_input_message = "\nThis setting has already been executed! Anything else?\n" 51 | else: 52 | settings_input_message = "\n\x1b[93mNordVPN throws an unexpected message, namely:\n" + additional_setting_execute + "\nTry something different.\x1b[0m\n" 53 | return settings_input_message 54 | 55 | def saved_settings_check(): 56 | print("\33[33mTrying to load saved settings...\33[0m") 57 | try: 58 | instructions = json.load(open("settings_nordvpn.txt")) 59 | except FileNotFoundError: 60 | raise Exception("\n\nSaved settings not found.\n" 61 | "Run initialize_VPN() first and save the settings on your hard drive or store it into a Python variable.") 62 | else: 63 | print("\33[33mSaved settings loaded!\n\33[0m") 64 | return instructions 65 | 66 | def set_headers(user_agent_rotator): 67 | useragent_pick = user_agent_rotator.get_random_user_agent() 68 | headers = {'User-Agent': useragent_pick, 69 | 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 70 | 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 71 | 'Accept-Encoding': 'none', 72 | 'Accept-Language': 'en-US,en;q=0.8', 73 | 'Connection': 'keep-alive'} 74 | return headers 75 | 76 | def get_ip(): 77 | headers = set_headers(user_agent_rotator) 78 | ip_check_websites = ['http://ip4only.me/api/',"https://api64.ipify.org/"] 79 | website_pick = random.choice(ip_check_websites) 80 | request_currentip = urllib.request.Request(url=website_pick, headers=headers) 81 | ip = urllib.request.urlopen(request_currentip).read().decode('utf-8') 82 | if website_pick == 'http://ip4only.me/api/': 83 | ip = re.search("IPv4,(.*?),", ip).group(1) 84 | return ip 85 | 86 | def get_nordvpn_servers(): 87 | serverlist = BeautifulSoup(requests.get("https://nordvpn.com/api/server").content,"html.parser") 88 | site_json=json.loads(serverlist.text) 89 | 90 | filtered_servers = {key: [] for key in ['windows_names','linux_names']} 91 | for specific_dict in site_json: 92 | try: 93 | if specific_dict['categories'][0]['name'] == 'Standard VPN servers': 94 | filtered_servers['windows_names'].append(specific_dict['name']) 95 | filtered_servers['linux_names'].append(specific_dict['domain'].split('.')[0]) 96 | except IndexError: 97 | pass 98 | return filtered_servers 99 | 100 | ############### 101 | #intialize vpn# 102 | ############### 103 | def initialize_VPN(stored_settings=0,save=0,area_input=None,skip_settings=0): 104 | 105 | ###load stored settings if needed and set input_needed variables to zero if settings are provided### 106 | windows_pause = 3 107 | additional_settings_needed = 1 108 | additional_settings_list = list() 109 | if stored_settings == 1: 110 | instructions = saved_settings_check() 111 | additional_settings_needed = 0 112 | input_needed = 0 113 | elif area_input is not None: 114 | input_needed = 2 115 | windows_pause = 8 116 | else: 117 | input_needed = 1 118 | 119 | ###performing system check### 120 | opsys = platform.system() 121 | 122 | ##windows## 123 | if opsys == "Windows": 124 | print("\33[33mYou're using Windows.\n" 125 | "Performing system check...\n" 126 | "###########################\n\33[0m") 127 | #seek and set windows installation path# 128 | option_1_path = 'C:/Program Files/NordVPN' 129 | option_2_path = 'C:/Program Files (x86)/NordVPN' 130 | custom_path = str() 131 | if path.exists(option_1_path) == True: 132 | cwd_path = option_1_path 133 | elif path.exists(option_2_path) == True: 134 | cwd_path = option_2_path 135 | else: 136 | custom_path = input("\x1b[93mIt looks like you've installed NordVPN in an uncommon folder. Would you mind telling me which folder? (e.g. D:/customfolder/nordvpn)\x1b[0m") 137 | while path.exists(custom_path) == False: 138 | custom_path = input("\x1b[93mI'm sorry, but this folder doesn't exist. Please double-check your input.\x1b[0m") 139 | while os.path.isfile(custom_path+"/NordVPN.exe") == False: 140 | custom_path = input("\x1b[93mI'm sorry, but the NordVPN application is not located in this folder. Please double-check your input.\x1b[0m") 141 | cwd_path = custom_path 142 | print("NordVPN installation check: \33[92m\N{check mark}\33[0m") 143 | 144 | #check if nordvpn service is already running in the background 145 | check_service = "nordvpn-service.exe" in (p.name() for p in psutil.process_iter()) 146 | if check_service is False: 147 | raise Exception("NordVPN service hasn't been initialized, please start this service in [task manager] --> [services] and restart your script") 148 | print("NordVPN service check: \33[92m\N{check mark}\33[0m") 149 | 150 | # start NordVPN app and disconnect from VPN service if necessary# 151 | print("Opening NordVPN app and disconnecting if necessary...") 152 | open_nord_win = subprocess.Popen(["nordvpn", "-d"],shell=True,cwd=cwd_path,stdout=DEVNULL) 153 | while ("NordVPN.exe" in (p.name() for p in psutil.process_iter())) == False: 154 | time.sleep(windows_pause) 155 | open_nord_win.kill() 156 | print("NordVPN app launched: \33[92m\N{check mark}\33[0m") 157 | print("#####################################") 158 | 159 | ##linux## 160 | elif opsys == "Linux": 161 | print("\n\33[33mYou're using Linux.\n" 162 | "Performing system check...\n" 163 | "###########################\n\33[0m") 164 | 165 | #check if nordvpn is installed on linux# 166 | check_nord_linux = check_output(["nordvpn"]) 167 | if len(check_nord_linux) > 0: 168 | print("NordVPN installation check: \33[92m\N{check mark}\33[0m") 169 | else: 170 | raise Exception("NordVPN is not installed on your Linux machine.\n" 171 | "Follow instructions on shorturl.at/ioDQ2 to install the NordVpn app.") 172 | 173 | #check if user is logged in. If not, ask for credentials and log in or use credentials from stored settings if available.# 174 | try: 175 | check_output(["nordvpn", "account"]) 176 | except: 177 | login_needed = 1 178 | while login_needed == 1: 179 | login_message = input("\n\033[34mYou are not logged in. Please provide your credentials in the form of LOGIN/PASSWORD\n\033[0m") 180 | try: 181 | if instructions['credentials'] in locals(): 182 | credentials = stored_settings['credentials'] 183 | else: 184 | credentials = login_message 185 | except: 186 | credentials = login_message 187 | finally: 188 | try: 189 | login = credentials.split("/")[0] 190 | password = credentials.split("/")[1] 191 | except IndexError: 192 | error_login = input("\n\033[34mYou have provided your credentials in the wrong format. Press enter and please try again.\n" 193 | "Your input should look something like this: name@gmail.com/password\033[0m") 194 | else: 195 | login_needed = 0 196 | try: 197 | login_nordvpn = check_output(["nordvpn","login","-username",login,"-password",password]) 198 | except subprocess.CalledProcessError: 199 | raise Exception("\nSorry,something went wrong while trying to log in\n") 200 | if "Welcome" in str(login_nordvpn): 201 | print("\n\n\033[34mLogin successful!\n\033[0m\n") 202 | pass 203 | else: 204 | raise Exception("\nSorry, NordVPN throws an unexpected message, namely:\n"+str(login_nordvpn)) 205 | else: 206 | print("NordVPN login check: \33[92m\N{check mark}\33[0m") 207 | 208 | #disconnect from VPN if necessary 209 | terminate = subprocess.Popen(["nordvpn", "d"],stdout=DEVNULL) 210 | 211 | #provide opportunity to execute additional settings.# 212 | settings_input_message = "\n\033[34mDo you want to execute additional settings?\033[0m" 213 | while additional_settings_needed == 1 and skip_settings == 0: 214 | additional_settings = input(settings_input_message+ 215 | "\n_________________________\n\n" 216 | "Press enter to continue\n" 217 | "Type 'help' for available options\n").strip() 218 | if additional_settings == "help": 219 | options_linux = pkg_resources.open_text(NordVPN_options, 'options_linux.txt').read().split('\n') 220 | for line in options_linux: 221 | print(line) 222 | additional_settings = input("").strip() 223 | 224 | additional_settings = str(additional_settings).split(" ") 225 | if len(additional_settings[0]) > 0: 226 | settings_input_message = additional_settings_linux(additional_settings) 227 | if any(re.findall(r'done|already been executed', settings_input_message,re.IGNORECASE)): 228 | additional_settings_list.append(additional_settings) 229 | else: 230 | additional_settings_needed = 0 231 | 232 | #however, if provided, just skip the additional settings option and execute the stored settings.# 233 | if 'instructions' in locals(): 234 | if len(instructions['additional_settings'][0][0]) > 0: 235 | print("Executing stored additional settings....\n") 236 | for count,instruction in enumerate(instructions['additional_settings']): 237 | print("Executing stored setting #"+str(count+1)+": "+str(instruction)) 238 | additional_settings_linux(instruction) 239 | else: 240 | pass 241 | 242 | else: 243 | raise Exception("I'm sorry, NordVPN switcher only works for Windows and Linux machines.") 244 | 245 | ###provide settings for VPN rotation### 246 | 247 | ##open available options and store these in a dict## 248 | areas_list = pkg_resources.open_text(NordVPN_options, 'countrylist.txt').read().split('\n') 249 | country_dict = {'countries':areas_list[0:60],'europe': areas_list[0:36], 'americas': areas_list[36:44], 250 | 'africa east india': areas_list[49:60],'asia pacific': areas_list[49:60], 251 | 'regions australia': areas_list[60:65],'regions canada': areas_list[65:68], 252 | 'regions germany': areas_list[68:70], 'regions india': areas_list[70:72], 253 | 'regions united states': areas_list[72:87],'special groups':areas_list[87:len(areas_list)]} 254 | 255 | ##provide input if needed## 256 | while input_needed > 0: 257 | if input_needed == 2: 258 | print("\nYou've entered a list of connection options. Checking list...\n") 259 | try: 260 | settings_servers = [area.lower() for area in area_input] 261 | settings_servers = ",".join(settings_servers) 262 | except TypeError: 263 | raise Exception("I expected a list here. Are you sure you've not entered a string or some other object?\n ") 264 | 265 | else: 266 | settings_servers = input("\n\033[34mI want to connect to...\n" 267 | "_________________________\n" 268 | "Type 'help' for available options\n\033[0m").strip().lower() 269 | #define help menu# 270 | if settings_servers.lower().strip() == 'help': 271 | #notation for specific servers differs between Windows and Linux.# 272 | if opsys == "Windows": 273 | notation_specific_server = " (e.g. Netherlands #742,Belgium #166)\n" 274 | else: 275 | notation_specific_server = " (e.g. nl742,be166)\n" 276 | 277 | settings_servers = input("\nOptions:\n" 278 | "##########\n" 279 | "* type 'quick' to choose quickconnect \n" 280 | "* type 'complete rotation' to rotate between all available NordVPN servers\n" 281 | "* Single country or local region (e.g.Germany)\n" 282 | "* Regions within country (e.g. regions united states')\n" 283 | "* World regions (europe/americas/africa east india/asia pacific)\n" 284 | "* Random multiple countries and/or local regions (e.g.France,Netherlands,Chicago)\n" 285 | "* Random n countries (e.g. random countries 10)\n" 286 | "* Random n countries within larger region (e.g. random countries europe 5)\n" 287 | "* Random n regions in country (e.g. random regions United States 6)\n"\ 288 | "* Specialty group name (e.g. Dedicated IP,Double VPN)\n" 289 | "* Specific list of servers"+notation_specific_server).strip().lower() 290 | 291 | #set base command according to running os# 292 | if opsys == "Windows": 293 | nordvpn_command = ["nordvpn", "-c"] 294 | if opsys == "Linux": 295 | nordvpn_command = ["nordvpn", "c"] 296 | 297 | #create sample of regions from input.# 298 | #1. if quick connect# 299 | if settings_servers == "quick": 300 | if input_needed == 1: 301 | quickconnect_check = input("\nYou are choosing for the quick connect option. Are you sure? (y/n)\n") 302 | if 'y' in quickconnect_check: 303 | sample_countries = [""] 304 | input_needed = 0 305 | pass 306 | if input_needed == 2: 307 | sample_countries = [""] 308 | input_needed = 0 309 | else: 310 | print("\nYou are choosing for the quick connect option.\n") 311 | #2. if completely random rotation 312 | elif settings_servers == 'complete rotation': 313 | print("\nFetching list of all current NordVPN servers...\n") 314 | for i in range(120): 315 | try: 316 | filtered_servers = get_nordvpn_servers() 317 | if opsys == "Windows": 318 | nordvpn_command.append("-n") 319 | sample_countries = filtered_servers['windows_names'] 320 | else: 321 | sample_countries = filtered_servers['linux_names'] 322 | except: 323 | time.sleep(0.5) 324 | continue 325 | else: 326 | input_needed = 0 327 | break 328 | else: 329 | raise Exception("\nI'm unable to fetch the current NordVPN serverlist. Check your internet connection.\n") 330 | #3. if provided specific servers. Notation differs for Windows and Linux machines, so two options are checked (first is Windows, second is Linux# 331 | elif "#" in settings_servers or re.compile(r'^[a-zA-Z]+[0-9]+').search(settings_servers.split(',')[0]) is not None: 332 | if opsys == "Windows": 333 | nordvpn_command.append("-n") 334 | sample_countries = [area.strip() for area in settings_servers.split(',')] 335 | input_needed = 0 336 | else: 337 | #3. If connecting to some specific group of servers# 338 | if opsys == "Windows": 339 | nordvpn_command.append("-g") 340 | #3.1 if asked for random sample, pull a sample.# 341 | if "random" in settings_servers: 342 | #determine sample size# 343 | samplesize = int(re.sub("[^0-9]", "", settings_servers).strip()) 344 | #3.1.1 if asked for random regions within country (e.g. random regions from United States,Australia,...)# 345 | if "regions" in settings_servers: 346 | try: 347 | sample_countries = country_dict[re.sub("random", "", settings_servers).rstrip('0123456789.- ').lower().strip()] 348 | input_needed = 0 349 | except: 350 | input("\n\nThere are no specific regions available in this country, please try again.\nPress enter to continue.\n") 351 | if input_needed == 2: 352 | input_needed = 1 353 | continue 354 | if re.compile(r'[^0-9]').search(settings_servers.strip()): 355 | sample_countries = random.sample(sample_countries, samplesize) 356 | #3.1.2 if asked for random countries within larger region# 357 | elif any(re.findall(r'europe|americas|africa east india|asia pacific', settings_servers)): 358 | larger_region = country_dict[re.sub("random|countries", "", settings_servers).rstrip('0123456789.- ').lower().strip()] 359 | sample_countries = random.sample(larger_region,samplesize) 360 | input_needed = 0 361 | #3.1.3 if asked for random countries globally# 362 | else: 363 | if re.compile(r'[^0-9]').search(settings_servers.strip()): 364 | sample_countries = random.sample(country_dict['countries'], samplesize) 365 | input_needed = 0 366 | else: 367 | sample_countries = country_dict['countries'] 368 | input_needed = 0 369 | #4. If asked for specific region (e.g. europe)# 370 | elif settings_servers in country_dict.keys(): 371 | sample_countries = country_dict[settings_servers] 372 | input_needed = 0 373 | #5. If asked for specific countries or regions (e.g.netherlands)# 374 | else: 375 | #check for empty input first.# 376 | if settings_servers == "": 377 | input("\n\nYou must provide some kind of input.\nPress enter to continue and then type 'help' to view the available options.\n") 378 | if input_needed == 2: 379 | input_needed = 1 380 | continue 381 | else: 382 | sample_countries = [area.strip() for area in settings_servers.split(',')] #take into account possible superfluous spaces# 383 | approved_regions = 0 384 | for region in sample_countries: 385 | if region in [area.lower() for area in areas_list]: 386 | approved_regions = approved_regions + 1 387 | pass 388 | else: 389 | input("\n\nThe region/group " + region + " is not available. Please check for spelling errors.\nPress enter to continue.\n") 390 | if input_needed == 2: 391 | input_needed = 1 392 | continue 393 | if approved_regions == len(sample_countries): 394 | input_needed = 0 395 | 396 | ##fetch current ip to prevent ip leakage when rotating VPN## 397 | for i in range(59): 398 | try: 399 | og_ip = get_ip() 400 | except ConnectionAbortedError: 401 | time.sleep(1) 402 | continue 403 | else: 404 | break 405 | else: 406 | raise Exception("Can't fetch current ip, even after retrying... Check your internet connection.") 407 | 408 | ##if user does not use preloaded settings## 409 | if "instructions" not in locals(): 410 | #1.add underscore if spaces are present on Linux os# 411 | for number,element in enumerate(sample_countries): 412 | if element.count(" ") > 0 and opsys == "Linux": 413 | sample_countries[number] = re.sub(" ","_",element) 414 | else: 415 | pass 416 | #2.create instructions dict object# 417 | instructions = {'opsys':opsys,'command':nordvpn_command,'settings':sample_countries,'original_ip':og_ip} 418 | if opsys == "Windows": 419 | instructions['cwd_path'] = cwd_path 420 | if opsys == "Linux": 421 | instructions['additional_settings'] = additional_settings_list 422 | if 'credentials' in locals(): 423 | instructions['credentials'] = credentials 424 | #3.save the settings if requested into .txt file in project folder# 425 | if save == 1: 426 | print("\nSaving settings in project folder...\n") 427 | try: 428 | os.remove("settings_nordvpn.txt") 429 | except FileNotFoundError: 430 | pass 431 | instructions_write = json.dumps(instructions) 432 | f = open("settings_nordvpn.txt", "w") 433 | f.write(instructions_write) 434 | f.close() 435 | 436 | print("\nDone!\n") 437 | return instructions 438 | 439 | ########################## 440 | #rotate and terminate VPN# 441 | ########################## 442 | #1.rotate 443 | def rotate_VPN(instructions=None,google_check = 0): 444 | if instructions is None: 445 | instructions = saved_settings_check() 446 | 447 | opsys = instructions['opsys'] 448 | command = instructions['command'] 449 | settings = instructions['settings'] 450 | og_ip = instructions['original_ip'] 451 | 452 | if opsys == "Windows": 453 | cwd_path = instructions['cwd_path'] 454 | 455 | for i in range(2): 456 | try: 457 | current_ip = new_ip = get_ip() 458 | except urllib.error.URLError: 459 | print("Can't fetch current ip. Retrying...") 460 | time.sleep(10) 461 | continue 462 | else: 463 | print("\nYour current ip-address is:", current_ip) 464 | break 465 | else: 466 | raise Exception("Can't fetch current ip, even after retrying... Check your internet connection.") 467 | 468 | for i in range(4): 469 | if len(settings) > 1: 470 | settings_pick = list([random.choice(settings)]) 471 | else: 472 | settings_pick = settings 473 | 474 | input = command + settings_pick 475 | 476 | if settings[0] == "": 477 | print("\nConnecting you to the best possible server (quick connect option)...") 478 | else: 479 | print("\n\33[34mConnecting you to", settings_pick[0], "...\n\33[0m") 480 | 481 | try: 482 | if opsys == "Windows": 483 | new_connection = subprocess.Popen(input, shell=True, cwd=cwd_path) 484 | new_connection.wait(50) 485 | else: 486 | new_connection = check_output(input) 487 | print("Found a server! You're now on "+re.search('(?<=You are connected to )(.*)(?=\()', str(new_connection))[0].strip()) 488 | except: 489 | print("\n An unknown error occurred while connecting to a different server! Retrying with a different server...\n") 490 | time.sleep(15) 491 | continue 492 | 493 | for i in range(12): 494 | try: 495 | new_ip = get_ip() 496 | except: 497 | time.sleep(5) 498 | continue 499 | else: 500 | if new_ip in [current_ip,og_ip]: 501 | time.sleep(5) 502 | continue 503 | else: 504 | break 505 | else: 506 | pass 507 | 508 | if new_ip in [current_ip,og_ip]: 509 | print("ip-address hasn't changed. Retrying...\n") 510 | time.sleep(10) 511 | continue 512 | else: 513 | print("your new ip-address is:", new_ip) 514 | 515 | if google_check == 1: 516 | print("\n\33[33mPerforming captcha-check on Google search and Youtube...\n" 517 | "---------------------------\33[0m") 518 | try: 519 | google_search_check = BeautifulSoup( 520 | requests.get("https://www.google.be/search?q=why+is+python+so+hard").content,"html.parser") 521 | youtube_video_check = BeautifulSoup( 522 | requests.get("https://www.youtube.com/watch?v=dQw4w9WgXcQ").content,"html.parser") 523 | 524 | google_captcha = google_search_check.find('div',id="recaptcha") 525 | youtube_captcha = youtube_video_check.find('div', id = "recaptcha") 526 | 527 | if None not in (google_captcha,youtube_captcha): 528 | print("Google throws a captcha. I'll pick a different server...") 529 | time.sleep(5) 530 | continue 531 | except: 532 | print("Can't load Google page. I'll pick a different server...") 533 | time.sleep(5) 534 | continue 535 | else: 536 | print("Google and YouTube don't throw any Captcha's: \33[92m\N{check mark}\33[0m") 537 | break 538 | else: 539 | break 540 | 541 | else: 542 | raise Exception("Unable to connect to a new server. Please check your internet connection.\n") 543 | 544 | print("\nDone! Enjoy your new server.\n") 545 | #2.terminate 546 | def terminate_VPN(instructions=None): 547 | if instructions is None: 548 | instructions = saved_settings_check() 549 | 550 | opsys = instructions['opsys'] 551 | if opsys == "Windows": 552 | cwd_path = instructions['cwd_path'] 553 | 554 | print("\nDisconnecting...") 555 | if opsys == "Windows": 556 | terminate = subprocess.Popen(["nordvpn", "-d"],shell=True,cwd=cwd_path,stdout=DEVNULL) 557 | else: 558 | terminate = subprocess.Popen(["nordvpn", "d"],stdout=DEVNULL) 559 | 560 | terminate.wait() 561 | print("Done!") -------------------------------------------------------------------------------- /nordvpn_switcher/nordvpn_switcher/nordvpn_switch.py: -------------------------------------------------------------------------------- 1 | ################# 2 | #import packages# 3 | ################# 4 | #1.system and terminal/cmd 5 | import os 6 | from os import path 7 | import platform 8 | import subprocess 9 | from subprocess import check_output,DEVNULL 10 | #2.utilities (randomisations etc) 11 | import psutil 12 | import random 13 | import re 14 | import time 15 | #3.scraping 16 | import urllib 17 | from bs4 import BeautifulSoup 18 | from random_user_agent.user_agent import UserAgent 19 | from random_user_agent.params import SoftwareName, OperatingSystem 20 | import requests 21 | #4.file formats 22 | import json 23 | #5.package dependencies 24 | import importlib.resources as pkg_resources 25 | from nordvpn_switcher import NordVPN_options 26 | 27 | ################################## 28 | #retrieve useragents for scraping# 29 | ################################## 30 | software_names = [SoftwareName.CHROME.value] 31 | operating_systems = [OperatingSystem.WINDOWS.value, OperatingSystem.LINUX.value] 32 | user_agent_rotator = UserAgent(software_names=software_names, operating_systems=operating_systems, limit=100) 33 | 34 | ################## 35 | #helper functions# 36 | ################## 37 | def additional_settings_linux(additional_settings): 38 | try: 39 | additional_setting_execute = str(check_output(additional_settings)) 40 | except: 41 | additional_setting_execute = "error" 42 | else: 43 | pass 44 | 45 | if "successfully" in additional_setting_execute: 46 | settings_input_message = "\nDone! Anything else?\n" 47 | elif additional_setting_execute == "error": 48 | settings_input_message = "\n\x1b[93mSomething went wrong. Please consult some examples by typing 'help'\x1b[0m\n" 49 | elif "already" in additional_setting_execute: 50 | settings_input_message = "\nThis setting has already been executed! Anything else?\n" 51 | else: 52 | settings_input_message = "\n\x1b[93mNordVPN throws an unexpected message, namely:\n" + additional_setting_execute + "\nTry something different.\x1b[0m\n" 53 | return settings_input_message 54 | 55 | def saved_settings_check(): 56 | print("\33[33mTrying to load saved settings...\33[0m") 57 | try: 58 | instructions = json.load(open("settings_nordvpn.txt")) 59 | except FileNotFoundError: 60 | raise Exception("\n\nSaved settings not found.\n" 61 | "Run initialize_VPN() first and save the settings on your hard drive or store it into a Python variable.") 62 | else: 63 | print("\33[33mSaved settings loaded!\n\33[0m") 64 | return instructions 65 | 66 | def set_headers(user_agent_rotator): 67 | useragent_pick = user_agent_rotator.get_random_user_agent() 68 | headers = {'User-Agent': useragent_pick, 69 | 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 70 | 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 71 | 'Accept-Encoding': 'none', 72 | 'Accept-Language': 'en-US,en;q=0.8', 73 | 'Connection': 'keep-alive'} 74 | return headers 75 | 76 | def get_ip(): 77 | headers = set_headers(user_agent_rotator) 78 | ip_check_websites = ['http://ip4only.me/api/',"https://api64.ipify.org/"] 79 | website_pick = random.choice(ip_check_websites) 80 | request_currentip = urllib.request.Request(url=website_pick, headers=headers) 81 | ip = urllib.request.urlopen(request_currentip).read().decode('utf-8') 82 | if website_pick == 'http://ip4only.me/api/': 83 | ip = re.search("IPv4,(.*?),", ip).group(1) 84 | return ip 85 | 86 | def get_nordvpn_servers(): 87 | serverlist = BeautifulSoup(requests.get("https://nordvpn.com/api/server").content,"html.parser") 88 | site_json=json.loads(serverlist.text) 89 | 90 | filtered_servers = {key: [] for key in ['windows_names','linux_names']} 91 | for specific_dict in site_json: 92 | try: 93 | if specific_dict['categories'][0]['name'] == 'Standard VPN servers': 94 | filtered_servers['windows_names'].append(specific_dict['name']) 95 | filtered_servers['linux_names'].append(specific_dict['domain'].split('.')[0]) 96 | except IndexError: 97 | pass 98 | return filtered_servers 99 | 100 | ############### 101 | #intialize vpn# 102 | ############### 103 | def initialize_VPN(stored_settings=0,save=0,area_input=None,skip_settings=0): 104 | 105 | ###load stored settings if needed and set input_needed variables to zero if settings are provided### 106 | windows_pause = 3 107 | additional_settings_needed = 1 108 | additional_settings_list = list() 109 | if stored_settings == 1: 110 | instructions = saved_settings_check() 111 | additional_settings_needed = 0 112 | input_needed = 0 113 | elif area_input is not None: 114 | input_needed = 2 115 | windows_pause = 8 116 | else: 117 | input_needed = 1 118 | 119 | ###performing system check### 120 | opsys = platform.system() 121 | 122 | ##windows## 123 | if opsys == "Windows": 124 | print("\33[33mYou're using Windows.\n" 125 | "Performing system check...\n" 126 | "###########################\n\33[0m") 127 | #seek and set windows installation path# 128 | option_1_path = 'C:/Program Files/NordVPN' 129 | option_2_path = 'C:/Program Files (x86)/NordVPN' 130 | custom_path = str() 131 | if path.exists(option_1_path) == True: 132 | cwd_path = option_1_path 133 | elif path.exists(option_2_path) == True: 134 | cwd_path = option_2_path 135 | else: 136 | custom_path = input("\x1b[93mIt looks like you've installed NordVPN in an uncommon folder. Would you mind telling me which folder? (e.g. D:/customfolder/nordvpn)\x1b[0m") 137 | while path.exists(custom_path) == False: 138 | custom_path = input("\x1b[93mI'm sorry, but this folder doesn't exist. Please double-check your input.\x1b[0m") 139 | while os.path.isfile(custom_path+"/NordVPN.exe") == False: 140 | custom_path = input("\x1b[93mI'm sorry, but the NordVPN application is not located in this folder. Please double-check your input.\x1b[0m") 141 | cwd_path = custom_path 142 | print("NordVPN installation check: \33[92m\N{check mark}\33[0m") 143 | 144 | #check if nordvpn service is already running in the background 145 | check_service = "nordvpn-service.exe" in (p.name() for p in psutil.process_iter()) 146 | if check_service is False: 147 | raise Exception("NordVPN service hasn't been initialized, please start this service in [task manager] --> [services] and restart your script") 148 | print("NordVPN service check: \33[92m\N{check mark}\33[0m") 149 | 150 | # start NordVPN app and disconnect from VPN service if necessary# 151 | print("Opening NordVPN app and disconnecting if necessary...") 152 | open_nord_win = subprocess.Popen(["nordvpn", "-d"],shell=True,cwd=cwd_path,stdout=DEVNULL) 153 | while ("NordVPN.exe" in (p.name() for p in psutil.process_iter())) == False: 154 | time.sleep(windows_pause) 155 | open_nord_win.kill() 156 | print("NordVPN app launched: \33[92m\N{check mark}\33[0m") 157 | print("#####################################") 158 | 159 | ##linux## 160 | elif opsys == "Linux": 161 | print("\n\33[33mYou're using Linux.\n" 162 | "Performing system check...\n" 163 | "###########################\n\33[0m") 164 | 165 | #check if nordvpn is installed on linux# 166 | check_nord_linux = check_output(["nordvpn"]) 167 | if len(check_nord_linux) > 0: 168 | print("NordVPN installation check: \33[92m\N{check mark}\33[0m") 169 | else: 170 | raise Exception("NordVPN is not installed on your Linux machine.\n" 171 | "Follow instructions on shorturl.at/ioDQ2 to install the NordVpn app.") 172 | 173 | #check if user is logged in. If not, ask for credentials and log in or use credentials from stored settings if available.# 174 | try: 175 | check_output(["nordvpn", "account"]) 176 | except: 177 | login_needed = 1 178 | while login_needed == 1: 179 | login_message = input("\n\033[34mYou are not logged in. Please provide your credentials in the form of LOGIN/PASSWORD\n\033[0m") 180 | try: 181 | if instructions['credentials'] in locals(): 182 | credentials = stored_settings['credentials'] 183 | else: 184 | credentials = login_message 185 | except: 186 | credentials = login_message 187 | finally: 188 | try: 189 | login = credentials.split("/")[0] 190 | password = credentials.split("/")[1] 191 | except IndexError: 192 | error_login = input("\n\033[34mYou have provided your credentials in the wrong format. Press enter and please try again.\n" 193 | "Your input should look something like this: name@gmail.com/password\033[0m") 194 | else: 195 | login_needed = 0 196 | try: 197 | login_nordvpn = check_output(["nordvpn","login","-username",login,"-password",password]) 198 | except subprocess.CalledProcessError: 199 | raise Exception("\nSorry,something went wrong while trying to log in\n") 200 | if "Welcome" in str(login_nordvpn): 201 | print("\n\n\033[34mLogin successful!\n\033[0m\n") 202 | pass 203 | else: 204 | raise Exception("\nSorry, NordVPN throws an unexpected message, namely:\n"+str(login_nordvpn)) 205 | else: 206 | print("NordVPN login check: \33[92m\N{check mark}\33[0m") 207 | 208 | #disconnect from VPN if necessary 209 | terminate = subprocess.Popen(["nordvpn", "d"],stdout=DEVNULL) 210 | 211 | #provide opportunity to execute additional settings.# 212 | settings_input_message = "\n\033[34mDo you want to execute additional settings?\033[0m" 213 | while additional_settings_needed == 1 and skip_settings == 0: 214 | additional_settings = input(settings_input_message+ 215 | "\n_________________________\n\n" 216 | "Press enter to continue\n" 217 | "Type 'help' for available options\n").strip() 218 | if additional_settings == "help": 219 | options_linux = pkg_resources.open_text(NordVPN_options, 'options_linux.txt').read().split('\n') 220 | for line in options_linux: 221 | print(line) 222 | additional_settings = input("").strip() 223 | 224 | additional_settings = str(additional_settings).split(" ") 225 | if len(additional_settings[0]) > 0: 226 | settings_input_message = additional_settings_linux(additional_settings) 227 | if any(re.findall(r'done|already been executed', settings_input_message,re.IGNORECASE)): 228 | additional_settings_list.append(additional_settings) 229 | else: 230 | additional_settings_needed = 0 231 | 232 | #however, if provided, just skip the additional settings option and execute the stored settings.# 233 | if 'instructions' in locals(): 234 | if len(instructions['additional_settings'][0][0]) > 0: 235 | print("Executing stored additional settings....\n") 236 | for count,instruction in enumerate(instructions['additional_settings']): 237 | print("Executing stored setting #"+str(count+1)+": "+str(instruction)) 238 | additional_settings_linux(instruction) 239 | else: 240 | pass 241 | 242 | else: 243 | raise Exception("I'm sorry, NordVPN switcher only works for Windows and Linux machines.") 244 | 245 | ###provide settings for VPN rotation### 246 | 247 | ##open available options and store these in a dict## 248 | areas_list = pkg_resources.open_text(NordVPN_options, 'countrylist.txt').read().split('\n') 249 | country_dict = {'countries':areas_list[0:60],'europe': areas_list[0:36], 'americas': areas_list[36:44], 250 | 'africa east india': areas_list[49:60],'asia pacific': areas_list[49:60], 251 | 'regions australia': areas_list[60:65],'regions canada': areas_list[65:68], 252 | 'regions germany': areas_list[68:70], 'regions india': areas_list[70:72], 253 | 'regions united states': areas_list[72:87],'special groups':areas_list[87:len(areas_list)]} 254 | 255 | ##provide input if needed## 256 | while input_needed > 0: 257 | if input_needed == 2: 258 | print("\nYou've entered a list of connection options. Checking list...\n") 259 | try: 260 | settings_servers = [area.lower() for area in area_input] 261 | settings_servers = ",".join(settings_servers) 262 | except TypeError: 263 | raise Exception("I expected a list here. Are you sure you've not entered a string or some other object?\n ") 264 | 265 | else: 266 | settings_servers = input("\n\033[34mI want to connect to...\n" 267 | "_________________________\n" 268 | "Type 'help' for available options\n\033[0m").strip().lower() 269 | #define help menu# 270 | if settings_servers.lower().strip() == 'help': 271 | #notation for specific servers differs between Windows and Linux.# 272 | if opsys == "Windows": 273 | notation_specific_server = " (e.g. Netherlands #742,Belgium #166)\n" 274 | else: 275 | notation_specific_server = " (e.g. nl742,be166)\n" 276 | 277 | settings_servers = input("\nOptions:\n" 278 | "##########\n" 279 | "* type 'quick' to choose quickconnect \n" 280 | "* type 'complete rotation' to rotate between all available NordVPN servers\n" 281 | "* Single country or local region (e.g.Germany)\n" 282 | "* Regions within country (e.g. regions united states')\n" 283 | "* World regions (europe/americas/africa east india/asia pacific)\n" 284 | "* Random multiple countries and/or local regions (e.g.France,Netherlands,Chicago)\n" 285 | "* Random n countries (e.g. random countries 10)\n" 286 | "* Random n countries within larger region (e.g. random countries europe 5)\n" 287 | "* Random n regions in country (e.g. random regions United States 6)\n"\ 288 | "* Specialty group name (e.g. Dedicated IP,Double VPN)\n" 289 | "* Specific list of servers"+notation_specific_server).strip().lower() 290 | 291 | #set base command according to running os# 292 | if opsys == "Windows": 293 | nordvpn_command = ["nordvpn", "-c"] 294 | if opsys == "Linux": 295 | nordvpn_command = ["nordvpn", "c"] 296 | 297 | #create sample of regions from input.# 298 | #1. if quick connect# 299 | if settings_servers == "quick": 300 | if input_needed == 1: 301 | quickconnect_check = input("\nYou are choosing for the quick connect option. Are you sure? (y/n)\n") 302 | if 'y' in quickconnect_check: 303 | sample_countries = [""] 304 | input_needed = 0 305 | pass 306 | if input_needed == 2: 307 | sample_countries = [""] 308 | input_needed = 0 309 | else: 310 | print("\nYou are choosing for the quick connect option.\n") 311 | #2. if completely random rotation 312 | elif settings_servers == 'complete rotation': 313 | print("\nFetching list of all current NordVPN servers...\n") 314 | for i in range(120): 315 | try: 316 | filtered_servers = get_nordvpn_servers() 317 | if opsys == "Windows": 318 | nordvpn_command.append("-n") 319 | sample_countries = filtered_servers['windows_names'] 320 | else: 321 | sample_countries = filtered_servers['linux_names'] 322 | except: 323 | time.sleep(0.5) 324 | continue 325 | else: 326 | input_needed = 0 327 | break 328 | else: 329 | raise Exception("\nI'm unable to fetch the current NordVPN serverlist. Check your internet connection.\n") 330 | #3. if provided specific servers. Notation differs for Windows and Linux machines, so two options are checked (first is Windows, second is Linux# 331 | elif "#" in settings_servers or re.compile(r'^[a-zA-Z]+[0-9]+').search(settings_servers.split(',')[0]) is not None: 332 | if opsys == "Windows": 333 | nordvpn_command.append("-n") 334 | sample_countries = [area.strip() for area in settings_servers.split(',')] 335 | input_needed = 0 336 | else: 337 | #3. If connecting to some specific group of servers# 338 | if opsys == "Windows": 339 | nordvpn_command.append("-g") 340 | #3.1 if asked for random sample, pull a sample.# 341 | if "random" in settings_servers: 342 | #determine sample size# 343 | samplesize = int(re.sub("[^0-9]", "", settings_servers).strip()) 344 | #3.1.1 if asked for random regions within country (e.g. random regions from United States,Australia,...)# 345 | if "regions" in settings_servers: 346 | try: 347 | sample_countries = country_dict[re.sub("random", "", settings_servers).rstrip('0123456789.- ').lower().strip()] 348 | input_needed = 0 349 | except: 350 | input("\n\nThere are no specific regions available in this country, please try again.\nPress enter to continue.\n") 351 | if input_needed == 2: 352 | input_needed = 1 353 | continue 354 | if re.compile(r'[^0-9]').search(settings_servers.strip()): 355 | sample_countries = random.sample(sample_countries, samplesize) 356 | #3.1.2 if asked for random countries within larger region# 357 | elif any(re.findall(r'europe|americas|africa east india|asia pacific', settings_servers)): 358 | larger_region = country_dict[re.sub("random|countries", "", settings_servers).rstrip('0123456789.- ').lower().strip()] 359 | sample_countries = random.sample(larger_region,samplesize) 360 | input_needed = 0 361 | #3.1.3 if asked for random countries globally# 362 | else: 363 | if re.compile(r'[^0-9]').search(settings_servers.strip()): 364 | sample_countries = random.sample(country_dict['countries'], samplesize) 365 | input_needed = 0 366 | else: 367 | sample_countries = country_dict['countries'] 368 | input_needed = 0 369 | #4. If asked for specific region (e.g. europe)# 370 | elif settings_servers in country_dict.keys(): 371 | sample_countries = country_dict[settings_servers] 372 | input_needed = 0 373 | #5. If asked for specific countries or regions (e.g.netherlands)# 374 | else: 375 | #check for empty input first.# 376 | if settings_servers == "": 377 | input("\n\nYou must provide some kind of input.\nPress enter to continue and then type 'help' to view the available options.\n") 378 | if input_needed == 2: 379 | input_needed = 1 380 | continue 381 | else: 382 | sample_countries = [area.strip() for area in settings_servers.split(',')] #take into account possible superfluous spaces# 383 | approved_regions = 0 384 | for region in sample_countries: 385 | if region in [area.lower() for area in areas_list]: 386 | approved_regions = approved_regions + 1 387 | pass 388 | else: 389 | input("\n\nThe region/group " + region + " is not available. Please check for spelling errors.\nPress enter to continue.\n") 390 | if input_needed == 2: 391 | input_needed = 1 392 | continue 393 | if approved_regions == len(sample_countries): 394 | input_needed = 0 395 | 396 | ##fetch current ip to prevent ip leakage when rotating VPN## 397 | for i in range(59): 398 | try: 399 | og_ip = get_ip() 400 | except ConnectionAbortedError: 401 | time.sleep(1) 402 | continue 403 | else: 404 | break 405 | else: 406 | raise Exception("Can't fetch current ip, even after retrying... Check your internet connection.") 407 | 408 | ##if user does not use preloaded settings## 409 | if "instructions" not in locals(): 410 | #1.add underscore if spaces are present on Linux os# 411 | for number,element in enumerate(sample_countries): 412 | if element.count(" ") > 0 and opsys == "Linux": 413 | sample_countries[number] = re.sub(" ","_",element) 414 | else: 415 | pass 416 | #2.create instructions dict object# 417 | instructions = {'opsys':opsys,'command':nordvpn_command,'settings':sample_countries,'original_ip':og_ip} 418 | if opsys == "Windows": 419 | instructions['cwd_path'] = cwd_path 420 | if opsys == "Linux": 421 | instructions['additional_settings'] = additional_settings_list 422 | if 'credentials' in locals(): 423 | instructions['credentials'] = credentials 424 | #3.save the settings if requested into .txt file in project folder# 425 | if save == 1: 426 | print("\nSaving settings in project folder...\n") 427 | try: 428 | os.remove("settings_nordvpn.txt") 429 | except FileNotFoundError: 430 | pass 431 | instructions_write = json.dumps(instructions) 432 | f = open("settings_nordvpn.txt", "w") 433 | f.write(instructions_write) 434 | f.close() 435 | 436 | print("\nDone!\n") 437 | return instructions 438 | 439 | ########################## 440 | #rotate and terminate VPN# 441 | ########################## 442 | #1.rotate 443 | def rotate_VPN(instructions=None,google_check = 0): 444 | if instructions is None: 445 | instructions = saved_settings_check() 446 | 447 | opsys = instructions['opsys'] 448 | command = instructions['command'] 449 | settings = instructions['settings'] 450 | og_ip = instructions['original_ip'] 451 | 452 | if opsys == "Windows": 453 | cwd_path = instructions['cwd_path'] 454 | 455 | for i in range(2): 456 | try: 457 | current_ip = new_ip = get_ip() 458 | except urllib.error.URLError: 459 | print("Can't fetch current ip. Retrying...") 460 | time.sleep(10) 461 | continue 462 | else: 463 | print("\nYour current ip-address is:", current_ip) 464 | break 465 | else: 466 | raise Exception("Can't fetch current ip, even after retrying... Check your internet connection.") 467 | 468 | for i in range(4): 469 | if len(settings) > 1: 470 | settings_pick = list([random.choice(settings)]) 471 | else: 472 | settings_pick = settings 473 | 474 | input = command + settings_pick 475 | 476 | if settings[0] == "": 477 | print("\nConnecting you to the best possible server (quick connect option)...") 478 | else: 479 | print("\n\33[34mConnecting you to", settings_pick[0], "...\n\33[0m") 480 | 481 | try: 482 | if opsys == "Windows": 483 | new_connection = subprocess.Popen(input, shell=True, cwd=cwd_path) 484 | new_connection.wait(50) 485 | else: 486 | new_connection = check_output(input) 487 | print("Found a server! You're now on "+re.search('(?<=You are connected to )(.*)(?=\()', str(new_connection))[0].strip()) 488 | except: 489 | print("\n An unknown error occurred while connecting to a different server! Retrying with a different server...\n") 490 | time.sleep(15) 491 | continue 492 | 493 | for i in range(12): 494 | try: 495 | new_ip = get_ip() 496 | except: 497 | time.sleep(5) 498 | continue 499 | else: 500 | if new_ip in [current_ip,og_ip]: 501 | time.sleep(5) 502 | continue 503 | else: 504 | break 505 | else: 506 | pass 507 | 508 | if new_ip in [current_ip,og_ip]: 509 | print("ip-address hasn't changed. Retrying...\n") 510 | time.sleep(10) 511 | continue 512 | else: 513 | print("your new ip-address is:", new_ip) 514 | 515 | if google_check == 1: 516 | print("\n\33[33mPerforming captcha-check on Google search and Youtube...\n" 517 | "---------------------------\33[0m") 518 | try: 519 | google_search_check = BeautifulSoup( 520 | requests.get("https://www.google.be/search?q=why+is+python+so+hard").content,"html.parser") 521 | youtube_video_check = BeautifulSoup( 522 | requests.get("https://www.youtube.com/watch?v=dQw4w9WgXcQ").content,"html.parser") 523 | 524 | google_captcha = google_search_check.find('div',id="recaptcha") 525 | youtube_captcha = youtube_video_check.find('div', id = "recaptcha") 526 | 527 | if None not in (google_captcha,youtube_captcha): 528 | print("Google throws a captcha. I'll pick a different server...") 529 | time.sleep(5) 530 | continue 531 | except: 532 | print("Can't load Google page. I'll pick a different server...") 533 | time.sleep(5) 534 | continue 535 | else: 536 | print("Google and YouTube don't throw any Captcha's: \33[92m\N{check mark}\33[0m") 537 | break 538 | else: 539 | break 540 | 541 | else: 542 | raise Exception("Unable to connect to a new server. Please check your internet connection.\n") 543 | 544 | print("\nDone! Enjoy your new server.\n") 545 | #2.terminate 546 | def terminate_VPN(instructions=None): 547 | if instructions is None: 548 | instructions = saved_settings_check() 549 | 550 | opsys = instructions['opsys'] 551 | if opsys == "Windows": 552 | cwd_path = instructions['cwd_path'] 553 | 554 | print("\nDisconnecting...") 555 | if opsys == "Windows": 556 | terminate = subprocess.Popen(["nordvpn", "-d"],shell=True,cwd=cwd_path,stdout=DEVNULL) 557 | else: 558 | terminate = subprocess.Popen(["nordvpn", "d"],stdout=DEVNULL) 559 | 560 | terminate.wait() 561 | print("Done!") --------------------------------------------------------------------------------