How can password be passed in a shell script using su(without sudo and except)?. I have tried echo "password" | su root -c .But it didnt work.
Asked
Active
Viewed 9,160 times
3
-
**Are you crazy?** Never, ever put the root password in a script (or use it in a command in a way it is captured in the `history` file). That is just asking for trouble. The proper way to `su` or `sudo` to root without a password is to make yourself a member of the `wheel` group, then `su` to root (give password), edit sudo config `visudo` and add the following line at the end `%wheel ALL = (ALL) NOPASSWD:ALL`. Then you and all members of the `wheel` group can `su` or `sudo` without being prompted for a password. – David C. Rankin Jun 29 '15 at 22:39
-
1Why did this get downvotes? Aside from making the tactical error of suggesting a solution that would expose the root password, this is a good question about how to pipe passwords to the `su` utility. – jayhendren Sep 13 '18 at 23:35
-
A [near-identical question on AskUbuntu](https://askubuntu.com/questions/354838/is-there-a-single-line-command-to-do-su) got 12 upvotes and two decent, upvoted answers. – jayhendren Sep 13 '18 at 23:38
-
Also https://stackoverflow.com/questions/233217/how-to-pass-the-password-to-su-sudo-ssh-without-overriding-the-tty is a near-duplicate, but none of the upvoted answers address passing passwords to `su` specifically (only `sudo` and `ssh`). – jayhendren Sep 13 '18 at 23:47
1 Answers
5
The best way of doing this is with sudo
, but since you don't want the best solution, you can you can use script
instead:
{ sleep 3; echo "yourpassword"; } | script -q -c 'su -c whoami' /dev/null
This will print root
, the output of whoami
.
Please make sure to try this command verbatim (with password replaced) before trying to adapt it to run your own commands, since adapting it is difficult and error prone.

that other guy
- 116,971
- 11
- 170
- 194