Search code examples
phpescapingshell-exec

Escaping shell_exec


I can run this:

echo shell_exec ("tail -n 500 /var/log/website.com_access_log | cut -d' ' -f1 | sort | uniq -c | sort -gr | head -10");   

But I can't run this (works in terminal):

echo shell_exec ("tail -n 500 /var/log/website.com_access_log | sed -e 's/^\([[:digit:]\.]*\).*\"\(.*\)\"$/\1 \2/' | sort | uniq -c | sort -gr | head -10");  

returns nothing or "500 " (gibberish here)

Obviously, it has something to do with escaping. Only " are escaped for PHP in example.
I tried escapeshellarg() and escapeshellcmd() without success (returns nothing). A also tested escaping \ with \\, \\\, \\\\.

What is wrong here? What should I escape?


Solution

  • Using single quotes solve the problem. Also adding : in your first capture group allows to grab IPv6 addresses.

    echo shell_exec ('tail -n 500 /var/log/website.com_access_log | sed -e \'s/^\([[:digit:]:\.]*\).*\"\(.*\)\"$/\1 \2/\' | sort | uniq -c | sort -gr | head -10');
    

    Outputs :

    474 127.0.0.1 Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0
     19 ::1 Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.xx (KHTML, like Gecko) Chrome/64.0.xxx.xxx Safari/xxx.xx
      7 ::1 Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.xx (KHTML, like Gecko) Ubuntu Chromium/64.0.xxx.xx Chrome/64.0.xxx.xxx Safari/xxx.xx