How to Switch to Different User Inside a Shell Script and Execute Some Command with the New User?
I Am Currently Logged into "Server1" with User "User1", and I Have Placed My Bash Script Here. This Script Has to Switch to Different User "User2" on the Same...
I am currently logged into "SERVER1" with user "USER1", and i have placed my bash script here. This script has to switch to different user "USER2" on the same server "SERVER1" and execute some commands with the new switched user.
Note: USER1 is not a root user, so i need to specify the USER2 password inside the script, but in a encrypted format.
Please help me in achieving this..!
#!/bin/bash
command1
command2
.
.
...
echo "PASSWORD" | su USER2 << EOF
command1
command2
.
.
...
Please note, i don't want to change any configuration files here to achieve this.
1 Answer
It's not a good idea to store passwords in scripts, or attempt to stream them into su. The better approach is to use sudo.
Since you're allowing USER1 to act as USER2 without a password, you can set up /etc/sudoers like this:
USER1 localhost=(USER2) NOPASSWD: ALL
Then you can invoke sudo as USER1 as follows:
sudo -u USER2 bash
If you want to lock it down a bit more, you can specify a script that the user is allowed to execute. The line in /etc/sudoers might look like:
USER1 localhost=(USER2) NOPASSWD: /home/USER1/setup.sh
And you would call:
sudo -u USER2 /home/USER1/setup.sh
Note in this last example, I think that USER2 would need to have an actual shell configured in /etc/passwd (i.e. NOT /bin/false).