Running shell commands

As much as we like to criticize Microsoft’s command prompt some of the commands provided can be very useful. The Internet is littered with commands to get helpful information. To make them really useful we need to get output from these commands into Python. Thankfully this is easy if you use the correct command.

You will need to import the subprocess module. All the work in this module is done by popen constructor which allows a good deal of flexibility. However we do not need such fine grained control so we can just you the convenience function check_output().

Just need an example now. I’m going to use a command from Rob van der Woulde’s scripting pages to list all of the domain controllers using dsquery. Feel free to change this to something suitable. This returns each DC on a line as you can see from the output. I can get a more useful list simply with DCs.split()

import subprocess
  DCs = subprocess.check_output("dsquery server -o rdn",universal_newlines=True)
except subprocess.CalledProcessError:

This doesn’t just work for shell commands. Batch files can be ran in exactly the same way.


Leave a Reply

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

You are commenting using your 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