Ive been working on a program in Python, which cracks encrypted zip files. The problem is, part of my programs key functions doesn't work.
How my program's meant to work...
User enters in zip file name.
User enters min password length.
User enters max password length.
Program will enter a loop, where it will gen a password that is within the min & max numbers.
Program will try to open the zip with the password.
Program will then print out the password if it was successful or not.
It is the 2nd last step that my program messes up on.
Instead of stooping when the passwords match, the program continues, and then tries another password. I think this is happening because there is an error happening when it tries to open the zip. So even if the password's match, its just going straight to the "except:" statement.
Here is my code which messes up -
# Function which tries to open zip (The buggy function)
def extract(zip_name, password, number):
print("\nAttempt", number)
# Tries and opens the zip
try:
zip_name.extractall(pwd=password)
print("Success: " + password)
exit(0)
except:
print("Failed: " + password)
Can anyone please show me how to make this work. Thanks
What happens when you call exit(0)? Well, if you read the documentation for the exit built-in, then you'll see that it says:
when called, raises SystemExit with the specified exit code
so it raises an exception, but in your program this is inside a try: ... except: ... so the next thing that happens is that the exception is caught and the program prints Failed and continues.
This is why people often give the advice "don't use a bare except:" — you almost never want to catch SystemExit.
Instead you could catch the actual exception raised by zipfile when the password doesn't match, which seems to be RuntimeError. Additionally, it would improve the program if you replaced the exit(0) with something like return True, and handle success or failure at a higher level of your program.
Related
Hello everyone I have my code almost done but I'm trying to add in some sort of check to avoid errors. But I'm not really understanding what statement would be better to use to test the code. I know there are a few options of either using a loop, if-statement, or try. But here is the code in regards to doing captcha. I need it to run the first set of code which if the captcha doesn't pop up I continue on. But if the captcha does pop up solve it then continue on.
Some times captcha doesnt appear and if I run the whole set of code I get an error because we are expecting captcha to pop up.
Or if the captcha does appear to solve it which would.
I would really appreciate any help please as I'm not sure the right statement to use.
try should be used when something would return an error and would otherwise cause your program to stop/crash. An example of this would be:
try:
import pandas
except:
print("Unable to import pandas. Module not installed")
In this example your program will attempt to import the pandas module. If this fails it will then print out a line of text and continue running.
if statements are used to decided when to do something or not based on the returned logic. The key difference is that logic IS returned and not an error.
if x > 10:
print("This is a large number")
else:
print("This is a small number")
With this example, if 'x' did not exist it would produce an error, no more code will be executed, and the program will crash. The main difference between IF and TRY is whether logic is returned as true/false or is something just plains fails.
With your specific example it is important to know if the captcha appearing or not will break your code. Does the logic boil down to captcha = false or does captcha not exist at all and logic fails entirely?
Q: How do you define sometimes captcha doesn't appear (1%, 20%, 50%, ...)?
A: Maybe 5% of the time captcha doesn't appear.
In this case, I prefer to use Exception handling: do stuff and if something goes wrong, fix it
try:
# > 95% of the time the code below works when the captcha appears
except SomeException:
# < 5% of the time the code is called when the captcha doesn't appear
IMHO, you have not really 2 different codes: you have one and a fallback solution, it's really different than:
if x % 2:
...
else:
...
So I have a script that isn't quite working yet but I am hoping to get it to a point where it keeps trying to connect to a server until it finally succeeds (using the paramiko library). In simplistic terms, this is what my code is like:
canConnect = False
while canConnect == False:
try:
stdin, stdout, stderr = ssh.exec_command('ps')
if stdout.read():
canConnect = True
else:
# cannot connect
time.sleep(20)
except:
# cannot connect
time.sleep(20)
Now... this would be quite basic for a simple if statement but gets more complicated because I need to use "try" and "except". If the code can connect successfully (using "ps" as a random command that returns content and will prove the server is connectable), I assume it passes into the if condition that then sets canConnect to True and stops the loop. If it cannot connect, I think Paramiko will throw an exception (I put the "else" command there just in case), but once it hits the "except", it should wait for 20 seconds and then I assume the while statement will take the code back to the beginning and start again? What I have witnessed so far is that some kind of loop is happening, but it doesn't actually appear to be attempting to connect to the server.
Also, an unrelated question, documentation is scarce but I assume Paramiko /has/ to take 3 arguments like that to perform an exec_command (regardless of variables assigned, they will take standard output In, Out, Err in that order?)? I also assume it is uncommon to assign multiple comma-delimited variables to something like that, besides lists or method calls?
I think your use of except: may be masking the real problem, as it catches all exceptions, and disregards them. That would explain the some kind of loop is happening, but it doesn't actually appear to be attempting to connect to the server behavior. consider changing that to something like:
except (paramiko.SSHException, socket.error)
I'm new to programming and trying to work out the error handling at the moment.
But i keep running into the same problem. When I find an error i want to rerun the script again. The problem is, if you enter a good input after the first mistake, it still sees it as a bad input. please help me out.
def new_user_name()
print "Choose a Username"
username = input_str()
try:
data = lite.connect(database)
dat = data.cursor()
dat.execute("INSERT INTO Users('User_Name') VALUES(?)", username);
dat.rollback()
return username
except:
print "The username %s is already in use" % username
time.sleep(2)
new_user_name()
Can someone help me out, or link a nice tutorial about errorhandling?
It would me help out alot
dat.rollback() (if this is a valid syntax, didn't check but looks close) should be in the except section and not in the try section.
Notice that you should be better of if you initiliazed the database connection outside the function (so you won't have to do it every function call) or at least outside the try section.
dat.execute("INSERT INTO Users('User_Name') VALUES(?)", username);
This line is the problem. The second argument should be a tuple, not a string, so it's raising a ValueError. Because you're catching all errors instead of just sqlite3.IntegrityError (which would be raised if you tried to insert a duplicate primary key), you will always end up in the except block.
Never use catch-all except blocks if you can avoid it.
Python has a great official documentation, links are below:
v 2.7 http://docs.python.org/2/tutorial/errors.html
v 3.3 http://docs.python.org/3.3/tutorial/errors.html
Please notice you must never use except: without Exception class, it is a bad practice.
I've the following python 2.7.3 code which I am submitting to codechef online programming contest:
case = input()
for i in xrange(0, case):
try:
l = [elem for elem in raw_input().split()]
res = int(l[0][::-1]) + int(l[1][::-1])
print int(str(res)[::-1])
except:
break
This works on my computer, even when I use input redirection and use a in.txt file for input, still it works.
But the problem is when i submit it for evaluation, I get an exception and that exception gets removed when I use raw_input for getting the value of case
case = int(raw_input())
My in.txt file is as follows:
1
23 45
My problem is that its working on my computer perfectly, what is it that the online contest site feeding at the 1st line that an exception is being raised, and further it gets rectified when I use raw_input.
Shouldn't input() also work when my 1st line is always an integer?
Most likely, the site that you're submitting the code to disables the input command. This is sometimes done as part of "sandboxing", to prevent you from running arbitrary code on their machine. E.g., they wouldn't want to let you run a script that deletes all files on their disk.
The input command is more-or-less equivalent to running eval(raw_input()), and eval can be used to do just about anything.
You say you get an exception. Exactly what kind of exception, and what is the exception message?
I'm writing a program that adds normal UNIX accounts (i.e. modifying /etc/passwd, /etc/group, and /etc/shadow) according to our corp's policy. It also does some slightly fancy stuff like sending an email to the user.
I've got all the code working, but there are three pieces of code that are very critical, which update the three files above. The code is already fairly robust because it locks those files (ex. /etc/passwd.lock), writes to to a temporary files (ex. /etc/passwd.tmp), and then, overwrites the original file with the temporary. I'm fairly pleased that it won't interefere with other running versions of my program or the system useradd, usermod, passwd, etc. programs.
The thing that I'm most worried about is a stray ctrl+c, ctrl+d, or kill command in the middle of these sections. This has led me to the signal module, which seems to do precisely what I want: ignore certain signals during the "critical" region.
I'm using an older version of Python, which doesn't have signal.SIG_IGN, so I have an awesome "pass" function:
def passer(*a):
pass
The problem that I'm seeing is that signal handlers don't work the way that I expect.
Given the following test code:
def passer(a=None, b=None):
pass
def signalhander(enable):
signallist = (signal.SIGINT, signal.SIGQUIT, signal.SIGABRT, signal.SIGPIPE, signal.SIGALRM, signal.SIGTERM, signal.SIGKILL)
if enable:
for i in signallist:
signal.signal(i, passer)
else:
for i in signallist:
signal.signal(i, abort)
return
def abort(a=None, b=None):
sys.exit('\nAccount was not created.\n')
return
signalhander(True)
print('Enabled')
time.sleep(10) # ^C during this sleep
The problem with this code is that a ^C (SIGINT) during the time.sleep(10) call causes that function to stop, and then, my signal handler takes over as desired. However, that doesn't solve my "critical" region problem above because I can't tolerate whatever statement encounters the signal to fail.
I need some sort of signal handler that will just completely ignore SIGINT and SIGQUIT.
The Fedora/RH command "yum" is written is Python and does basically exactly what I want. If you do a ^C while it's installing anything, it will print a message like "Press ^C within two seconds to force kill." Otherwise, the ^C is ignored. I don't really care about the two second warning since my program completes in a fraction of a second.
Could someone help me implement a signal handler for CPython 2.3 that doesn't cause the current statement/function to cancel before the signal is ignored?
As always, thanks in advance.
Edit: After S.Lott's answer, I've decided to abandon the signal module.
I'm just going to go back to try: except: blocks. Looking at my code there are two things that happen for each critical region that cannot be aborted: overwriting file with file.tmp and removing the lock once finished (or other tools will be unable to modify the file, until it is manually removed). I've put each of those in their own function inside a try: block, and the except: simply calls the function again. That way the function will just re-call itself in the event of KeyBoardInterrupt or EOFError, until the critical code is completed.
I don't think that I can get into too much trouble since I'm only catching user provided exit commands, and even then, only for two to three lines of code. Theoretically, if those exceptions could be raised fast enough, I suppose I could get the "maximum reccurrsion depth exceded" error, but that would seem far out.
Any other concerns?
Pesudo-code:
def criticalRemoveLock(file):
try:
if os.path.isFile(file):
os.remove(file)
else:
return True
except (KeyboardInterrupt, EOFError):
return criticalRemoveLock(file)
def criticalOverwrite(tmp, file):
try:
if os.path.isFile(tmp):
shutil.copy2(tmp, file)
os.remove(tmp)
else:
return True
except (KeyboardInterrupt, EOFError):
return criticalOverwrite(tmp, file)
There is no real way to make your script really save. Of course you can ignore signals and catch a keyboard interrupt using try: except: but it is up to your application to be idempotent against such interrupts and it must be able to resume operations after dealing with an interrupt at some kind of savepoint.
The only thing that you can really to is to work on temporary files (and not original files) and move them after doing the work into the final destination. I think such file operations are supposed to be "atomic" from the filesystem prospective. Otherwise in case of an interrupt: restart your processing from start with clean data.