Python Forum
Login to NordVPN on Linux with python script
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Login to NordVPN on Linux with python script
#1
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!
Reply
#2
What about it is failing? Are you getting errors? What's the output of the subprocess command?
Reply
#3
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Is possible to run the python command to call python script on linux? cuten222 6 629 Jan-30-2024, 09:05 PM
Last Post: DeaD_EyE
  Is there a *.bat DOS batch script to *.py Python Script converter? pstein 3 3,000 Jun-29-2023, 11:57 AM
Last Post: gologica
  [SOLVED] [Linux] Script in cron stops after first run in loop Winfried 2 894 Nov-16-2022, 07:58 PM
Last Post: Winfried
  How to compile a Python script for a Windows / Linux executable? netanelst 2 1,272 May-24-2022, 07:02 AM
Last Post: netanelst
  How to use a variable in linux command in python code? ilknurg 2 1,547 Mar-14-2022, 07:21 AM
Last Post: ndc85430
  Python syntax in Linux St0rmcr0w 2 44,677 Jul-29-2021, 01:40 PM
Last Post: snippsat
  Error when running script on startup in Linux NoahTheNerd 0 1,924 Mar-07-2021, 04:54 PM
Last Post: NoahTheNerd
  in a login interface when i try login with a user supposed to say test123 but nothing NullAdmin 3 2,217 Feb-20-2021, 04:43 AM
Last Post: bowlofred
  how to run linux command with multi pipes by python !! evilcode1 2 6,215 Jan-25-2021, 11:19 AM
Last Post: DeaD_EyE
  where to get portable Python for Linux (Fedora)? python001 5 6,155 Nov-01-2020, 05:23 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020