Skip to content

Instantly share code, notes, and snippets.

@AndreyDodonov-EH
Created March 4, 2023 21:17
Show Gist options
  • Select an option

  • Save AndreyDodonov-EH/2c7b455c8987dbfb63437d4c8a77d5be to your computer and use it in GitHub Desktop.

Select an option

Save AndreyDodonov-EH/2c7b455c8987dbfb63437d4c8a77d5be to your computer and use it in GitHub Desktop.
Calling shell command from python with sudo
import logging
import subprocess
def sudo_exec(pwd: str, cmd: list[str]):
"""Executes given shell command with sudo.
:param pwd: password for sudo
:param cmd: command to execute as a sudo as an array, e.g. ['echo','hi']
:return: touple where first entry is a return code and second is output
"""
try:
logging.getLogger().setLevel(logging.INFO)
logging.info(' '.join(cmd))
ps = subprocess.Popen(('echo', pwd), stdout=subprocess.PIPE)
sudo_cmd = ['sudo', '-S'] + cmd
res = subprocess.check_output(sudo_cmd, stdin=ps.stdout)
ps.wait()
except subprocess.CalledProcessError as e:
logging.error(e.output)
return e.returncode, e.output
logging.info(res)
return ps.returncode, res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment