su pass password to script

RobM picture RobM · Oct 3, 2013 · Viewed 33k times · Source

I am trying to write a script that will run the following commands:

sudo su
runmqsc_result=`su -c "runmqsc QMGR < /home/rob/query_queue.txt" -m "mqm"`

My issue however, is that these commands are run as part of a shell script, by user that is in the sudoers file. However, obviously sudo su asks for the password of the user running it.

What I need to do is to pass the password to sudo su so that the script will run automatically. How can I do this?

p.s: I can't change the permissions for running "runmqsc"...it HAS to be run as user mqm which needs to be switched to from the root user.

Answer

n.st picture n.st · Oct 3, 2013

From man sudo:

-S    The -S (stdin) option causes sudo to read the password from the standard
      input instead of the terminal device.  The password must be followed by a
      newline character.

So, while it defies all security principles, echo 'password' | sudo -S su [...] should work.


Alternatively, you could make your script writeable only by root and add the following to /etc/sudoers to allow the user johndoe to run it with root priviledges without having to enter his password:

johndoe ALL = NOPASSWD: /full/path/to/your/script

The part writeable only by root is important to prevent johndoe from modifying the script and executing arbitrary commands as root.