su pass password to script

前端 未结 2 1664
慢半拍i
慢半拍i 2021-01-02 17:18

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\"`         


        
相关标签:
2条回答
  • 2021-01-02 17:42

    This solution work by using 'script' command from the 'bsdutiles' package that setup a pty (a terminal). The 'sleep' command is there to prevent sending the password before the 'su' command is ready to read it. The 'tail' command remove the "Password:" input line issued by 'su'.

     { sleep 1; echo rootpassword } | script -qc 'su -c "runmqsc QMGR < /home/rob/query_queue.txt" -m "mqm"' /dev/null | tail -n +2
    

    Beware that the rootpassword could be see in many ways (history, ps, /proc/, etc...). Start the command with a space to at least avoid history recording.

    0 讨论(0)
  • 2021-01-02 17:52

    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.

    0 讨论(0)
提交回复
热议问题