Book Image

Mastering Python for Networking and Security

By : José Ortega
Book Image

Mastering Python for Networking and Security

By: José Ortega

Overview of this book

It’s becoming more and more apparent that security is a critical aspect of IT infrastructure. A data breach is a major security incident, usually carried out by just hacking a simple network line. Increasing your network’s security helps step up your defenses against cyber attacks. Meanwhile, Python is being used for increasingly advanced tasks, with the latest update introducing many new packages. This book focuses on leveraging these updated packages to build a secure network with the help of Python scripting. This book covers topics from building a network to the different procedures you need to follow to secure it. You’ll first be introduced to different packages and libraries, before moving on to different ways to build a network with the help of Python scripting. Later, you will learn how to check a network’s vulnerability using Python security scripting, and understand how to check vulnerabilities in your network. As you progress through the chapters, you will also learn how to achieve endpoint protection by leveraging Python packages along with writing forensic scripts. By the end of this book, you will be able to get the most out of the Python language to build secure and robust networks that are resilient to attacks.
Table of Contents (16 chapters)

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.