Bash – Switch user in a shell script without entering the password

bashscriptingshell-script

I'm running a shell script using terminal from userA. In the middle of this shell script, I switch to userB user using su, but this asks me for the password of userB and I have to manually enter the password through terminal. I'm asking if there is a way so that I can enter the password automatically without having me to stay beside the machine to manually enter the password? As there is a loop in this script and I don't want to keep staying all the time looking at the terminal to enter the password of userB when it asks me. Or if there is a way I can put the password in my shellscript so that the terminal won't wait for me to manually enter it? Could anyone please advise how this could be done?

Best Answer

sudo also allows NOPASSWD on specific entries in the /etc/sudoers configuration, if you can get to that. Like:

userA ALL = (userB) NOPASSWD: ALL

This will give userA full access to userB without password. Should probably only be used if userA can be trusted to lock his screen whenever leaving it …

Alternatively, you can give userA access to only certain scripts. For instance:

userA ALL = (userB) NOPASSWD: /home/userB/scripts-for-userA/

This lets userA run any command in the directory /home/userB/scripts-for-userA/ as userB. It's still only as secure as those commands are, though.

Related Question