0

Is it possible to write a script that run su or sudo command without typing password?. I googled and its said that su doesn't read password from buffer. So is there any solution?

Braiam
  • 35,991
linerd
  • 167
  • 2
  • 9

2 Answers2

2

Two approaches as far as I can tell:

Good idea

When setting up sudo for a specific user or group, you can use the ALL=NOPASSWD option in the /etc/sudoers file.

Some pointers on how to do that:

Bad idea

You can use sudo with the -S option to give the password through standard input instead of the terminal device. For example, you can write down the password in a file, and then do cat myPass.txt | sudo -S your_command.

jimm-cl
  • 1,128
  • So, having your user use passwordless sudo is "best"? Or barring that, Assuming that keeping a password in plain text would be bad, you'll need a user who can use passwordless sudo, then you'll have to log in as that user? Any easy way to do that without it being insecure? – Xen2050 Jan 02 '15 at 14:56
  • Setting it in the sudoers list would be the secure way, in my opinion. Having passwords in plain text out there is always a bad idea, but I just wanted to let the OP know that it can be done, whether it's a good or a bad idea... – jimm-cl Jan 02 '15 at 15:03
  • Also, I think the sudoers list can be setup to allow one specific command to be run. Take a look at this and this. – jimm-cl Jan 02 '15 at 15:06
  • 1
    Specific command "nopwd" sudo sounds the best. Just trying to log in as another user, without keeping that user's pw in plain text is the same problem as not keeping your own (sudo) password in plain text. Unless logging in as the other user with ssh keys or something over complicated – Xen2050 Jan 02 '15 at 15:09
  • 1
    I would definitely recommend the NOPASSWD approach over putting the password in a file. – Graeme Jan 02 '15 at 15:10
  • I have edited my answer to make it clear that using passwords in plain text files is not a good idea :) thanks for your comments! – jimm-cl Jan 02 '15 at 15:14
  • 1
    @jim Instead of using su or sudo from a normal user. set setuid flag on the script. See http://en.wikipedia.org/wiki/Setuid . So after you've created the script, change the owner to root, for example chown root:buadmins myscript , and give the appropriate execute permissions, for example chmod 755. Then set uid, for example chmod ug+s myscript Then when the user runs the script it will run as root. – PaperMonkey Jan 02 '15 at 17:06
0

You can use expect for this:

#!/usr/bin/expect
set password "mypassword"
spawn sudo mkdir -v newdir
expect "Password:"
send -- "$password\n"
expect "mkdir: created directory 'newdir'"