Is there a tool as service which can monitor network traffic for every processes. So that I can use command-line to analyze the usage?
31 Answer
According to your comments you need no logs saved on drive and wish to run the network monitor as system service enabled at system start. Let's do it.
Install nethogs utility:
sudo apt install nethogsCreate bash script inside your home directory (your can replace it with other directory) assuming your username is bob:
touch /home/bob/nethogs.shMake the created script executable:
chmod +x /home/bob/nethogs.shOpen script in text editor and copy and paste its code:
#!/bin/bash
pipe=/tmp/nethogs_pipe
trap "rm -f $pipe" EXIT
if [[ ! -p $pipe ]]; then mkfifo $pipe
fi
exec 3<>$pipe
nethogs -t -a >&3 2>&1
exit 0Save changes and close text editor. Next create another script to read named pipe created by nethogs.sh script:
touch /home/bob/netmon.shMake the script executable:
chmod +x /home/bob/netmon.shCopy and paste to netmon.sh the code:
#!/bin/bash
pipe="/tmp/nethogs_pipe"
while true
do if read line; then echo $line fi
done <"$pipe"
exit 0At next step we have to convert the nethogs.sh bash script to system service. Create/open the file in editor:
sudo nano /etc/systemd/system/nethogs.serviceand copy/paste the code (replace bob in ExecStart with your username):
[Unit]
After=network.target
[Service]
ExecStart=/home/bob/nethogs.sh
[Install]
WantedBy=default.targetSave changes and close the file. Make the created service enabled at system start:
sudo systemctl enable nethogs.serviceStart the nethogs service:
sudo systemctl start nethogs.serviceand check its status:
sudo systemctl status nethogs.serviceFinally cd to your home directory where netmon.sh script resides and execute the script:
./netmon.shTo quit monitoring press CTRL+C. That's all.
If you want to save monitoring data to drive, replace content of the nethogs.sh script with the code:
#!/bin/bash
log="/var/log/nethogs.log"
err="/var/log/nethog.err"
nethogs -t -a > $log 2> $err
exit 0and restart service:
sudo systemctl restart nethogs.serviceLive monitor through named pipe will be disabled and output of the script will be saved to /var/log/nethogs.log file - just open it with less or tail, for example:
tail -f /var/log/nethogs.logAll of errors will be saved to /var/log/nethogs.log file. The /var/log/nethogs.log will be cleaned up everytime computer rebooted/service restarted, to disable files cleanup and to enable output appending replace content of the nethogs.sh script with another code:
#!/bin/bash
log="/var/log/nethogs.log"
err="/var/log/nethog.err"
nethogs -t -a >> $log 2>> $err
exit 0Remark. In nethogs command options -t and -a inside scripts can be replaced according to your version installed. In Ubuntu 18.04 nethogs version option -t means tracemode and option -ais listen all interfaces.