skip to Main Content

I have created a simple bash script to start capturing traffic from all interfaces I have in my Linux machine (ubuntu 22), but this script should stop capturing traffic 2 hours after the machine has reboot. Below is my bash script

#!/bin/bash
cd /home/user/
tcpdump -U -i any -s 65535 -w output.pcap &

pid=$(ps -e | pgrep tcpdump)
echo $pid
sleep 7200
kill -2 $pid 

The script works fine if I run it, but I need to have it running after every reboot.

Whenever I run the script, it works without problem

user@linux:~$ sudo ./startup.sh
[sudo] password for user:
tcpdump: data link type LINUX_SLL2
tcpdump: listening on any, link-type LINUX_SLL2 (Linux cooked v2), snapshot length 65535 bytes
1202
35 packets captured
35 packets received by filter
0 packets dropped by kernel

but when I set it in the crontab as

@reboot /home/user/startup.sh

it does not start at reboot. I used ps -e | pgrep tcpdump to make sure if the script is running but there is not an output, it seems that it is not starting the script after the reboot. I don’t know if I need to have root permissions for that. Also, I checked the file permission, and it has

-rwxrwxr-x 1 user user 142 Nov 4 10:11 startup.sh

Any suggestion on why it is not starting the script at the reboot?

2

Answers


  1. Chosen as BEST ANSWER

    The problem here was that even though the user has root permission, if an script needs to be run in crontab at @reboot, crontab needs to be modified by root. That was the only way I found to run the script. As long as I am running tcpdump, this will require root permission but crontab will not start it at the boot up if it is not modified by sudo.


  2. Suggesting to update your script:

    #!/bin/bash
    source /home/user/.bash_profile
    cd /home/user/
    tcpdump -U -i any -s 65535 -w output.pcap &
    
    pid=$(pgrep -f tcpdump)
    echo $pid
    sleep 7200
    kill -2 $pid
    

    Suggesting to inspect crontab execution log in /var/log/cron

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search