2

I am creating a script. I want this script perform next task: Log in as a root user. (I am trying to use one line) How to create script which will enter password automatically?

#echo "Hello Admin"
#su root@admin

enter image description here

enter image description here

I just want to bash script and don't enter password. Why does it ask me to enter password?

2 Answers2

0

If your goal is to su without password, I recommend using sudo su. Allow the user to use su without password in /etc/sudoers with

[username] ALL=(ALL) NOPASSWD: /bin/su

or

[username] ALL=(ALL) NOPASSWD: ALL

since the user can already do whatever he/she wants with root access. Benefit over passing cleartext password from script is that the root password isn't leaked out. Remember that the password may be readable after deleting the script.

EDIT:Sollution below doesn't work after all, su treats stdin as a command and exits after it. echo 'passwd'|sudo -S [command] works for most commands other than su but if you use it, note that stdin still has the password if sudo didn't ask for it because timestamp was still fresh. You can use sudo -k first to force password query.sudo -k && echo 'passwd'|sudo -S [cmd]. Still, better use NOPASSWD in /etc/sudoers.

EDIT: Also, instead of using NOPASSWD:, you can also use sudo -S to read the sudo password from stdin and use something like echo [password]|sudo -S su. sudo takes the user password and needs permission to run /bin/su or ALL like above. Like all sudo commands, password expected is the user's password, not root's

  • Well I used this method for the other user. But for this user I try to create script. –  Jun 01 '15 at 23:02
  • @user3043926 will the edit work for you? – WhimsicalWombat Jun 01 '15 at 23:06
  • ** Do you have an example?** –  Jun 01 '15 at 23:09
  • @user3043926 [username] ALL=(ALL) /bin/su in /etc/sudoers, echo [user password] | sudo -S su in script to switch to root. – WhimsicalWombat Jun 01 '15 at 23:19
  • **In the the etc/sudoers I have user borya ALL=(ALL) /bin/su. In the script I typed echo admin | sudo -S su . Now I logged in under the user borya and run the script. It shows me admin: command not found. –  Jun 02 '15 at 00:00
  • @user3043926 huh. subshell indeed treats stdin as command and exists after it. I can't figure out out to prevent that. I'll edit the answer to remove that. Sorry, should've tested it, assumed it worked since sudo -S [command] works and NOPASSWD: sudo su works. – WhimsicalWombat Jun 02 '15 at 02:58
0

It's not possible! Not for that command, but you can create a sudo user with ALL ALL: NO Password, search online on how to cerate a sudo user to run sudo commands without password.