Error exception causing print to fail - python2 - python

Here is a snippet from my code. For some reason it simply won't print out the second line saying "Cracking took 10 seconds" or whatever, but this first bit saying Password Found: does work... Why?
def connect(host, user, password, release):
global Found
global Fails
global startTime
try:
s = pxssh.pxssh()
s.login(host, user, password)
print '[+] Password Found: ' + password
print 'Cracking the password took' + datetime.now()-startTime + 'seconds.'
Found = True
except Exception, e:
if 'read_nonblocking' in str(e):
Fails += 1
time.sleep(5)
connect(host, user, password, False)
elif 'synchronize with original prompt' in str(e):
time.sleep(1)
connect(host, user, password, False)

You are trying to concatenate two different things (datetime and str), try converting the datetime to str as:
def connect(host, user, password, release):
global Found
global Fails
global startTime
try:
s = pxssh.pxssh()
s.login(host, user, password)
print '[+] Password Found: ' + password
print 'Cracking the password took' + str(datetime.now()-startTime) + 'seconds.'
Found = True
except Exception, e:
if 'read_nonblocking' in str(e):
Fails += 1
time.sleep(5)
connect(host, user, password, False)
elif 'synchronize with original prompt' in str(e):
time.sleep(1)
connect(host, user, password, False)
Moreover, you shouldn't trap all kind Exception, just those you need.

The issue is probably that you haven't set startTime, but you masked it by over-broad exception handling. Either remove the try/except, select some other exception to trap, or simply include a bare raise command in your exception handler and you should see a NameError because of the absence of initialization. Fix that and your code has more of a chance.

Related

How difference between ConnectionAbortedError, ConnectionRefusedError and ConnectionResetError and whether to catch an exception

I'm working on the internet connection programming, including Server and Client Socket, FTP, SMTP. But there is an error that depending on internet connection condition that I must handle it. But I don't know what the ConnnectionAbortedError, ConnectionRefusedError and ConnectionResetError do. And whether to catch an exception.
I definitely understand that TimeoutError is catch for the connection is not respond for long time then raise an error.
But I can't identify what are the three connection errors on above do.
FTPManager.py module for using in another module.
from ftplib import *
blockSize = 1024
host = "localhost"
instance = None
def login():
global instance
while True:
try:
instance = FTP(host)
instance.login(user="NetPro",passwd="12345678")
instance.retrlines("LIST")
instance.cwd("Final Assignment")
print("FTP Connected!")
break
except TimeoutError:
print("FTP Login Timeout Error. Retrying...")
def logout():
global instance
instance.quit()
def changeDirectory(directory):
global instance
instance.cwd(directory)
instance.retrlines("LIST")
def listAllFiles():
global instance
return instance.nlst()
def isFileExists(filename):
global instance
fileList = instance.nlst()
if filename in fileList:
return True
return False
def downloadFile(filename):
while True:
try:
with open(filename,"wb") as f:
instance.retrbinary("RETR " + filename, f.write, blockSize)
print("Download file " + filename + " completed.")
break
except ConnectionRefusedError:
print("FTP Connection has been aborted.")
login()
def uploadFile(filename):
while True:
try:
with open(filename,"rb") as f:
instance.storbinary("STOR " + filename, f, blockSize)
print("Upload file " + filename + " completed.")
break
except ConnectionAbortedError:
print("FTP Connection has been aborted.")
login()
login()
The error exception is also used in SMTPManager.py for handling the internet connection error.
Thank you. Any help is appreciated.

Python 3 Mass Email Verification Connection Refused

Im having trouble verifying a mass list of email addresses. The issue is with the error code "connection refused" Every email verification returns Connection refused. Why would this be? Can you give me a solution? No issues with verifying the email syntax
The below code is only for the correct area of the programme, i.e mxrecord check. Im using intellij Idea, python 3.4.3 and tkinter for the GUI.
def handle_accuracy(self):
for email in self.emails:
# See if email string contains ampersand and period.
if (email.find('#') < 0) or (email.find('.') < 0):
print("Email not syntactically correct.")
self.inaccurate_emails.append(email)
else:
email_exists = self.check_existence(email)
if email_exists:
print("Email is accurate and exists.")
self.accurate_emails.append(email)
else:
print("Email is syntactically correct but couldn\'t be found")
self.inaccurate_emails.append(email)
def check_existence(self, email):
at_pos = email.find('#')
mx_name = email[(at_pos + 1):]
# Connect to email server and get name of SMTP server
records = dns.resolver.query(mx_name, 'MX')
for record in records:
print(record.exchange)
mxRecord = records[0].exchange
mxRecord = str(mxRecord)
host = socket.gethostname()
# Setup an exception block to handle issues with connection.
try:
server = smtplib.SMTP(mxRecord)
except TimeoutError:
print("Timeout")
# Indicate to calling function that email cannot be found.
return False
except ConnectionRefusedError:
print("Connection Refused")
return False
server.set_debuglevel(0)
# Setup another exception block to handle further issues with connection.
try:
server.connect()
server.helo(host) #needs to have a helo rather than hello
server.mail(email)
code, message = server.rcpt()
except TimeoutError:
print("Timeout")
server.quit()
return False
except ConnectionRefusedError:
print("Connection Refused")
server.quit()
return False
server.quit()
if code == 250:
return True
else:
return False
Thanks in advance.

Python not catching exceptions

I have this script:
#!/usr/bin/env python
#import needed modules
import telnetlib
import time
#define variables
HOST = "xxxxxx"
user = "xxxxxx"
password = "xxxxxx"
#open telnet connection
tn = telnetlib.Telnet(HOST, 10800)
time.sleep(2)
#check for initial screen and press enter to go to login
tn.read_until("Device")
tn.write("\r\n")
time.sleep(2)
#Wait for username prompt and enter user/pass
try:
tn.read_until("User Name:",5)
except:
#Timeout looking for Username prompt
print "CRITICAL: User Name prompt never arrived"
exit(2)
tn.write(user + "\r\n")
tn.read_until("Password :")
tn.write(password + "\r\n")
time.sleep(2)
#wait for logout prompt
try:
tn.read_until("7<Logout >",5)
except:
#Timeout looking for successful login
print "CRITICAL: Did not login successfully"
exit(2)
#Logout and close connection
tn.write("7\r")
tn.close()
#Exit with success
print "OK: Test login to MWA Succeeded"
exit(0)
No matter what I do, no exceptions are caught. I changed the read_until looking for "User Name:" to just some garbage characters and it still just gets to the end of the code. I'm hoping I'm just doing something very stupid and not an issue with telnetlib.
Thanks!
Per the docs:
Read until a given string, expected, is encountered or until timeout
seconds have passed.
When no match is found, return whatever is available instead, possibly
the empty string. Raise EOFError if the connection is closed and no
cooked data is available.
Check the return value in the try block, and if this value does not match your expectations, raise on your own to trigger the except case.

subprocess function displaying odd output

I've got a function def tldomaint that executes the Tasklist command via a subprocess call_checkout. All is working as expected but I'm getting odd output from TaskList. I'm not sure if it's due to my error capturing or if its just an oddity of Tasklist. I'm hoping someone can help pin-point the issue.
Output example:
Attempting to make remote connections and gather data:
Targeted User: xpuser
ERROR: The RPC server is unavailable.
1
WARNING: User credentials cannot be used for local connections
ERROR: The RPC server is unavailable.
1
The 1 in the output is the oddity I'm referring to.
Below is the function.
def tldomaint(serverlist, domain, username, password, targetuser):
nlist = serverlist
print "\nAttempting to make remote connections and gather data:\n"
print "Targeted User: {0}\n" .format(targetuser)
for serverl in nlist:
try:
out = subprocess.check_output(["tasklist", "/V", "/S", serverl, "/U", domain + "\\" + username, "/P", password, "/FO", "List", "/FI", "USERNAME eq %s\\%s" % (domain, targetuser)])
users = [item for item in out.split() if domain in item and targetuser in item]
sortedl = set(users)
for name in sortedl:
if name in sortedl != '':
print "Targeted User Found On {0}\n" .format(serverl)
print name
else:
print "User Not Found"
except CalledProcessError as e:
print(e.returncode)
return sortedl
You are printing the process return code:
except CalledProcessError as e:
print(e.returncode)
From the subprocess.check_output() documentation:
If the return code was non-zero it raises a CalledProcessError.
When an error occured, the tasklist writes an error message to stderr, and sets the exit code to 1. subprocess.check_output() then raises the CalledProcessError exception (as documented) and you catch that exception and then print the return code.
Remove the print() statement and your mysterious 1s will go away.
If you wanted to handle the problem in Python, redirect stderr to stdout; the exception will still be raised but you can read the output still:
out = subprocess.check_output(["tasklist", "/V", "/S", serverl, "/U",
domain + "\\" + username, "/P", password, "/FO", "List",
"/FI", "USERNAME eq %s\\%s" % (domain, targetuser)],
stderr=subprocess.STDOUT)
and in your exception handler:
except CalledProcessError as e:
errormessage = e.output
# do something with the error message

Proper syntax for executing a function only if another function is successful

I have the following code that is part of my email class that I use in my programs. Currently I am running the quit function whether or not a connection to the SMTP server was made in the connect function. I know I could put the quit function inside of the try statement after the email is sent, but I would like to figure out how to write the code to say the equivalent of "if a connection to the server is open, close it." What is the best way to write that in Python?
Thanks!
def connect(self, headers, msg):
try:
self.server.starttls()
try:
self.server.login(self.usrname,self.pswd)
try:
self.server.sendmail(self.sendfrom, self.sendto, headers + "\r\n\r\n" + msg)
except Exception as sendmailfail:
print(sendmailfail)
except Exception as emailfail:
print (emailfail)
except Exception as error:
print(error)
def quit(self):
self.server.quit()
print("The SMTP connection is closed")
first = GmailSmpt('x','y','z','zz')
x , y = first.message()
first.connect(x,y)
first.quit()
You need to finish the "Errors and Exceptions" section of the tutorial.
try:
possibly_fail()
except ...:
handle_exception()
else:
no_exceptions()
finally:
always_run_this()

Categories

Resources