uzla
uzla

Reputation: 525

How from Bash script (running as root or a superuser/sudo) to check sudoers file if a user can SUDO

I need to check from bash script (running with root priveledges) if another user is question can execute sudo as a dedicaite permission via 'username ALL=(ALL) NOPASSWD: ALL' in sudoers.

simple command run from a user in question easily returns 1 or 0:

sudo -n uptime 2>&1|grep 'load'|wc -l

but it always returns as empty if I change the user within script:

sudo -i -u username bash <<EOF
CAN_I_RUN_SUDO="$(sudo -n uptime 2>&1|grep 'load'|wc -l)"
echo "$CAN_I_RUN_SUDO"
whoami
EOF

Here is my full script:

sudo -i -u username bash <<EOF
whoami
CAN_I_RUN_SUDO="$(sudo -n uptime 2>&1|grep 'load'|wc -l)"
echo "$CAN_I_RUN_SUDO"
EOF
if [ ${CAN_I_RUN_SUDO} -gt 0 ]
then
    echo "I can run the Sudo command. No need to change sudoers"
else
    echo "I can't run the Sudo command. Added to Sudoers."
    sh -c "echo \"username ALL=(ALL) NOPASSWD: ALL\" >> /etc/sudoers"
fi

However, $CAN_I_RUN_SUDO is always returns empty (rather then 0 or 1) when I run it as a script. :-( so condition always fails.

I obviously missing something, but can't see it. Could you please help me?

Upvotes: 0

Views: 319

Answers (1)

zneak
zneak

Reputation: 138261

Instead of grepping for output, you may be able to just check the return value of sudo:

if sudo -i -u username sudo -n uptime 2>&1; then
    echo "I can run the Sudo command. No need to change sudoers"
else
    echo "I can't run the Sudo command. Added to Sudoers."
    echo "username ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers
fi

If I may, my unrelated security advice would be to avoid automatically adding users to the sudoers file.

Upvotes: 1

Related Questions