Mój licznik transferu to tak na prawdę dwa skrypty w bashu, przy czym jeden jest uruchamiany cyklicznie co minutę przez crona. Wykorzystałem dobrodziejstwo jakiego dostarcza nam iptables i wyszło coś takiego:
1. Tworzymy plik /usr/bin/traffic i wklejamy poniższy kod:
#!/bin/bash if [[ $EUID -ne 0 ]]; then echo "You must be a root user" 2>&1 exit 1 fi if [ -x /var/log/traffic ]; then echo "/var/log/traffic dir exists" else mkdir /var/log/traffic fi iptables -F TRAFFIC_COUNTER > /dev/null out1=$(iptables -N TRAFFIC_COUNTER) if [ -n "$out1" ]; then echo "Chain exists!" 2>&1 exit 1 fi iptables -I INPUT -j TRAFFIC_COUNTER iptables -I OUTPUT -j TRAFFIC_COUNTER iptables -A TRAFFIC_COUNTER -p tcp iptables -A TRAFFIC_COUNTER -p udp iptables -A TRAFFIC_COUNTER -p icmp out2=$(iptables -L TRAFFIC_COUNTER -v -n -x) #echo "$out2" 2>&12. Dajemy prawa do uruchamiania:
sudo chmod +x /usr/bin/traffic3. Tworzymy plik /usr/bin/trafficwatcher i wklejamy poniższy kod:
#!/bin/bash
if [[ $EUID -ne 0 ]]; then
echo "You must be a root user" 2>&1
exit 1
fi
out1=$(iptables -L -v -n -x | grep TRAFFIC_COUNTER)
if [ "$out1" = "" ]; then
echo "Can't find TRAFFIC_COUNTER chain! Creating..." 2>&1
traffic
fi
fileName=$(date +%Y%m)
lastValue=$(cat /var/log/traffic/$fileName.log)
if [ "$lastValue" = "" ]; then
lastValue="0"
fi
totalTraffic=$(iptables -L TRAFFIC_COUNTER -v -n -x | egrep -wo '[[:space:]]+[0-9]+[[:space:]]+([0-9]+)' | sed 's/ \+\([0-9]*\) \+\([0-9]*\) *$/\2/' | awk '{a+=$0}END{print a}')
echo "$totalTraffic" 2>&1
echo "$lastValue" 2>&1
totalTraffic=$(echo "scale=2; ($totalTraffic / 1048576) + $lastValue" | bc -l)
if [ "$totalTraffic" != "" ]; then
echo "$totalTraffic" > "/var/log/traffic/$fileName.log"
fi
# zerujemy licznik
iptables -Z TRAFFIC_COUNTER
4. Dajemy prawa do uruchamiania:sudo chmod +x /usr/bin/trafficwatcher5. Dodajemy joba w cronie, tak żeby trafficwatcher uruchamiał się co minutę. Edytujemy /etc/crontab i dodajemy do niego linijkę
*/1 * * * * root trafficwatcher6. restartujemu crona:
sudo service cron restart
7. Skrypt trafficwatcher stworzy plik /var/log/traffic/RRRRMM.log (gdzie RRRR to rok, a MM to aktualny miesiąc) i od teraz co minutę będzie go aktualizował wpisując zużyty transfer w megabajtach.


Brak komentarzy:
Prześlij komentarz