Linux shell script to switch user and prompt required information background to script

Linux shell script to switch user and prompt required information background to script

I need a sample linux shell script for scenario below:

During interactive session:

su user1
Password: <Type password>

What I will do is I will save the password in some file (e.g.: ~/pwd.txt). I need a shell script such that when we execute that script, the password for the target user will be read from the file and automatically passed to su and I will then switch to the target user. It isn't necessary to show the prompt, it would be fine if everything gets processed in the background and I just see the switch to the new user directly).

Please help!

Thanks!

答案1

It's not secured to store your raw password in a file ; but at least this will be an answer for your question.

Using NOPASSWD in sudoers

Add the below entry to your sudoers :

<your_user> ALL=NOPASSWD: /bin/su - user1
#Then simply run
sudo -S su - user1

Without sudoers : Usefull for non interactive shells

su - user1 -c ""  < ~/pwd.txt &>/dev/null

< ~/pwd.txt Redirect your password stored in ~/pwd.txt to su command.

&>/dev/null Redirect both stdout and sterr to >/dev/null.

## BETTER ## :

You can use gpg tool to encrypt your password :

    # Encrypt your password with choosing a passphrase :
    gpg -c ~/pwd.txt 
    # Remove your raw password file :
    rm -f ~/pwd.txt.gpg

Now when trying to su use the above to decrypt your password :

su - user1 -c ""  <<< "$(gpg -q -d ~/pwd.txt.gpg 2>/dev/null)" &>/dev/null

相关内容