11

I would like to write a systemd service that depends on USB WiFi dongle being present. It doesn't need to start when device is plugged in as long as it doesn't start when device is not plugged in. How can I achieve this?

The systemd configruation file is in network@.conf format. It uses the the %i placeholder. So I tried adding this to the unit file:

[Path]
PathExists = /dev/%i

Where %i would be something like wlan0. Unfortunately, this gets completely ignored, so I might not understand the proper use of this section.

I've also tried:

[Unit]
....
BindsTo=sys-subsystem-net-devices-%i.device
After=sys-subsystem-net-devices-%i.device

I it picked up from somewhere (I forgot where), and that doesn't work either.

1 Answer 1

10

You need to combine udev and systemd.

Add a new rule for udev, in /etc/udev/rules.d/95-mywifi.rules, as follows:

 ACTION=="add", ATTRS{idVendor}=="...", ATTRS{idProduct}=="...", SYMLINK=="mywifi", TAG+="systemd", ENV{SYSTEMD_WANTS}="netctl-auto@mywifi.service"

(You must substitute for the dots the Vendor and Product codes appropriate to your dongle).

The exisiting netctl-auto@.service is:

  # cat /lib/systemd/system/netctl-auto\@.service 
  [Unit]
  Description=Automatic wireless network connection using netctl profiles
  Documentation=man:netctl.special(7)
  BindsTo=sys-subsystem-net-devices-%i.device
  After=sys-subsystem-net-devices-%i.device
  Before=network.target
  Wants=network.target

  [Service]
  ExecStart=/usr/bin/netctl-auto start %I
  ExecStop=/usr/bin/netctl-auto stop %I
  RemainAfterExit=yes
  Type=forking

  [Install]
  WantedBy=multi-user.target

For this to work, you will have to setup a netctl profile, see the Arch Linux Wiki to see how to do that.

4
  • Is there a way to do this for any wifi dongle without having to know vendor and product IDs?
    – user128580
    Dec 14, 2014 at 21:06
  • 1
    @bvukelic Yes: ACTION=="add", SUBSYSTEM=="net", KERNEL=="wlan[1-9]", SYMLINK=="mywifi", TAG+="systemd", ENV{SYSTEMD_WANTS}="netctl-auto@mywifi.service". This assumes you hve an onboard wifi called wlan0, in which case nothing is done, plus USB wifi dongles called from wlan1 to wlan9. If you have no onboard wifi card, change [1-9] to [0-9] Dec 14, 2014 at 23:00
  • Thank you for very detailed instructions. I'll test this tomorrow.
    – user128580
    Dec 15, 2014 at 0:18
  • 1
    I don't have enough rep to comment on the accepted answer, and I know this is a bit of a necro but to expand on answer: I got a working rule based on MariusMatutiaes: ACTION=="add", SUBSYSTEM=="net", KERNEL=="wlan[1-9]", TAG+="systemd", ENV{SYSTEMD_WANTS}="netctl-auto@$name.service" I'm not sure if its better but I would think so because it doesn't use a symlink.
    – gdunstone
    Jan 3, 2017 at 11:20

Your Answer

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