Search code examples
bashshellunixsudo

Safer way of performing SUDO from shell script


hi i am performing SUDO from shell script and taking instruction from hereDOC. But i want to know i am doing it correct or in safer way or not . It sometime locks my account(when i tried to change path ) i don't know why.

#!/bin/bash
# set the STRING variable
path=/u/siebel/abcdef/sie/sieb/
echo abcd | sudo -S /usr/bin/su - abcdef << EOF
crontab -l > cronbackup1.txt
#ls -lrt
cd "$path"
ls -lrt
EOF

Above script just locked my account . But when i executed it without cd it worked fine . This time it prompts me wrong password 3 times on its own as i do ./testing.sh and get locked can some one explain me why it runs 3 times there is no loop in script though ?

This what i get after setting cd "$path".

Password: Sorry, try again.
Password: Sorry, try again.
Password: Sorry, try again.
sudo: 3 incorrect password attempts

For same password crontab worked fine.


Solution

  • When you do:

    somecmd | cmd << EOF
    ...
    EOF
    

    The stdin of cmd will be the content of the here-document, and whatever is coming from the pipeline will not be read. The stdout of somecmd will be closed without reading anything from it.

    So what happens in your example is that sudo tries to read the password from the here-document, instead of the echo that you tried to pipe to it.

    In other words, you cannot supply the password to sudo and at the same time pass a here-document to its shell.

    What you can do is separate these two actions, by taking advantage of the timeout option of sudo. That is, once you successfully used sudo, it remembers your authenticated state for a while, and subsequent calls to sudo will not ask for the password again.

    echo abcd | sudo -S true
    sudo /usr/bin/su - abcdef << EOF
    crontab -l > cronbackup1.txt
    #ls -lrt
    cd "$path"
    ls -lrt
    EOF
    

    But I urge you not to do this. Passing your password in clear text in the shell, and especially in a script is very poor security. It would be better to create a dedicated script to perform the action you need with the other user account and configure sudoers appropriately.