November 7, 2016
Using Python to Automate Network Information Gathering
November 7, 2016
By looking at Figure 1., we can see that 10 lines of code (including comments and empty lines) were enough for us to write a Python script that executes ipconfig /all command and displays the result.
Figure 1. Python script which runs the ipconfig /all command in MS Windows CMD
A Python module that enables us to run external commands is called subprocess module. The subprocess module allows us to spawn new processes, connect to their input/output/error pipes (via PIPE function) and obtain their return codes. In order to test our script from Figure 1., we have to save it to a file with py extension. Let's call our script ipconfig.py and run it from CMD by typing python ipconfig.py. Figure 2. shows the results of the ipconfig.py script.
Figure 2. Executing Python script which runs the ipconfig /all command
For our second example let's take a look at how would we run the ping command from a Python script. Figure 3. shows the content of our new script called ping.py.
Figure 3. Python script which runs the ping command
Since we are using Python 3.5 in our demonstration we need to explicitly convert bytes object into str object since Python 3.5 can't be certain what character encoding is being used. That's why we are using the
decode() method. Figure 4. shows the result of running our ping.py script.
Figure 4. Result of ping.py script
As you can see by now many everyday tasks can be automated using Python, thus making your life easy. I hope you've found this article useful and informative. Install Python and give it a try.