6

I suspect su doesn't have any way to allow passing the password from the shell instead of being prompted for one, for security reasons (couldn't find anything in the MAN). Is this true?

ripper234
  • 31,763

2 Answers2

7

That's true, there is no way to have su(1) redirect its input from a place other than the tty. But there are libraries and programs to simulate a terminal for automated scripting, for example, Expect. Something similar to:

stty echo
log_user 0
set timeout 2
if [catch "spawn su root" reason] {
    send_user "Failed to spawn su: $reason\n"
    exit 1
}
expect "Password:"
send "$PASSWORD\r"
expect "\r\n"
#set timeout 5
log_user 1
expect {
    "# " {send_user "\nsu successful.\n"}
    timeout {send_user "\nsu timed out.\n"; exit 1}
    "incorrect" {send_user "\nsu failed.\n"; exit 1}
}
Arcege
  • 22,536
4

It's an incredibly bad idea, but if you really want to do it you can use sudo's NOPASSWD option:

In /etc/sudoers: 
# User privilege specification
johndoe  ALL=(ALL) NOPASSWD:ALL

Then user johndoe can do sudo su and wind up with a root prompt without ever being asked for a password.

I reiterate, though, that this is a REALLY BAD IDEA in most circumstances. Sudo, preferably /without/ the nopasswd flag is significantly safer.

  • Reread the question, he wants to do echo "password" | su or something like that - NOT get rid of the password, NOT use sudo (which is less secure than su...) – mathepic Feb 21 '11 at 17:36
  • 2
    @mathepic: If su is only being used for a specific command, giving the user sudo powers to run that command is a lot better security than storing the root password in a file in most use cases. – Gilles 'SO- stop being evil' Feb 21 '11 at 21:20
  • @Gilles: correct but a certain distribution has sort of changed the normal use of sudo. I do like sudo for what it was meant to be used as - but not as a replacement for su. – mathepic Feb 21 '11 at 21:37
  • @mathepic, what idiot told you that sudo is less secure than su ? More importantly, if you do echo password | su in some way or another the password would be part of the command line and easily visible in ps aux – Shadur-don't-feed-the-AI Jun 19 '18 at 09:36