-2

I am new to python so forgive me if I have made a stupid mistake. I am trying to create a script in python3.8 to automate whether or not if a service is running and then take an action from there. So for example if the ssh service is running then I would like the script to send a command for stopping it. However my second statement in the if loop is not getting executed it just outputs the information from the command "service ssh status" and that is it. Can you please help with this?

#!/usr/bin/env python3.8

import os

ssh_status = os.system('service ssh status | grep running')

if ssh_status == 'running':
    os.system('service ssh stop') 
Mr. Discuss
  • 355
  • 1
  • 4
  • 13
Mo99709
  • 3
  • 1
  • Does this answer your question? [Running shell command and capturing the output](https://stackoverflow.com/questions/4760215/running-shell-command-and-capturing-the-output) – Tsyvarev Sep 06 '20 at 17:50

2 Answers2

1

os.system returns the exit code of the command. It will never return a string like "running", and therefore the if block will not run. Likely what you are looking for is the command subprocess.check_output().

Big Dumb
  • 120
  • 1
  • 7
0

Maybe the condition is not fulfilled, you can put else: print(ssh_status) to see if its different or just add a print before the if. The ssh_status maybe isn't 'running' so check what it is.

quamrana
  • 37,849
  • 12
  • 53
  • 71