5

This answer gives a solution to run scripts when a connection has been set up by NetworkManager. However, I'd like to run my script (that auto-connect to some special kinds of hotspot) as a non-root user, because it's quite dirty, and I would not bet that it's not possible to do code-injection inside. Do you know if a kind of ~/.config/NetworkManager/dispatcher.d/ exists ?

Thank you!

3

I wanted to do the same thing and here is what I did to make this work:

Create /etc/NetworkManager/dispatcher.d/99-user-scripts:

#!/bin/bash
#
#   Run NeworkManager dispatcher scripts from user home directories
#   for logged in users
#   See: https://developer.gnome.org/NetworkManager/stable/NetworkManager.html
#   See: https://unix.stackexchange.com/q/405242
#
for user in $(who | awk '{print $1}' | sort | uniq); do
  scripts_dir="/home/${user}/.config/NetworkManager/dispatcher.d"
  [ ! -d "$scripts_dir" ] && continue
  find $scripts_dir -type f -executable -user $user -perm -u+rwx ! -perm /go+w ! -perm /+s | \
    sort | \
    xargs -I{} sudo -u $user --set-home --preserve-env -- {} $1 $2
done

Set proper permissions on file according to NetworkManager documentation:

$ chmod u+x,go-w,a-s /etc/NetworkManager/dispatcher.d/99-user-scripts

Then create your user script directory and create your user script:

$ mkdir -p ~/.config/NetworkManager/dispatcher.d
$ touch ~/.config/NetworkManager/dispatcher.d/50-my-script
$ chmod u+x,go-w,a-s ~/.config/NetworkManager/dispatcher.d/50-my-script

Here is a sample ~/.config/NetworkManager/dispatcher.d/50-my-script:

#!/bin/bash
prog="$(basename "${BASH_SOURCE[0]}")"
logger -t $prog -p user.notice "Running ${BASH_SOURCE[0]} $@"
printenv | logger -t $prog -p user.notice # verify environment variables are inherited

You can verify the sample script is being run by checking the system log after a network event has occurred.

Limitations

  • Will not work with /root or non-standard user home directory paths (easily fixable)
  • For simplicity I chose not to implement the pre-up.d and pre-down.d functionality (a possible enhancement)
  • I am not positive the execution order is exactly the same as /etc/NetworkManager/dispatcher.d scripts. The docs say alphabetical, so I used sort on the found files. Probably not a huge issue but FYI.
  • I am using Bash 4+ syntax rather than generic shell code because that is what I am familiar with. I imagine this could be made to support other shells.
  • I make NO CLAIMS as to the security of this implementation!
1
  • Interesting trick, thanks!
    – tobiasBora
    Sep 4 '19 at 19:06

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.