Search code examples
bashloggingnetwork-programmingcronrsyslog

Crontab job than writes transition data to log file


I am having two computers. First "Router" have two ip address(10.3.0.1 and 192.168.1.105 ) is looking to internet and to sub-network 10.3.0.0/28 and have net.ipv4.ip_forward=1. I also added rules to iptables to allow forwarding from 10.3.0.0/24 . Second "User" have an ip 10.3.0.14 and def route 10.3.0.1 enter image description here I need to create cron job which will write hourly to a log file /var/log/net-usage/10.3.0.14.log the quantity of the transition data (upload and download). I need to use rsyslog(combined with loger), cron and iptables. Log format must be like Dec 31 08:23:06 Upload: 171K; Download: 8799K

I tried to solve it using transition information from iptables -vnL

I wrote simple bash code script.sh and made it executable

#!/bin/bash
date=$(date '+ %h %d  %H:%M:%S')
upload=$(iptables -vnL |sed -n 11p| awk '{print"UPLOAD" " " $2 ";"}')
download=$(iptables -vnL | sed -n 12p | awk '{print "DOWNLOAD" " " $2}')
echo $date $upload $download >> /var/log/net-usage/10.3.0.14.log

I am having two issues. First when i am running this script from terminal ./script.sh i got what i want

Ju20 15 08:05:12 UPLOAD 1446K; DOWNLOAD 25M

But when tried to add it to cron. crontab -e

0 * * * * /path_to_script/script.sh

I got only

Jul 20 05:00:01

without upload/download statistics in my 10.3.0.14.log file.

Second issue. I need to duplicate file 10.3.0.14.log from router to a user machine using rsyslog(and logger if needed). And put it to /var/log/net-usage.log.


Solution

  • Try changing iptables to /sbin/iptables(* in the crontab. The default path for cron doesn't usually include /sbin.

    *) or whatever type iptables prints.