In the last article titled "Networker’s View of Windows CMD," we learned about useful CMD commands which can help us troubleshoot/manage networking configuration of our computer. In this article, we'll see how to use Python script to automate the execution of these commands. As some of you may already know Python is extremely powerful but at the same time is a fairly easy to read scripting language. In order to run Python scripts, you have to install Python on your computer. To find out more about different versions of Python and to download installation files please visit Now that we've covered the basic requirements we can continue.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 and run it from CMD by typing python Figure 2. shows the results of the 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


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 bytes object's decode() method. Figure 4. shows the result of running our script.


Figure 4. Result of 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.

Start learning with Cybrary

Create a free account

Related Posts

All Blogs