Search code examples
linuxbashshellunixsudo

Provide password for running a script inside another script as different user


Imagine you run script as user A: sudo -u A ./script.sh Inside that script.sh we have a line that calls another script script2.sh with a different user B: sudo -u B ./script2.sh. Now I get prompted to enter a password for user B. Is there any way to provide that password uppon call?

P.S. I know all the security breaches it can create. Please do not mention me that.


Solution

  • Yes you have option for that. But that password you have to provide at the time of executing the script or hard coded it in the script itself. Try with the below example:-

    echo 'passwordofB' | sudo -u B -S ./script2.sh
    

    Also you can do it like:-

     sudo -u A ./script.sh passwordofB #as a command line parameter
    

    now inside script.sh:-

    echo $1 | sudo -u B -S ./script2.sh
    

    You are executing another script sudo -u B ./script2.sh from script ./script.sh right? So change that line with echo $1 | sudo -u B -S ./script2.sh and run your first script as sudo -u A ./script.sh passwordofB where passwordofB is the password for user 'B'