Let's start from the beginning: I have a Pi which wakes up my server when a request comes in on tcpdump, and it works like a treat!

My problem is that I want my server to sleep when there is no incoming data for, let's say, 30 mins. The server is used only by me, both from within and outside my LAN.

I think that I need to use tcpdump in a shell script to monitor the port or the IP and, if there is no incoming, it will react to it. I have an idea to do this, because I have looked around on the internet for 2 days, and tried a lot of things, but I can't succeed.

How can I do this?


I'm assuming that "no incoming data" means: tcpdump is not printing any line. Therefore we have to start a 30 minute timer and reset it whenever tcpdump prints a line.

Starting it is fairly simple:

sleep 30m && poweroff

How do we reset it? Simple: we kill sleep and restart it.

How do we detect new lines from tcpdump? A good old while read -r loop.

Putting everything together:


set -e

shutdown-timer() {
    # Waits 30 minutes and shuts down the computer.
    sleep 30m && poweroff

reset-timer() {
    # Kills 'shutdown-timer' (if it's running) and
    # restarts it, saving its PID in 'timerpid'.
    if [[ -n "$timerpid" ]]
        kill "$timerpid" || true
    shutdown-timer &

# Start the timer for the first time.

tcpdump | while read -r line
    # A new packet was sent or received.

Note that there might be disturbing packets every now and then. For example you might have configured APT to check for updates every 5 minutes. This will prevent the computer from shutting down, because the timer would be reset every 5 minutes.

If you need, you can filter the output of tcpdump using grep or whatever tool, like this:

tcpdump | grep -v archive.ubuntu.com | while read -r line

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.