Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Python for Networking and Security

You're reading from   Mastering Python for Networking and Security Leverage Python scripts and libraries to overcome networking and security issues

Arrow left icon
Product type Paperback
Published in Sep 2018
Publisher Packt
ISBN-13 9781788992510
Length 426 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
José Manuel Ortega José Manuel Ortega
Author Profile Icon José Manuel Ortega
José Manuel Ortega
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Preface 1. Working with Python Scripting 2. System Programming Packages FREE CHAPTER 3. Socket Programming 4. HTTP Programming 5. Analyzing Network Traffic 6. Gathering Information from Servers 7. Interacting with FTP, SSH, and SNMP Servers 8. Working with Nmap Scanners 9. Connecting with the Metasploit Framework 10. Interacting with the Vulnerabilities Scanner 11. Identifying Server Vulnerabilities in Web Applications 12. Extracting Geolocation and Metadata from Documents, Images, and Browsers 13. Cryptography and Steganography 14. Assessments 15. Other Books You May Enjoy

Python functions and managing exceptions

In this section, we will review Python functions and managing exceptions. We will see some examples for declaring and using both in our script code. We'll also review the main exceptions we can find in Python for include in our scripts.

Python functions

In Python, functions provide organized blocks of reusable code. Typically, this allows a programmer to write a block of code to perform a single, related action. While Python provides many built-in functions, a programmer can create user-defined functions. In addition to helping us to program and debug by dividing the program into parts, the functions also allow us to reuse code.

Python functions are defined using the def keyword with the function name, followed by the function parameters. The body of the function consists of Python statements that are to be executed. At the end of the function, you can choose to return a value to the function caller, or by default, it will return the None object if you do not specify a return value.

For example, we can define a function that, given a sequence of numbers and an item passed by a parameter, returns True if the element is within the sequence and False otherwise:

>>> def contains(sequence,item):
for element in sequence:
if element == item:
return True
return False
>>> print contains([100,200,300,400],200) True >>> print contains([100,200,300,400],300) True >>> print contains([100,200,300,400],350) False

Managing exceptions

Exceptions are errors detected by Python during program execution. When the interpreter encounters an exceptional situation, such as trying to divide a number by 0 or trying to access a file that does not exist, it generates or throws an exception, informing the user that there is a problem.

If the exception is not captured, the execution flow is interrupted and the information associated with the exception in the console is displayed so that the programmer can solve the problem.

Let's see a small program that would throw an exception when trying to divide 1 by 0. If we execute it, we will get the following error message:

The first thing that is shown is the traceback, which consists of a list of the calls that caused the exception. As we see in the stack trace, the error was caused by the call to calculate () of line 7, which in turn calls division (1, 0) on line 5, and ultimately the execution of the a/b sentence of division line 2.

The Python language provides an exception-handling capability to do just this. We use try/except statements to provide exception-handling. Now, the program tries to execute the division by zero. When the error occurs, our exception-handling catches the error and prints a message to the screen:

In the following example, we try to create a file-type f object. If the file is not passed as a parameter, an exception of the IOError type is thrown, which we capture thanks to our try-except:

Some of the exceptions available by default are listed here (the class from which they are derived is in parentheses):

  • BaseException: Class from which all exceptions inherit.
  • Exception (BaseException): Super class of all exceptions that are not output.
  • ZeroDivisionError (ArithmeticError): Launched when the second argument of a division or module operation was 0.
  • EnvironmentError (StandardError): Parent class of errors related to input/output.
  • IOError (EnvironmentError): Error in an input/output operation.
  • OSError (EnvironmentError): Error in a system call.
  • ImportError (StandardError): The module or the module element that you wanted to import was not found.
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at ₹800/month. Cancel anytime