Search code examples
linuxunixsudoers

How to execute 'iftop' without sudo


I have a script that runs iftop in text mode, cuts down the output to what I'm concerned in, and saves it to a text file along with the output of the date command (I am monitoring network usage on various interfaces over time). Only problem I'm having is I'm trying to run my script every 15 minutes via the crontab, and in order to run the iftop command I need sudo permissions. Does anyone know some way to change the permissions of iftop to make it so I don't need sudo permissions?

Alternatively if I can give the script the ability to run the command with sudo that would be fine by me as well. I tried adding the script to the sudoers file via sudo visudo and adding the line:

user ALL=(ALL) NOPASSWD: /home/user/network_usage.sh

but that didn't work...perhaps a result of executing from the crontab?

Thanks,

-Eric


Solution

  • You may use root's crontab to run the script. If instead of crontab -e you use sudo crontab -e you will edit root's crontab. Tasks specified in that file will run under root's account and privileges.

    Alternatively, you can set the setuid access flag for your script file. To do so first change the owner of the file to root, then enable setuid like this:

    sudo chown root /home/user/network_usage.sh
    sudo chmod +s-w /home/user/network_usage.sh
    

    The setuid bit makes an executable file run with the effective UID of its owner.

    Regardless of what approach you take, be very careful.

    • Make your script owned by root and don't let any other user write to it, otherwise it could ease a privilege escalation.
    • Be aware of the side effects of your setuid programs. If the script has setuid and may create or modify files, it might be used by someone else to modify or create files they aren't supposed to. Always check the manual before giving setuid to any program you haven't written.