Last active
December 5, 2017 21:01
-
-
Save SwagDevOps/3b0128763541e7a8a70fe1bd0fc24e45 to your computer and use it in GitHub Desktop.
execute scripts when your machine is connected to a specific network
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env sh | |
| # | |
| # This script depends on ``nmcli`` (and network-manager). | |
| # | |
| # Use this script in a crontab to periodically execute scripts | |
| # when your machine is connected to given networks. | |
| # | |
| # Scripts are stored in: ``~/.nm-scripts/${type}/${connection}`` | |
| # | |
| # Sample crontab: | |
| # | |
| # ``` | |
| # SHELL=/bin/sh | |
| # PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin | |
| # | |
| # */2 * * * * root nm-scripts john-doe > /dev/null 2>&1 || : | |
| # ``` | |
| export LANGUAGE=en_US | |
| export LANG=en_US.UTF-8 | |
| main() { | |
| set_user "$1" || { | |
| echo 'argv[1] (user) required' 1>&2 | |
| return 22 # EINVAL | |
| } | |
| is_logged_user || { | |
| echo "user (${NM_USER}) must be logged in" 1>&2 | |
| return 130 # EOWNERDEAD | |
| } | |
| which nmcli > /dev/null || { | |
| echo 'nmcli required' 1>&2 | |
| return 95 # EOPNOTSUPP | |
| } | |
| set_status | |
| test "$(echo "${NM_STATUS}" | wc -l)" -gt 0 || { | |
| return 100 # ENETDOWN | |
| } | |
| echo "Connected (${NM_USER}):\n${NM_STATUS}\n" | sed 's#/#\t#g' | |
| execute_network_scripts | |
| } | |
| # Define ``NM_USER`` | |
| # | |
| # User manipulating nm-cli (through sudo or crontab user) | |
| set_user() { | |
| local user=${1} | |
| test -z "$1" && { | |
| user=${SUDO_USER} | |
| } | |
| test -n "${user}" && { | |
| export NM_USER=${user} | |
| } || { | |
| return 1 | |
| } | |
| } | |
| is_logged_user() { | |
| test $(w -hs "${NM_USER}" | wc -l) -gt 0 | |
| } | |
| set_status() { | |
| export NM_STATUS="$(sudo -u "${NM_USER}" \ | |
| nmcli -t --fields state,type,connection d | \ | |
| grep -E '^connected' | \ | |
| grep -Ev -- ':--$' | \ | |
| awk -F ':' '{print $2"/"$3}')" | |
| } | |
| # Scripts MUST be accessible through ``~/.nm-scripts`` | |
| # | |
| # scripts are executed as ``root`` | |
| # scripts receive the following arguments: | |
| # * ``$1`` ``NM_USER`` | |
| # * ``$2`` ``NM_STATUS`` | |
| execute_network_scripts() { | |
| local nm_dir=$(getent passwd "${NM_USER}" | cut -d: -f6)/.nm-scripts | |
| echo "$NM_STATUS" | while read line; do | |
| script="${nm_dir}/${line}" | |
| test -f "${script}" || continue | |
| test -x "${script}" || continue | |
| echo "Executing... ${line}" | |
| "${script}" "${NM_USER}" "${NM_STATUS}" || { | |
| echo "Script '${line}', terminated with status ${?}" 1>&2 | |
| } | |
| done | |
| } | |
| main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment