6

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
  • Even if you manage to use su and pass the password using expect, the password needs to be plain text. Use sudo with NOPASSWD option. This will guarantee no one can steal the password from your script. Commented Nov 18, 2016 at 2:45

1 Answer 1

6

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).

Sign up to request clarification or add additional context in comments.

6 Comments

ya.. i know this. I was just trying to get it done without touching /etc/sudoers file, as i am not a root user to edit it. Thanks for the reply..!
@Rohith: If there are painful limitations like "I can't add anything to /etc/sudoers", then you should list them in the question so that people can avoid giving you the obvious sensible answer when it doesn't meet your requirements because of the limitations. (There's also a difference between "don't want to" and "do not have permission to" w.r.t "edit configuration files".) If you can't hack /etc/sudoers, you may need to explore expect in combination with su or something similarly devious. That's not a good solution; it might be a better solution, though.
If you don't have root privileges on that system, then what business do you have executing commands as another user?
@JonathanLeffler: Sure will try that.
@paddy: I am from Automation Team, i don't have root privileges on the PROD servers, SysAdmins do. They might not agree to edit /etc/sudoers, will check with them. Thanks..!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.