Python Forum
do sudo su - user in python script
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
do sudo su - user in python script
#1
I want to use sudo su - username inside a python script and also I need to assign password(I won't hardcode this instead this will come from user input from GUI) as well to it in script itself.

Manual steps:
1.usera$ sudo su - userb
2.usera$ "Entering password"
3.userb$ ./file.sh

I want to do the above steps inside a python script.

I have tried with the below but it switch's to userb and it will halt and wont run ./file.sh , when I exit it run's file.sh

#!/usr/bin/python
import os
os.system("echo password| sudo -S su - userb")

os.system("sudo -S su - userb")

os.system("file.sh")

Please help!
Thanks
Reply
#2
Use subprocess module.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
I have an old snippet in my notes:
import getpass
import subprocess as sp
COMMAND = ['ls']
mypass = getpass.getpass('This needs administrator privileges: ')

proc = sp.Popen(['sudo', '-kS'] + COMMAND, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
proc.stdin.write(mypass + '\n')
o, e = proc.communicate()

if proc.recurncode:
    print('command failed')
else:
    print('success')
print(o)
print(e)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Is there a *.bat DOS batch script to *.py Python Script converter? pstein 3 3,008 Jun-29-2023, 11:57 AM
Last Post: gologica
  Randomizer script to provide options based on user and priority cubangt 10 2,331 Mar-11-2022, 07:22 PM
Last Post: cubangt
  sudo apt Not Working Dacdiver 11 18,267 Nov-09-2021, 05:48 PM
Last Post: jefsummers
  sudo RyAn 2 1,495 Nov-09-2021, 12:43 PM
Last Post: DeaD_EyE
  Automatic user/password entry on prompt by bash script PBOX_XS4_2001 3 2,727 May-18-2021, 06:42 PM
Last Post: Skaperen
  cant use ping, sudo or other commands in remote shell script. throwaway34 7 3,534 May-17-2021, 11:29 AM
Last Post: throwaway34
  [SOLVED] Requiring help running an old Python script (non Python savvy user) Miletkir 13 5,308 Jan-16-2021, 10:20 PM
Last Post: Miletkir
  How to kill a bash script running as root from a python script? jc_lafleur 4 5,789 Jun-26-2020, 10:50 PM
Last Post: jc_lafleur
  crontab on RHEL7 not calling python script wrapped in shell script benthomson 1 2,248 May-28-2020, 05:27 PM
Last Post: micseydel
  Linux Script Sudo and "&" s3fac5 14 5,541 Aug-30-2019, 08:02 AM
Last Post: s3fac5

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020