0

This question already has an answer here:

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?

marked as duplicate by Graeme, jimmij, Anthon, derobert, Braiam Jan 2 '15 at 16:40

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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.

  • 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 2 '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 2 '15 at 15:03
  • 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 2 '15 at 15:09
  • 1
    I would definitely recommend the NOPASSWD approach over putting the password in a file. – Graeme Jan 2 '15 at 15:10
  • 1
    @jim Instead of using su or sudo from a normal user. set setuid flag on the script. See 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 2 '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'"

Not the answer you're looking for? Browse other questions tagged or ask your own question.