I need to write a python script, for example I need to run the command "systemctl is-enabled autofs" and if the output the command is "Failed to get unit file state for autofs.service: No such file or directory" then the script should print "no service installed" and if the output is "enabled" then the script should run "systemctl --now disable autofs". I have tried using os and subprocess module but could not make it. Any help would be appreciated.
From the subprocess Python documentation:
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False) Run command with arguments and return its output as a byte string.
If the return code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and any output in the output attribute.
You can check the output of your initial command. Based on that, you either print
no service installed or run
systemctl --now disable autofs.
import subprocess try: subprocess.check_output(["systemctl", "is-enabled", "autofs"], stderr=subprocess.DEVNULL) except subprocess.CalledProcessError as e: print('no service installed') else: subprocess.run(["systemctl --now disable autofs"])