-1

The three lines can run.

debian8@hwy:~$ trafficlog="/var/log/traffic.log"
debian8@hwy:~$ echo  `date "+%Y-%m-%d %H:%M:%S  "` |  sudo tee -a  $trafficlog    
2017-02-04 21:20:41
debian8@hwy:~$ sudo iptables  -v -L INPUT |grep Chain  |  sudo tee -a  $trafficlog
Chain INPUT (policy ACCEPT 122 packets, 28381 bytes)

Let me check it.

debian8@hwy:~$ cat  /var/log/traffic.log
2017-02-04 21:20:41
Chain INPUT (policy ACCEPT 122 packets, 28381 bytes)

Now to make it run at the runlevel6 on my debian8.

sudo vim /etc/init.d/K99trafficLog.sh
#!/bin/bash
trafficlog="/var/log/traffic.log"
echo  `date "+%Y-%m-%d %H:%M:%S  "` |  sudo tee -a  $trafficlog
sudo iptables  -v -L INPUT |grep Chain  |  sudo tee -a  $trafficlog

sudo chmod +x /etc/init.d/K99trafficLog.sh
sudo ln -s /etc/init.d/K99trafficLog.sh  /etc/rc6.d/K99trafficLog

Now to test it.

echo "" | sudo tee /var/log/traffic.log

Then to reboot to verify.

sudo cat /var/log/traffic.log

It is unlucky that nothing written into /var/log/traffic.log,why?

showkey
  • 323

2 Answers2

2

Those init scripts are run as root. Therefore you don't need all those sudo/tee hacks:

#!/bin/bash
exec >/var/log/traffic.log
date "+%Y-%m-%d %H:%M:%S  "
iptables -v -L INPUT |grep Chain

Also be aware that /etc/rc*.d/K* is run on leaving runlevel, while /etc/rc*.d/S* is run on entering runlevel.

Be aware that runlevel 6 is special. Entering that runlevel makes your system reboot, therefore you never actually leave that level.

You can always manually debug your script using sudo bash -x /etc/rc6.d/K99trafficLog.

Also be aware that current debian systems use systemd for managing services. Please read about about systemd which handles things different than old runlevel based approaches.

michas
  • 21,510
0

sudo vim /etc/systemd/system/graphical.target.wants/Ktraffic.service

[Unit]
Description=Record net traffic

[Service]
Type=oneshot
ExecStart=/bin/bash   /etc/init.d/K01trafficLog.sh

[Install]
WantedBy=poweroff.target

sudo vim /etc/init.d/K011trafficLog.sh

#!/bin/bash
trafficlog="/var/log/traffic.log"
date "+%Y-%m-%d %H:%M:%S  "         >> $trafficlog
iptables  -v -L INPUT |grep Chain   >> $trafficlog

systemctl enable ktraffic.service

michas
  • 21,510
showkey
  • 323