Code:
def ScanNetwork():
nmScan = nmap.PortScanner()
s = nmScan.scan("192.168.1.1/24", '0-4444', arguments="-O")
for host in nmScan.all_hosts():
if nmScan[host].state() == "up":
print("Host : %s (%s)" % (host, nmScan[host].hostname()))
try:
print("Version: " + s['scan'][host]['osmatch'][0]['name'] + "\nType: " + s['scan'][host]['osmatch'][0]['osclass'][0]['type'])
except:
print("An Error occured while scanning this host!\nNo extra info was collected!")
continue
for proto in nmScan[host].all_protocols():
print("---------------------------")
print("\nProtocol : %s" % proto)
lport = nmScan[host][proto].keys()
lport = sorted(lport)
for port in lport:
print("\nport: " + f'{port}' + "\tstate: " + nmScan[host][proto][port]['state'])
print("---------------------------\n")
print("\n\nScan Completed!")
ScanNetwork()
Sometimes an exception occurs when the nmap fails to identify the Version or the Os running in a host. (It's a KeyError exception)
The part which is supposed to handle that exception is this:
try:
print("Version: " + s['scan'][host]['osmatch'][0]['name'] + "\nType: " + s['scan'][host]['osmatch'][0]['osclass'][0]['type'])
except:
print("An Error occured while scanning this host!\nNo extra info was collected!")
continue
I of course assume that there's nothing wrong with nmap's output and I've again made a huge beginner mistake and that's the reason my code is getting stuck..
Notes:
I've left the script running over night incase it returned some useful info but nothing happened!
Please do not tell me that I need to quit using the nmap module and turn to nmap3
Having tired you with all the above, does anyone know a way to still handle that exception without the code getting stuck?
You have forgotten to add the type of the exception to excpect while running the code inside the try-except block.
This should fix it:
try:
print("Version: " + s['scan'][host]['osmatch'][0]['name'] + "\n" + "Type: " + s['scan'][host]['osmatch'][0]['osclass'][0]['type'])
except KeyError:
print("An Error occured while scanning this host!\nNo extra info was collected!")
continue
In case you want to catch any possible exception that could occur (and yes custom ones included) then you should use the following code:
try:
<some critical code with possible exceptions to catch>
except Exception:
print("An exception occured")
Related
I am making a Reddit bot using PRAW and the code gives me the error that the exception is not iterable. Here is a simplification of my code:
try:
#something with praw that isn't relevant
except Exception as e: #this except error catches the APIexception, APIexpections in PRAW are a wide field of exceptions that dont't always have the same solution, so I scan the text for the error I'm looking for.
print(e)
if "keyword thats in the error" in e:
#fix the problem with the specific error
else:
print("Unkown APIExpection error")
This works fine for me, but when I run this code:
try:
#something
except Exception as e:
for character in e:
print(character)
#I also tried this
try:
#something
except Exception as e:
for character in str(e):
print(character)
#None of the above work but this is my actual code and what I need to do, anything that gets the above to work should work here too, I'm just letting you know this so that I don't get any other errors I have to ask another question for.
try:
#something
except Exception as e:
characterNum = 0
for character in e:
characterNum += 1
print(str(characterNum) + ": " + character)
It gives me a "TypeError: 'RedditAPIException' is not iterable", RedditAPIException can be ignore though as that's just the error I'm catching.
Convert the exception to string and then check in the if statement.
Change to => if "keyword thats in the error" in str(e):
In Visual Basic, there is an inherited base object that is effective for error debugging purposes. Is there an equivalent for the "Err" object in Python?
Dim Msg As String
' If an error occurs, construct an error message.
On Error Resume Next ' Defer error handling.
Err.Clear
Err.Raise(6) ' Generate an "Overflow" error.
' Check for error, then show message.
If Err.Number <> 0 Then
Msg = "Error # " & Str(Err.Number) & " was generated by " _
& Err.Source & ControlChars.CrLf & Err.Description
MsgBox(Msg, MsgBoxStyle.Information, "Error")
End If
For example:
def exec_sproc(sql,cnxn):
try:
cursor=cnxn.cursor()
cursor.execute(sql)
cnxn.commit()
cursor.close()
except(err):
print("error: {0}".format(err))
There is a suggestion to try
except Exception,e: print str(e)
I get an invalid syntax because 'e' is not defined or in the former example err shows as invalid syntax.
What is the base error object in Python? In most examples, user-defined custom errors are demonstrated rather than coding a return of the actual "Python" error. If I know what the error is, I prefer not to make it. Instead, show me what Python sees as the error. (anything other than invalid syntax would help)
I guess this is what you are looking for
def exec_sproc(sql,cnxn):
try:
cursor=cnxn.cursor()
cursor.execute(sql)
cnxn.commit()
cursor.close()
except Exception as err:
print("error: {0}".format(err))
for more on Python exceptions look here
I am a relative python newbie and I am getting confused with how to properly handle exceptions. Apologies for the dumb question.
In my main() I iterate through a list of dates and for each date I call a function, which downloads a csv file from a public web server. I want to properly catch exceptions for obvious reasons but especially because I do not know when the files of interest will be available for download. My program will execute as part of a cron job and will attempt to download these files every 3 hours if available.
What I want is to download the first file in the list of dates and if that results in a 404 then the program shouldn't proceed to the next file because the assumption is if the oldest date in the list is not available then none of the others that come after it will be available either.
I have the following python pseudo code. I have try/except blocks inside the function that attempts to download the files but if an exception occurred inside the function how do I properly handle it in the main() so I can make decisions whether to proceed to the next date or not. The reason why I created a function to perform the download is because I want to re-use that code later on in the same main() block for other file types.
def main():
...
...
# datelist is a list of date objects
for date in datelist:
download_file(date)
def download_file(date):
date_string = str(date.year) + str(date.strftime('%m')) + str(date.strftime('%d'))
request = HTTP_WEB_PREFIX+ date_string + FILE_SUFFIX
try:
response = urllib2.urlopen(request)
except urllib2.HTTPError, e:
print "HTTPError = " + str(e)
except urllib2.URLError, e:
print "URLError = " + str(e)
except httplib.HTTPException, e:
print "HTTPException = " + str(e)
except IOError:
print "IOError = " + str(e)
except Exception:
import traceback
print "Generic exception: " + traceback.format_exc()
else:
print "No problem downloading %s - continue..." % (response)
try:
with open(TMP_DOWNLOAD_DIRECTORY + response, 'wb') as f:
except IOError:
print "IOError = " + str(e)
else:
f.write(response.read())
f.close()
The key concept here is, if you can fix the problem, you should trap the exception; if you can't, it's the caller's problem to deal with. In this case, the downloader can't fix things if the file isn't there, so it should bubble up its exceptions to the caller; the caller should know to stop the loop if there's an exception.
So let's move all the exception handling out of the function into the loop, and fix it so it craps out if there's a failure downloading the file, as the spec requires:
for date in datelist:
date_string = str(date.year) +
str(date.strftime('%m')) +
str(date.strftime('%d'))
try:
download_file(date_string)
except:
e = sys.exc_info()[0]
print ( "Error downloading for date %s: %s" % (date_string, e) )
break
download_file should now, unless you want to put in retries or something like that, simply not trap the exceptions at all. Since you've decoded the date as you like in the caller, that code can come out of download_file as well, giving the much simpler
def download_file(date_string):
request = HTTP_WEB_PREFIX + date_string + FILE_SUFFIX
response = urllib2.urlopen(request)
print "No problem downloading %s - continue..." % (response)
with open(TMP_DOWNLOAD_DIRECTORY + response, 'wb') as f:
f.write(response.read())
f.close()
I would suggest that the print statement is superfluous, but that if you really want it, using logger is a more flexible way forward, as that will allow you to turn it on or off as you prefer later by changing a config file instead of the code.
From my understanding of your question... you should just insert code into the except blocks that you want to execute when you encounter the particular exception. You don't have to print out the encountered error, you can do whatever you feel is necessary when it is raised... provide a popup box with information/options or otherwise direct your program to the next step. Your else section should isolate that portion, so it will only execute if none of your exceptions are raised.
I have this simple try-except code:
self.tf.router.EchoProg(state=1)
try:
print "\tCheckTestFirmwareCommunication_SetPort: "
print self.tf.DUT.CheckTestFirmwareCommunication_SetPort()
except NoResponseException, e:
print "\tCheckTestFirmwareCommunication_SetPort: ", repr(e)
self.tf.router.EchoProg(state=0)
Output with Exception:
CheckTestFirmwareCommunication_SetPort:
CheckTestFirmwareCommunication_SetPort:
DD_NoResponseException()
Questions:
Can someone explain why i still see the print statements even if i get an exception?
Is it possible to ignore print statements if the try-except catch an exception?
It is the second print line that throws the exception:
print self.tf.DUT.CheckTestFirmwareCommunication_SetPort()
The first print line did not and was executed.
Python executes each statement within the try suite, and only when one throws an exception, is execution aborted and transfers to the except block. If you don't want the first print statement to execute when CheckTestFirmwareCommunication_SetPort throws an exception, call that method first:
self.tf.router.EchoProg(state=1)
try:
port = self.tf.DUT.CheckTestFirmwareCommunication_SetPort()
print "\tCheckTestFirmwareCommunication_SetPort: "
print port
except NoResponseException, e:
print "\tCheckTestFirmwareCommunication_SetPort: ", repr(e)
self.tf.router.EchoProg(state=0)
The first print statement is executed before the exception occurs, hence they are printed.
The exception here is raised by self.tf.DUT.CheckTestFirmwareCommunication_SetPort(). You can move the print statements below it, so that it'll be printed when the first line is successfully executed.
try:
print self.tf.DUT.CheckTestFirmwareCommunication_SetPort()
print "\tCheckTestFirmwareCommunication_SetPort: "
except NoResponseException, e:
print "\tCheckTestFirmwareCommunication_SetPort: ", repr(e)
The thing is that exception is raised by the line:
print self.tf.DUT.CheckTestFirmwareCommunication_SetPort()
so the line:
print "\tCheckTestFirmwareCommunication_SetPort: "
always will by executed.
to avoid that change your code to:
self.tf.router.EchoProg(state=1)
try:
port = self.tf.DUT.CheckTestFirmwareCommunication_SetPort()
except NoResponseException, e:
print "\tCheckTestFirmwareCommunication_SetPort: ", repr(e)
else:
print "\tCheckTestFirmwareCommunication_SetPort: ", port
self.tf.router.EchoProg(state=0)
Alright, I am fairly new to python and I am making a console witch will allow multiple features, one of those is to grab a page source and either print it on the page, or if they have another arg then name the file of that arg... The first arg would be the website url to grab the source from.
My imports are:
import os, urllib.request
This is my code:
def grab(command, args, argslist):
if args == "":
print("The " + command + " command wan't used correctly type help " + command + " for help...")
if args != "":
print("This may take a second...")
try:
argslistcheck = argslist[0]
if argslistcheck[0:7] != "http://":
argslist[0] = "http://" + argslist[0]
with urllib.request.urlopen(argslist[0]) as url:
source = url.read()
source = str(source, "utf-8")
except IndexError:
print("Couln't connect")
source = ""
try:
filesourcename = argslist[1] + ".txt"
filesourceopen = open(filesourcename, "w")
filesourceopen.write(source)
filesourceopen.close()
print("You can find the file save in " + os.getcwd() + " named " + argslist[1] + ".txt.")
except IndexError:
print(source)
Now while I will be ok with improving my code right now I'm focusing on the main point. Right now it works, I will improve the code later on, the only problem is that if the user inputs a fake website or a website page that doesn't exist then it returns lot's of errors. Yet if I change:
except IndexError:
print("Coulnd't connect")
source = ""
to just:
except:
print("Couldn't connect")
source = ""
Then it always says Couldn't connect...
Any help? I didn't put the rest of my code because I didn't think it would be useful, if you need it I can put it all.
The reason I titled this hide error is because it still works for some reason it just says that it was unable to connect, if the user types a second argument then it will save the source to the file he named.
try:
argslistcheck = argslist[0]
if argslistcheck[0:4] != "http://":
argslist[0] = "http://" + argslist[0]
with urllib.request.urlopen(argslist[0]) as url:
source = url.read()
source = str(source, "utf-8")
except IndexError:
print("Couln't connect")
source = ""
In that code block, the only thing that can raise an IndexError exception is the argslist[0]. This will happen if there is no element within that list. This is very likely not your problem.
Now if an invalid address is entered, urlopen will fail. But it will not raise an IndexError but rather an urllib.error.URLError or the more specialized urllib.error.HTTPError.
If you just write except IndexError you will only catch that error, but not the exception raised by the urlopen. If you want to catch those as well, you have to add another except case:
except IndexError:
print('Argument is missing')
except urllib.error.URLError:
print('Could not connect to the URL.')
The alternative is to just catch any exception by just not specifying any (this is what you did in your last code). Note that this is usually not recommended as it will hide any exceptions that occur which you might not have expected to ever happen; i.e. it will hide bugs. So if you know that there are only a few possible exceptions, just catch those and handle them explicitely.