Link to home
Start Free TrialLog in
Avatar of lkrubner
lkrubnerFlag for United States of America

asked on

can the "lsof" command be run by non-root users?

I've got a cron script, written in PHP, that does this call:

lsof | greg vsftpd

and saves the output in a text file.

When I ssh to the server and login as root and call this script myself, everything works fine. That is, if I do this:

/usr/local/bin/contentingester/save_ftp_processes.php

I get the full list of files opened by vsftpd, saved to a text file, just like I would expect.

When the cron calls this script, it creates the file, like it should, but the file is empty.

Why is that? Is lsof limited to root users or something?

This is the PHP script that I'm calling as a cron, every 5 minutes:

$stringListingAllProcesses = shell_exec("lsof | grep vsftpd");
$filename = "/usr/local/bin/bluesugar_content_ingester/ftp_processes_" . time();
file_put_contents($filename, $stringListingAllProcesses);
chmod($filename, 0777);

This should cause files to be created in the folder "bluesugar_content_ingester". And the files are created. When I'm logged in as root, they are full of the output of lsof command. But when the script is called as a cron, the file is created, yet it is blank. It's as if there is no output.

Why would that be?

Avatar of David Beveridge
David Beveridge
Flag of Australia image

lsof on my system is in the /usr/sbin folder whichi is only accessible by root.



why not put it on roots crontab
You can run it as wwwrun, but it will only list the files which are used by processes owned by the wwwrun user, not all files like it's done by root.
> lsof on my system is in the /usr/sbin folder whichi is only accessible by root.
LOL; it's accessible by regular user as well. It's just (like hernst42) mentioned, it will list only those descriptors You have right to see.
Avatar of lkrubner

ASKER

ravenpl, that would explain why it gets nothing in return. I was thinking cron couldn't run lsof, so I ran visudo and added these lines to /etc/sudoers:

ALL  ALL = NOPASSWD: /usr/sbin/lsof
All  All = NOPASSWD: /bin/grep

I did "whereis lsof" and "whereis grep" to get the paths for these commands.
 But still nothing works. Your explanation makes sense.

Is there a way to make this script run as root?

bevhost, I was logged in as root when I ran "crontab -e" so the cron job should be listed in the root user's crontab.
ASKER CERTIFIED SOLUTION
Avatar of ravenpl
ravenpl
Flag of Poland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
PATH environment is not set inside Cron so perhaps you just need to prefix the lsof command with it's full path
eg
/usr/sbin/lsof
ravenpl, thanks. That was the problem. I needed to use the full path. cron is different from calling things from the command line.

I used "which lsof" to find the path.