Pexpect Brute Force, Python 2.7 - python

I've written a program that connects to a server on port 80, the goal being to brute force the login to gain access to the files inside.
I'm using john.txt as my password list, I know this list contains the password I need. When I run the program, it starts to attempt different passwords, but it's only testing every 3rd password in the list.
Here's my code:
import pexpect
password_list = 'john.txt'
passwords = open(password_list)
child = pexpect.spawn('nc 83.212.97.72 80')
for x in passwords.readlines():
ans = child.expect(['Login:', 'Password:', 'Login Incorrect', 'Too many failed attempts', 'Welcome max'])
if ans == 0:
child.sendline('max')
elif ans == 1:
child.sendline(x)
print 'Attemping {}'.format(x)
elif ans == 2:
child = pexpect.spawn('nc 83.212.97.72 80')
elif ans == 3:
child = pexpect.spawn('nc 83.212.97.72 80')
elif ans == 4:
print 'Login completed, welcome max'
As far as I can tell, there's no Syntax errors in my code, does anyone know why the program is only testing every 3rd password in john.txt?

Related

Trying to understand flow control/charting

import sys
access = False
while not access:
username = input('Enter username: ')
if username.lower() != 'joe':
print("imposter!")
continue
else:
print(f'Hello {username.capitalize()}')
for i in range(3):
password = input('Enter password: ')
if password == 'Water':
access = True
break
else:
print("3 strikes, you're out")
sys.exit()
print("Access granted")
Is this the proper flowchart for this code? I'm trying to understand how to properly draw flowcharts with for loops. I'm teaching myself through 'Automate the Boring Things in Python'
Your program looks quite well following your flowchart, However, to complete it without having to explicitly invoking the exit() function and END the flow at the end of the module, consider introducing a new flag, I called mine bol_access_denied. Really, it could be called by any name:
import sys
bol_access_denied = False # You will need to introduce a flag before you enter your while...loop.
access = False
while not access:
username = input('Enter username: ')
if username.lower() != 'joe':
print("imposter!")
continue
# else: # This else can be omitted since program flows here ONLY when username == joe
print(f'Hello {username.capitalize()}')
for i in range(3):
password = input('Enter password: ')
if password == 'Water':
access = True
break
else:
print("3 strikes, you're out")
bol_access_denied = True # set the flag here.
# sys.exit() This can be replaced by 'break', then backed by [see STEP Final-Check]
if bol_access_denied: # Test the flag here.
break
if access: # STEP Final-Check, is to navigate the user to a personalized section of your program.
print("Access granted")
# Your program ends here naturally without explicitly invoking the exit function.
Hope it helps.

Trouble navigating through my loops in Python

I have already asked people around me and tried countlessly to get this fix program. The program should be able to add the users websites and passwords as many times as they want to, and show the websites and password they selected.
For now when you answer would you like to add another website? with yes it dosn't re ask for a new website name and password but just repeats the question would you like to add another website?, also when you have entered in a website name and password and answer would you like to add another website? with no then selected option 1 to see existing accounts, it repeats would you like to add another website?, when this should even come up at option one
Inputs and how it should output:
1) find your existing passwords
2) save a new password for your apps
3) see a summary of your password locker
4) exit password locker successfully 1
You have no stored websites and passwords
1) find your existing passwords
2) save a new password for your apps
3) see a summary of your password locker
4) exit password locker successfully 2
What is the name of the website/app your are adding? instagram
What is the password of your {instagram} account? bob91
Would you like to add another website? yes
What is the name of the website/app your are adding? facebook
What is the password of your {facebook} account? bob92
Would you like to add another website? no
1) Find your existing passwords
2) Save a new password for your apps
3) See a summary of your password locker
4) Exit password locker successfully 1
enter the app you want to find the password for instagram
websitename = instagram
password = bob91
Full code:
vault_apps = []
app_name = ""
def locker_menu_func():
print('''You have opened the locker,
Please select what you would like to do,''')
locker_menu_var = input('''Press: \n1) find your existing passwords \n2) save a new password for your apps\n3) see a summary of your password locke \n4) exit password locker successfully\n---------------------------------------------------------------------------------
''')
print('''----------------------------------------------------------------''')
while True:
if locker_menu_var == "1":
while len(vault_apps) < 1:
print('''you have nothing stored''')
if len(vault_apps) > 1:
print(vault_apps)
break
break
if locker_menu_var == "2":
app_name = input('''
What is the name of the website/app your are adding?
''')
app_password = input('''What is the password of your {} account?
'''.format(app_name))
vault_apps.append([app_name, app_password])
while True:
ask_again = input('''Would you like to add another app and password?
''')
if ask_again.lower() == "yes":
locker_menu_var = "2"
elif ask_again.lower() == "no":
locker_menu_func()
else:
print("please enter a valid response") #should repeat if user want to add another website
Your code does not work because you do not break from a while True:-loop:
while True:
ask_again = input('''Would you like to add another app and password?''')
if ask_again.lower() == "yes":
locker_menu_var = "2" <--- does not leave while loop
elif ask_again.lower() == "no":
locker_menu_func()
else:
# etc.
Keep your methods small and handling one concern to simplify your control flow, example:
vault_apps = {}
# ,2,Hallo,Yuhu,y,Hallo2,Yuh,n,3,4
def menu():
print('\n'+'-'*40)
print('1) find your existing passwords')
print('2) save a new password for your apps')
print('3) see a summary of your password locker')
print('4) exit password locker successfully')
print('-'*40)
k = None
while k not in {"1","2","3","4"}:
k = input("Choose: ")
return int(k) # return the number chosen
def input_new_app():
global vault_apps
app = None
while not app:
app = input("What is your apps name? ")
pw = None
while not pw:
pw = input("What is your apps passphrase? ")
vault_apps[app]=pw
def print_vault():
print("Vault content:")
for key,value in vault_apps.items():
print(f" {key:<10}\t==>\t{value}")
def find_password():
if vault_apps:
pass
else:
print("nothing in your password store")
def main():
k = None
print('You have opened the locker,\nPlease select what you would like to do.')
while True:
choice = menu()
if choice == 1:
find_password()
elif choice == 2:
input_new_app()
k = input("Would you like to add another app and password?").lower()
while k in {"yes","y"}:
input_new_app()
elif choice == 3:
print_vault()
elif choice == 4:
print("Good bye")
break
main()
Output:
You have opened the locker,
Please select what you would like to do.
----------------------------------------
1) find your existing passwords
2) save a new password for your apps
3) see a summary of your password locker
4) exit password locker successfully
----------------------------------------
Choose: 1
nothing in your password store
----------------------------------------
1) find your existing passwords
2) save a new password for your apps
3) see a summary of your password locker
4) exit password locker successfully
----------------------------------------
Choose: 2
What is your apps name? A
What is your apps passphrase? 66
Would you like to add another app and password? n
----------------------------------------
1) find your existing passwords
2) save a new password for your apps
3) see a summary of your password locker
4) exit password locker successfully
----------------------------------------
Choose: 3
Vault content:
A ==> 66
----------------------------------------
1) find your existing passwords
2) save a new password for your apps
3) see a summary of your password locker
4) exit password locker successfully
----------------------------------------
Choose: 4
Good bye
This logic is flawed.
Once you enter the infinite while loop, you have no way to exit it, other than to enter "no". When you enter "yes", the value of locker_menu_var changes, but you donot exit the loop, so it keeps repeating the same menu.
while True:
ask_again = input('''Would you like to add another app and password?
''')
if ask_again.lower() == "yes":
locker_menu_var = "2"
elif ask_again.lower() == "no":
locker_menu_func()
You are mixing the looping and recursion, which is making things confusing. One simple way to do this is:
vault_apps = []
def locker_menu():
# the entry message
msg = '''You have opened the locker, Please select what you would like to do,'''
print(msg, end="\n\n")
# nume options
menu = ["1) find your existing passwords",
"2) save a new password for your apps",
"3) see a summary of your password locker",
"4) exit password locker successfully"]
menu_string = f"Press:\n{menu[0]}\n{menu[1]}\n{menu[2]}\n{menu[3]}\n"
# now enter the loop
while True:
# input variable
# NOTE: This variable is inside the loop,
# so that the user can enter the value everytime
# the loop repeates.
locker_menu_var = input(menu_string)
if locker_menu_var == "1":
# retrieve password for an existing record.
# although it's not a good idea to just print
# all the records, I am not changing your application logic
# because I don't see any use in it.
# you missed one case in your logic,
# which I have fixed here.
if len(vault_apps) == 0:
print("you have nothing stored")
else:
print(vault_apps)
elif locker_menu_var == "2":
# for a new entry
# enter your logic here
an = input("app name: ")
passw = input("password: ")
vault_apps.append([an, passw])
done = False # flag for exiting
while not done:
inp = input("enter another?")
if inp == "yes":
# enter logic here
an = input("app name: ")
passw = input("password: ")
vault_apps.append([an, passw])
else:
done = True
elif locker_menu_var == "3":
# do something
pass
elif locker_menu_var == "4":
return
if __name__ == "__main__":
locker_menu()

Python: Being asked for input twice and outputting duplicate print statements

I am trying to finish off my program my adding a menu that allows the user to select a few options that allow the user to store website names and passwords in lists. But there was a problem as soon as I have appended some website names and passwords into their respective vaults where whenn I try to select an option after appending the website names and passwords, "1" for example is the expected input to call the viewapp() function to see the websites and passwords stored so far. The thing is it takes more than twice to call the viewapp() function, where it rejects the first expected input but accepts the 2nd one strangely. Also when I select the 3rd option for the purpose to call summary(), the whole printed summary would print out twice, which is a similar pattern to the menu only accepting the 2nd expected input. The program is doing what I want except for this annoying bug where selecting those four options makes it ask for input a second time when it's supposed to straight away jump to that function. Help would be appreciated.
appvault = []
passvault = []
def logged():
print("----------------------------------------------------------------------\n")
print("Hello, welcome to the password vault console. ")
modea = input("""Below are the options you can choose from in the password vault console:
##########################################################################\n
1) Find the password for an existing webiste/app
2) Add a new website/app and a new password for it
3) Summary of the password vault
4) Exit
##########################################################################\n
> """).strip()
return modea
def viewapp():
if len(appvault) > 0:
for app in appvault:
print("Here is the website/app you have stored:")
print("- {}\n".format(app))
if len(passvault) > 0 :
for code in passvault:
print("Here is the password you have stored for the website/app: ")
print("- {}\n".format(code))
else:
print("You have no apps or passwords entered yet!")
def addapp():
while True:
validapp = True
while validapp:
new_app = input("Enter the new website/app name: ").strip().lower()
if len(new_app) > 20:
print("Please enter a new website/app name no more than 20 characters: ")
elif len(new_app) < 1:
print("Please enter a valid new website/app name: ")
else:
validapp = False
appvault.append(new_app)
validnewpass = True
while validnewpass:
new_pass = input("Enter a new password to be stored in the passsword vault: ")
if not new_pass.isalnum():
print("Your password for the website/app cannot be null, contain spaces or contain symbols \n")
elif len(new_pass) < 8:
print("Your new password must be at least 8 characters long: ")
elif len(new_pass) > 20:
print("Your new password cannot be over 20 characters long: ")
else:
validnewpass = False
passvault.append(new_pass)
validquit = True
while validquit:
quit = input("\nEnter 'end' to exit or any key to continue to add more website/app names and passwords for them: \n> ")
if quit in ["end", "End", "END"]:
logged()
else:
validquit = False
addapp()
return addapp
def summary():
if len(passvault) > 0:
for passw in passvault:
print("----------------------------------------------------------------------")
print("Here is a summary of the passwords stored in the password vault:\n")
print("The number of passwords stored:", len(passvault))
print("Passwords with the longest characters: ", max(new_pass for (new_pass) in passvault))
print("Passwords with the shortest charactrs: ", min(new_pass for (new_pass) in passvault))
print("----------------------------------------------------------------------")
else:
print("You have no passwords entered yet!")
while True:
chosen_option = logged()
print(chosen_option)
if chosen_option == "1":
viewapp()
elif chosen_option == "2":
addapp()
elif chosen_option == "3":
summary()
elif chosen_option == "4":
break
else:
print("That was not a valid option, please try again: ")
print("Goodbye")
This happens because you call logged() when exiting addapp():
if quit in ["end", "End", "END"]:
logged()
Then, the choice you enter is returned by logged(), and thrown away as it isn't assigned to anything.
You're now back at the end of the previous block in addapp(), and the next instruction is return addapp, that will bring you back to your main loop, where you'll be sent to logged() again by chosen_option = logged()
Note that in return addapp, you return the addapp function itself, which is certainly not what you want to do. So, as you don't need a return value for addapp(), just use return, or nothing at all, Python will automatically return at the end of the function.
So, to solve your problem: directly return when you're done entering sites:
if quit in ["end", "End", "END"]:
return
Note also that you recursively call addapp() from itself when you add more sites.
You should generaly avoid that unless you really want to use some recursive algorithm, and rather use a loop as you did in your main loop. By default, Python limits you to 1000 recursion levels - so you could even crash your app by entering more than 1000 sites in a row ;)
The summary problem is only caused by the unnecessary for loop in summary()
You are nearly there. The issue is in the addapp() function at line 63:
if quit not in ["end", "End", "END"]:
logged()
if you replace
logged()
with
pass
Then everything will work a ok.
You are not handling the result of the logged function here anyway.
You also do not need to process the logged function here. The addapp will exit and the logged function will be called and handled in the while loop the addapp function was called from.

Why won't this print, when I type in a keyword?

`print"Welcome to Caleb's login script!"
loop = 'true'
while(loop == 'true'):
username = raw_input("Username Please")
password= raw_input("Password Please")
if(username == "Caleb" and password == "Lamps320"):
print 'Logged in as ' + username
loop = 'false'
loop1 = 'true'
while(loop1 == 'true'):
command = raw_input(username + " >> ")
if(command == "exit" or command == "Exit"):
break
if(command == "Passwords" or command == "passwords"):
print"passwords"
else:
print 'Invalid Username/password! Please try again.'
I want it to print passwords when I type "Passwords or passwords" it will say 'password'. But when I try and run it and log in and type in passwords or Passwords it will not work. Can somebody help me?
The code is supposed to be a login system to access something. But when I type in the keyword (password) it just returns the command prompt. Note: I used Python2.7.3 (Also I can't get the python code to work with the code indent.
--For those just seeing this, I apologize! This was done very badly and when I was very immature! I have learned a lot since this post. Thanks to the person who tried to help old me!
Your script is inconsistently indented. It does what you say it does when that is fixed.
print"Welcome to Caleb's login script!"
loop = 'true'
while(loop == 'true'):
username = raw_input("Username Please")
password= raw_input("Password Please")
if(username == "Caleb" and password == "Lamps320"):
print 'Logged in as ' + username
loop = 'false'
loop1 = 'true'
while(loop1 == 'true'):
command = raw_input(username + " >> ")
if(command == "exit" or command == "Exit"):
break
if(command == "Passwords" or command == "passwords"):
print"passwords"
else:
print 'Invalid Username/password! Please try again.'
Depending on how secure this is supposed to be, there are many ways to make it better. Here are a few.
Compare the password to a hash instead of the actual password so your password isn't in plaintext inside the file. See, for example, PyBcrypt project
No 'true' and 'false' constants. Python already has True and False for this purpose, they are the boolean type.

Python program write to another python program?

New to programming and started a hobby project. In Python 3.4 I put together a program to type numbers to another Python program that acts as a combo lock. The combo lock reads 3 digit combos 000-999, unlocking if the user or second Python program types the correct 3 digit combo. I've accomplished the typer program using from win32api import keybd_event and have the functions to support this.
Snippit of typer program:
def main():
os.startfile('lockprogram.py')
for num in range(0,1000):
Write(str(num).zfill(3),speed = 1000)
Press('ENTER')
main()
Here's the lock program:
def main():
start = 'locked'
while start =='locked':
password = str(input('Enter the numbered three digit password: '))
if password == str(671).zfill(3):
start = 'open'
input('You unlocked the program. Enter to continue. ')
else:
print('Incorrect.')
#End program response.
x = True
while x == True:
response = str(input('To end press q: '))
if response == 'q':
x = False
else:
print()
main()
I'd like the typer program to write specifically to the lockprogram.py and not just as keyboard presses typing out in the open. Is there anyway to accomplish this? Like a py_file.write()?
The answer I'm writing below deviates a bit from writing to file. I'm using a multiprocessing.Queue (which internally it uses a Pipe, which uses a file to communicate the processes), but from a programatic point of view, it looks like it doesn't (I don't know if this is what you want or not). If you want to go with this solution, you should take a look to the documentation of the multiprocessing module.
You can certainly implement your own inter-process communication system, if you prefer, but once you start doing multi-threaded stuff, things get ugly. If it's multi-processed, things get... well... much, much uglier, so I'd go with something that exists out there, is well tested... yadda yadda yadda
I'd make this my typer.py:
def main(q):
while True:
print "Yellou. User typed %s" % q.get()
And this my lock.py:
from multiprocessing import Process, Queue
import typer
def main():
start = 'locked'
while start == 'locked':
password = str(
input('Enter the numbered three digit password: ')
).zfill(3)
print "You entered %s" % password
if password == '671':
start = 'open'
input('You unlocked the program. Enter to continue. ')
else:
print('Incorrect.')
# End program response.
# Launch typer.py
q = Queue()
p = Process(target=typer.main, args=(q,))
p.start()
x = True
while x is True:
response = input('To end press q: ')
if response == 'q':
x = False
p.terminate()
else:
q.put(response)
if __name__ == "__main__":
main()
To be able to import typer in lock.py these two scripts musts live in a directory that contains a third python file called __init__.py . This file can be totally empty, but I'll tell python that it's currently in a package (see this and this).
Your directory structure should look something like this:
my_programs/
|> typer.py
|> lock.py
|> __init__.py
If you run your lock.py, this will happen:
Enter the numbered three digit password: 671
You entered 671
You unlocked the program. Enter to continue.
Here
To end press q: helou
To end press q: Yellou. User typed helou
howdy?
To end press q: Yellou. User typed howdy?
q
As I mentioned, I'm not sure if this is what you're looking for exactly.
EDIT (I think the OP was trying to use typer.py to find the number that unlocks "the program")
If what you want is simulate a user interaction with the lock.py, I suggest you look at pexpect. As far as I know, is multiplatform:
This would be your typer.py
import pexpect
def main():
child = pexpect.spawnu('python /path/to/lock.py')
child.expect(u"Enter the numbered three digit password:.*", timeout=1)
pwd = None
for num in range(1000):
if pwd is None:
print "Trying %s" % (num)
child.sendline(unicode(num))
i = child.expect([
u'You entered.*\r\nIncorrect.*',
u'You entered.*\r\nYou unlocked the program.*',
pexpect.EOF])
if i == 0:
print "%s didn't work" % num
elif i == 1:
print "Cracked. Num is %s" % num
pwd = num
child.terminate(force=True)
else:
print "woot?"
return pwd
print "Got %s" % main()
That should find your number:
Trying 669
669 didn't work
Trying 670
670 didn't work
Trying 671
Cracked. Num is 671
Got 671

Categories

Resources