Python for Network Engineers: Basic Scripting

Hello friends and welcome to my blog series guide on network programming. Previously, I shared a short overview of how Python is useful for network engineers and Python data types. Today, we will explore Python scripting and make short scripts of our own. This post assumes you already have Python in your operating system and is familiar with IDLE (Python IDE that comes with Python installation).

Hello World

First we will learn how to output ‘hello world’. In your command line, use the print method below and hit enter (screenshot using IDLE). print() is a Python method to output something.

print('hello world')

User Input

Next, we will ask the user to input their name, save it into a variable. We will then output the name back to the user. This time, we are using the method input().

my_name = input('Please enter your name: ')
#asks the user to input their name and stores it into the variable my_name

Basic Ping Script

Now we will write a multi-line script and save it into a python file. This script will ask the user to input an IP address. The script then pings that IP address 4 times and displays the result to the user. Don’t worry too much about the methods used to run the ping test. The goal of this is to familiarize yourself with how to create a Python script.

Using IDLE, create a new file (File > New File) and write the code snippet below. Press F5 so IDLE will save this file in your local drive. Notice the file extension (.py) – this is your first python script file.

import os

ipaddr = input('Enter the IP address:')
stream = os.popen('ping {}'.format(ipaddr))
output = stream.read()

if '0 received' in output:
    print('IP unreachable')
else:
    print('IP reachable')

print(output)

After saving, IDLE automatically runs the script for you to test.

You can also run this script from your command prompt (Windows) or Terminal (Mac OS). Remember you saved your python script file? Make sure you are in the same folder as your python file. You can use ‘cd’ to change directory like how I did in below screenshot.

If you’ve reached this far and successfully created and ran your python script, congratulate yourself. In the coming days, we will explore Python strings and learn how to handle and manipulate them for all our needs. See you again soon!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s