pythonlinuxprivilegespolkit

Python - Use pkexec only one time in subprocess.run one time for multiple commands


I need to use two commands requiring privileges and for this reason I'm using pkexec. My piece of code is:

def __init__(self):
    self.__binary = "/usr/bin/docker"
    self.docker_start = subprocess.run(["pkexec", "systemctl", "start", "docker"], capture_output=True)
    self.pulled_containers = subprocess.run(["pkexec", self.__binary, "ps", "-a", "--format", "'{{.Image}}'"], capture_output=True)

I would like to avoid that the request of password is prompting two times, and I would like to have only one time for both of the commands. Usually I can use pkexec bash -c "command1; command2" and I tried to use:

self.pulled_containers = subprocess.run(["pkexec", "bash", "-c", "\"systemctl start docker; docker ps -a --format '{{.Image}}'\""], capture_output=True)

but it seems to not work. Is there a good way to run two commands by subprocess by using pkexec (and the password prompt) only one time?


Solution

  • You should not put double quotes (") for -c :

    #!/usr/bin/env bash
    
    python << EOF
    import subprocess
    print(subprocess.run(["pkexec", "bash", "-c", "date; sleep 1; date"], capture_output=True).stdout.decode())
    EOF