Python Forum
Login to NordVPN on Linux with python script - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Login to NordVPN on Linux with python script (/thread-32398.html)



Login to NordVPN on Linux with python script - AGreenPig - Feb-07-2021

Hello! I am fairly new to both python and Linux so forgive me if my code is bad or this is in the wrong Forum.
My Problem:
I am on a Kali Linux Virtual Machine. I have a list of NordVPN accounts with password in the form email:password. Since NordVPN connections only work when under six people are using the account at once and the accounts are public and are being shared, I would like to write a script that:
  1. Tries to login with the Email and Password (Goes to the next one if the password is wrong)
  2. Tries to connect to a server in a specific country. If the connection fails or takes too long, it goes to the next account.
  3. If the connection was a success, stop the program and print the used Email with password.

I am not 100% sure how to do this. I have written a script that looks like this:

import subprocess
import time
def checkConnection():
	cmd = ['nordvpn', 'c']
	proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

	o, e = proc.communicate()

	if "Connected" in o.decode('ascii'):
		return True
	else:
		return False

def tryConnection():
	cmd = ['nordvpn', 'c']
	proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
	time.sleep(2)
	if checkConnection() == True:
		print("Sucessfull Connection with:\n" + email +" " +password)
	else:
		print("Failed")
		cmd = ['nordvpn', 'logout']
		proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
			
		print("Logged out")
	
def loginWithPassword(email, password):
	cmd = ['nordvpn', 'login', '-u', email, '-p', password]
	proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
	print(proc)
	o, e = proc.communicate()

	if "is not correct" in o.decode('ascii'):
		print("Wrong password")
	else:
		tryConnection()

f = open("list.txt", "r")
for line in f:
	username = line.split(":")[0]	
	password = line.split(":")[1]
	print("--------------------------\nUsername "+username+", Password "+password)
	
	loginWithPassword(username, password)
But the connection just fails for every login. It could be a possibility that I have just set up NordVPN wrong, but I can manually login via the terminal.

Thanks for your help!


RE: Login to NordVPN on Linux with python script - nilamo - Feb-08-2021

What about it is failing? Are you getting errors? What's the output of the subprocess command?


RE: Login to NordVPN on Linux with python script - AGreenPig - Feb-09-2021

I think I got it to work like this:
import os
import subprocess
import sys
import argparse
import time
from typing import Union

# console colors
G = '\033[92m'  # Green
W = '\033[93m'  # Warning (yellow)
R = '\033[91m'  # Red
E = '\033[0m'   # Erase (the default color)
B = '\033[34m'  # Blue


def read_arguments():

    parser = argparse.ArgumentParser(
        description='Check NordVPN login and Connection'
    )

    parser.add_argument(
        '-f',
        '--file',
        help='The file that contains your email:password entries',
        action='store',
        required=True,
        metavar='FILE'
    )

    return parser.parse_args()
def try_connection() -> Union['False', None, str]:
    connection_result = subprocess.run(
    ['nordvpn', 'c'],
    capture_output = True,
    text = True
    )
    if not connection_result.returncode == 0:
    #failed to connect
        return False
    else:
        connection_info = subprocess.run(
            ['nordvpn', 'status'],
            capture_output=True,
            text=True
        )
        if 'Disconnected' in connection_info.stdout:
            return None
        else:
            return connection_info.stdout

def check_login(email: str, password: str) -> Union['False', None, str]:
    # make sure you're logged out of NordVPN
    subprocess.run(['nordvpn', 'logout'], capture_output=True)

    login_result = subprocess.run(
        ['nordvpn', 'login', '-u', email, '-p', password],
        capture_output=True,
        text=True
    )
    if not login_result.returncode == 0:
        # Failed to login
        return False
    else:
        # Ensure the user is logged in
        account_info = subprocess.run(
            ['nordvpn', 'account'],
            capture_output=True,
            text=True
        )
        if 'You are not logged in.' in account_info.stdout:
            return None
        else:
            return account_info.stdout


def parse_expiration_date(login_result: str) -> str:
    return login_result.split('VPN Service: ')[
        1].rstrip()


def read_file(args) -> None:
    input_file_path = args.file
    if not os.path.isfile(input_file_path):
        print('The path specified does not exist', input_file_path)
        sys.exit()

    # check if the specified file is empty
    if os.stat(input_file_path).st_size == 0:
        print('The file specified is empty.')
        sys.exit()

    with open(input_file_path) as f:
        count = 0
        for line in f:
            if not line.strip():  # ignore empty lines in file
                continue

            count += 1

            email, password = line.strip().split(':')
            print(B + f'{count}) Checking ➜', W +
                  f'{email}:{password}\r' + E, end='')

            login_result = check_login(email, password)
            connection_result = try_connection()

            if not login_result:
                # Failed to login
                print(
                    B + f'{count}) Checking ➜',
                    W + f'{email}:{password}',
                    '\t\t\t',
                    R + 'Failed' + E
                )
            elif login_result is None:
                # No response from NordVPN
                print(
                    B + f'{count}) Checking ➜',
                    W + f'{email}:{password}',
                    '\t\t\t',
                    R + 'No response' + E
                )
                print(
                    R+"NordVPN might be temporarily blocking your IP due to too many requests."+E)
            elif not connection_result:
        #failed to connect
                print(
                    B + f'{count}) Checking ➜',
                    W + f'{email}:{password}',
                    '\t\t\t',
                    R + 'Failed to Connect' + E
                )
            elif connection_result is None:
            #No Connection Result
                print(
                        B + f'{count}) Checking ➜',
                        W + f'{email}:{password}',
                        '\t\t\t',
                        R + 'No response Connection' + E
                    )
                print(R+"NordVPN might be temporarily blocking your IP due to too many requests."+E)
            else:
                account_expiration_date = parse_expiration_date(login_result)
                print(
                    B + f'{count}) Checking ➜',
                    W + f'{email}:{password}\t\t',
                    G + account_expiration_date ,
                    B + 'Connection Success!\n\n' + E
                )
                print("█▀▀ █▀█ █▄░█ █▄░█ █▀▀ █▀▀ ▀█▀ █ █▀█ █▄░█   █▀ █░█ █▀▀ █▀▀ █▀▀ █▀ █▀\n" +
                      "█▄▄ █▄█ █░▀█ █░▀█ ██▄ █▄▄ ░█░ █ █▄█ █░▀█   ▄█ █▄█ █▄▄ █▄▄ ██▄ ▄█ ▄█")
                print('------------------------------------------------------------------------------')
                print(email+" "+password)
                print('------------------------------------------------------------------------------')
                exit()

if __name__ == "__main__":
    args = read_arguments()

    # Initialize the script
    try:
        read_file(args)
    except KeyboardInterrupt:
        print(R+"\nQuitting..."+E)
I found a script on Github from behnambm that just checks if the login was successful, so I edited the script so that the connection gets tested as well. Hopes this works and helps someone.