You are not logged in.

#1 2012-10-07 00:30:45

snakeroot
Member
Registered: 2012-10-06
Posts: 103

Starting and Stopping Services Based on Network

Hi everyone,

This is something I've been playing with and I'd like to share it with you and get your thoughts.

The services I want to run at any given point depend on what network I'm attached to. For example, if I'm at home, I'll want avahi-daemon and cupsd started but I won't need iptables, since I'm behind my router's firewall. On the other hand if I'm at an internet cafe I need iptables but not the other two.

What I've done is set up a script in /etc/NetworkManager/dispatch.d which starts services based on the UUID of each connection (extracted from that connection's file in /etc/NetworkManager/system-connections.

I'm currently using the following script:

#!/bin/bash
IF=$1
STATUS=$2

function start_service {
        for i in "$@"
                do
                        if [ `/usr/bin/systemctl show "$i".service | grep -c "ActiveState=inactive"`=1 ]
                                then
                                        /usr/bin/systemctl start "$i".service
                        fi
                done
}

function stop_service {
        for i in "$@"
                do
                        if [ `/usr/bin/systemctl show "$i".service | grep -c "ActiveState=active"`=1 ]
                                then
                                       /usr/bin/systemctl stop "$i".service
                        fi
                done
}

if [ "$IF" = "wlan0" ] && [ "$STATUS" = "up" ]; then
UUID=`nmcli --nocheck -t --fields UUID con status`
case $UUID in
f5320fcd-43e2-4cc1-ba1a-9606f66b5332)
        start_service avahi-daemon cupsd
        logger "M5DKQ (home network) up"
;;
5bfff3c5-c349-436b-953b-90de15c854d7)
        start_service iptables
        logger "EVO (4G hotspot) up"
;;
40d74743-f809-41ce-821c-71f9f40b8513)
        logger "GuestAccess (office guest network) up"
;;
*)
        start_service iptables
        logger "Starting cafe-specific services"
;;
esac
fi

if [ "$IF" = "wlan0" ] && [ "$STATUS" = "down" ]; then
        stop_service avahi-daemon cupsd iptables
        logger "Stopped location-specific services"
        logger "wlan0 down"
fi

Is there a better way to do this, like maybe a systemd custom target? Is there a cleaner way to script this?

Thanks in advance,

Offline

Board footer

Powered by FluxBB