Skip to content

Instantly share code, notes, and snippets.

@aeroaks
Last active September 10, 2023 15:28
Show Gist options
  • Save aeroaks/f6150bd0add14bdbc244 to your computer and use it in GitHub Desktop.
Save aeroaks/f6150bd0add14bdbc244 to your computer and use it in GitHub Desktop.
Run Sudo command using Python
import subprocess
# run command using Popen and provide password using communicate.
# password requires byte format.
# sudo -S brings password request to PIPE
proc = subprocess.Popen(['sudo', '-S', 'nano', 'test.txt'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate(input=b'password\n')
# Print output and errors
print(proc)
@Rajan-sust
Copy link

Rajan-sust commented Sep 10, 2023

from subprocess import Popen, PIPE, STDOUT

password = 'xxxxxx'
cmd = f'echo {password} | sudo -S nano test.txt'

with Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, text=True) as process:
    # Wait for the command to complete and collect its output
    stdout, stderr = process.communicate()
    # Optionally, you can check the exit code and print the output
    if process.returncode == 0:
        print('Command succeeded:')
        print(stdout)
    else:
        print('Command failed:')
        print(stderr)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment