0

i have the following code:

        $cmd="lsof | awk '{print $1 \" \" $2 \" \" $3 \" \" $9}'";
        $info = shell_exec($cmd);        
        $processors = preg_split('/\s?\n\s?\n/', trim($info));
        $processors = explode("\n",$processors[0]);
        foreach($processors as $processor){
           echo $processor."\n";
        }

when i run it on the command line i get positive results. however, when i run it on a php script i get:

systemd 1 root denied) for each $processor

somejkuser
  • 8,856
  • 20
  • 64
  • 130
  • IMHO not sure `awk` tag should be there for this post or not, may be `bash` tag since `lsof` is a shell command(internal or external)? – RavinderSingh13 Nov 06 '19 at 18:28

2 Answers2

0

If you look at the full output of lsof you'll see most lines look like:

COMMAND     PID   TID TASKCMD            USER   FD      TYPE             DEVICE  SIZE/OFF       NODE NAME
systemd       1                          root  cwd   unknown                                         /proc/1/cwd (readlink: Permission denied)

Because the user you're running as doesn't have permissions to look at processes that aren't its own.

Try: sudo lsof

Sammitch
  • 30,782
  • 7
  • 50
  • 77
0

When I given a try to your code posted, I too got the same errors(was able to re-produce the errors).

Then I tried to put only lsof in place of your complete lsof command with awk to see whats the complete error and I got following error.

COMMAND PID    USER   FD      TYPE DEVICE SIZE/OFF       NODE NAME
sh        1    root  cwd   unknown                            /proc/1/cwd (readlink: Permission denied)
sh        1    root  rtd   unknown                            /proc/1/root (readlink: Permission denied)
sh        1    root  txt   unknown                            /proc/1/exe (readlink: Permission denied)
sh        1    root NOFD                                      /proc/1/fd (opendir: Permission denied)
time      9    root  cwd   unknown                            /proc/9/cwd (readlink: Permission denied)
time      9    root  rtd   unknown                            /proc/9/root (readlink: Permission denied)

After that I googled and found a great link https://unix.stackexchange.com/a/109228 (cross site reference) which tells us that lsof is providing error since we don't have access on those files/commands and obviously we are NOT running command with root.

So to overcome this problem IMHO you could:

  • Run lsof command as sudo to get rid of errors, in case your user has sudo access to run this command.
  • In case you are NOT interested in root processes details then you could remove these errors by sending them to /dev/null.
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93