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 try: DCs = subprocess.check_output("dsquery server -o rdn",universal_newlines=True) print(DCs) except subprocess.CalledProcessError: pass
This doesn’t just work for shell commands. Batch files can be ran in exactly the same way.