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 nethogs Create bash script inside your home directory (your can replace it with other directory) assuming your username is bob:
touch /home/bob/nethogs.sh Make the created script executable:
chmod +x /home/bob/nethogs.sh Open 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 0 Save changes and close text editor. Next create another script to read named pipe created by nethogs.sh script:
touch /home/bob/netmon.sh Make the script executable:
chmod +x /home/bob/netmon.sh Copy 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 0 At 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.service and copy/paste the code (replace bob in ExecStart with your username):
[Unit] After=network.target [Service] ExecStart=/home/bob/nethogs.sh [Install] WantedBy=default.target Save changes and close the file. Make the created service enabled at system start:
sudo systemctl enable nethogs.service Start the nethogs service:
sudo systemctl start nethogs.service and check its status:
sudo systemctl status nethogs.service Finally cd to your home directory where netmon.sh script resides and execute the script:
./netmon.sh To 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 0 and restart service:
sudo systemctl restart nethogs.service Live 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.log All 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 0 Remark. 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.