I want to switch to root user in bash script on RedHat by specifying the password in code rather than entering it.
Any help will be highly appreciated.
Thanks
It's not a good idea to store passwords in plain text in a script. You can use visudo
to edit the sudoers
file and allow users to run a command using sudo
without using a password.
The flexibility of sudo is widely under-estimated. This leads to very poor practices (like the sudo su -
canon-ball surgery method).
A much better method is to specificly allow the commands you intend to allow without use of a password:
phill = NOPASSWD: /bin/ls, /usr/bin/lprm
See for more examples: Shell script - Sudo-permissions lost over time
Let sudo read from stdin using the -S flag
sudo -S mkdir /mnt/somedir <<END
password here
END
This will let a user create a directory in /mnt owned by root
EDIT: this doesn't seem to work for the "su" command, yet I think this solution might be helpful