Assigning Static IP with Python

Practical Python projects are the best python projects right? I came up with a simple script that makes a common work task much faster and easier.

In the course of my daily activities as a VoIP technician I am frequently visiting different customer sites each with a server that has a unique static IP address. In order to access these sites from the network I need to make sure I find a switch port with the correct vlan and assign my laptops Ethernet port to a static IP in the same range as the server.

With over 300 sites 30-40 of which have IP based pbx systems it’s not practical to remember all these IP addresses. I wanted a simple way to type a short command into a command prompt and have my devices static IP changed easily. Much like the way DNS allows us to type in a domain name to access a web site without having to actually know the server’s IP address.

I began by doing some research on how I could modify my static IP in Python by importing the subprocess library I was able to achieve this. I then set about writing a function that takes user input, strips the capitalization and assigns an IP address based on the user input. I did this with a series of conditional elif statements. I’ll include a link to a redacted version of the script on GitHub for anyone interested in reading the code. But the pseudo code goes something like:

If user_input = “site1”:

    Set static IP x.x.x.1 subnet x.x.x.x gateway x.x.x.1

Elif user_input = “site2”:

   Set static IP x.x.x.2 subnet x.x.x.x gateway x.x.x.1

Etc etc….

While functional, this code is not considered very “pythonic” as it has a lot of unnecessary “hard coded” if statements that can be abstracted away with a for loop and a dictionary. This will bring the overall lines of code way down and increase the speed and efficiency the script executes. While the gains in speed are basically imperceptible with a data set this size it is still always a good idea to follow best practices. So I decided to make a version 2 of this script that takes user input and loops over a dictionary.

Comments

One response to “Assigning Static IP with Python”

  1. […] the code and trying to have it reusable as possible. For anyone that didn’t read my first post I wanted a simple way to change my work laptops Ethernet static IP address. I frequently visit many […]

Leave a Reply

Your email address will not be published. Required fields are marked *