Python is a wonderful language for automation, and it works well on Linux, or even on Windows.

Running an external command on Linux can use something like this:

def run_cmd(run_string):
  logger.debug('run_cmd: ' + run_string)
  return subprocess.check_output(run_string, shell=True,

This will print some debugging output, run the command passed in, and return the output from the command as a string. It will throw an exception if anything went wrong.

Now, you can run this from your main function as:

shell_output = run_cmd("service ssh stop")

What is more interesting about using an internal function to run a command, instead of calling it directly from the code, is that it's now easier to add mocking capabilities to the command for your unit tests. Being able to mock out all of these external calls in an easy manner really improves your unit testing, isolates concerns, and makes it run faster. I'll write about that another time.

This code is also meant to work with Python 2.7. The subprocess functions are a little different in Python 3.5