Php script running shell_exec to run sh scripts with tshark

35 Views Asked by At

I need to perform a packet capture operation during a process performed with wget

If I run thark or tcpdump from the console everything works perfectly. However, if I call the sh script with shell_exec from php the capture does not work. I also added, with sudo visudo, the user www-data to the sudoers that can run that sh script without a password prompt. For example tshark tells me in the logs, "tshark: The capture session could not be initiated on capture device "ens192" (socket: Address family not supported by protocol)." when the sh script is run from php.

This is the php script

$code = time();
$url = "https://www.google.com";

$output = null;
$return_var = null;

$output = shell_exec("sudo /var/www/vhosts/mysite/httpdocs/service/command.sh $code $url 2>&1");

echo $output;

This is the sh script

#!/bin/bash
CODE=$1
URL=$2
DIR=$(dirname "$0")
LOGFILE="$DIR/error.log"

echo $(date) >> $LOGFILE
whoami >> $LOGFILE

which tcpdump >> $LOGFILE

if [ $# -ne 2 ]; then
  echo "Errore: è necessario passare due argomenti"
  exit 1
fi

echo "Inizio script" >> $LOGFILE

mkdir "$DIR/$CODE" 2>> $LOGFILE
cd "$DIR/$CODE" 2>> $LOGFILE

echo "Esecuzione tshark" >> $LOGFILE

sudo -u myuser tshark -w "${CODE}.pcap" 2>> $LOGFILE &

TSHARK_PID=$!
sleep 2

echo "Esecuzione wget" >> $LOGFILE

wget --execute robots=off --no-warc-keep-log --page-requisites --span-hosts --user-agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36' --warc-cdx=on --output-file=$CODE-log.txt  --warc-file=$CODE  -d  -E --warc-file=$CODE $URL 2>> $LOGFILE
sleep 2

if [ $? -eq 0 ]; then
  echo "Wget in corso." >> $LOGFILE
else
  echo "Errore wget, esco." >> $LOGFILE
  kill -15 $TSHARK_PID
  exit 1
fi

ls -l >> $LOGFILE  # Verifica i file
sudo kill -15 $TSHARK_PID 2>> $LOGFILE

cd ..

zip -q -j "${CODE}-pcap.zip" "$DIR/$CODE/${CODE}.pcap" 2>> $LOGFILE

rm "$DIR/$CODE/${CODE}.pcap" 2>> $LOGFILE

zip -q -r "${CODE}-wget.zip" "$CODE" 2>> $LOGFILE

rm -rf "$CODE" 2>> $LOGFILE

mv "$CODE-wget.zip" done/

echo "Fine script" >> $LOGFILE
echo "**************************************************************************************" >> $LOGFILE
echo "${CODE}"

I've tried everything, I installed tcpdump, but it generates errors saying that it doesn't recognize the protocols, while if I run tcpdump via shell it works. Same thing for tshark

0

There are 0 best solutions below