1

I am on a raspberry 4B with headless raspbian v10 (buster). I am trying to get the response from the sudo systemctl status hostapd command using subprocess.check_output. Simply running sudo systemctl status hostapd in the raspi terminal works just fine and I get what I want to see:

  sudo systemctl status hostapd
● hostapd.service - Advanced IEEE 802.11 AP and IEEE 802.1X/WPA/WPA2/EAP Authenticator
   Loaded: loaded (/lib/systemd/system/hostapd.service; enabled; vendor preset: enabled)
   Active: inactive (dead)

However, when I run the code:
response = subprocess.check_output(['sudo systemctl status hostapd'], shell=True).decode('utf-8')
I get the error message:
Error: Command 'systemctl status hostapd.service' returned non-zero exit status 3.

Adding stderr=subprocess.STDOUT to the argument list does not provide more information.

Can someone tell me why the error is raised and what it means?

Slev1n
  • 25
  • 7

1 Answers1

0

The correct use of check_output is as follows:

subprocess.check_output(['systemctl','status','hostapd']).decode('utf-8')

Each argument in the command is part of an array and not the whole command.

Also, I suggest removing "sudo" from the command, and just run your python script with sudo.

James Gyps
  • 64
  • 4
  • 1
    `shell=True` is wrong here. See also [Actual meaning of `shell=True` in subprocess](https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess) – tripleee Oct 05 '22 at 11:09
  • What is the difference between using sudo within the command compared to calling the parent-python script with sudo? – Slev1n Oct 12 '22 at 12:56
  • 1
    When running sudo from within a script that runs under normal user - it will not have the permissions to do so. when using sudo to run the script the shell will ask for a password and then will run it with root permissions – James Gyps Oct 12 '22 at 13:32