Created
March 4, 2023 21:17
-
-
Save AndreyDodonov-EH/2c7b455c8987dbfb63437d4c8a77d5be to your computer and use it in GitHub Desktop.
Calling shell command from python with sudo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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