[PYTHON] I want to be notified of the connection environment when the Raspberry Pi connects to the network

I bought a Raspberry Pi 4. So, I put Arch Linux in the SD card.

I didn't buy the LED separately this time, but it will be operated in its original state, but there is one problem,

** It is troublesome to check where you are connected **

Basically, DHCP is used and there is no monitor, so it is troublesome to go to check the IP address regardless of whether it is a wired connection or a wireless connection. So, this time, as the title suggests, I decided to "get the connection information from myself when the network connection is established".

Summary

Environmental information

The code I wrote

py:/etc/NetworkManager/dispatcher.d/notify-connection-information.py


#!/usr/bin/env python
import json
import os
import sys
from urllib.request import urlopen


WEBHOOK_URL = 'https://hooks.slack.com/services/THISIS/SLACK/WEBHOOK'


def main(conn_id, ip_addr):
    payload = {
        'username': 'info',
        'icon_emoji': ':strawberry:',
        'text': f'*attakei-pi* has connected to {conn_id}\n IP address is `{ip_addr}`',
        'channel': '@attakei',
    }
    urlopen(WEBHOOK_URL, json.dumps(payload).encode())


if __name__ == '__main__':
    argv = sys.argv[1:]
    # if argv[0] != 'wlan0' or argv[1] != 'up':
    if argv[1] != 'up':
        sys.exit(0)
    ip_addr = os.environ['DHCP4_IP_ADDRESS']
    conn_id = os.environ['CONNECTION_ID']
    main(conn_id, ip_addr)

Completion notification

スクリーンショット 2019-12-02 18.58.02.png

NetworkManager story

What is NetworkManager?

It is a daemon (+ tool) for managing various things related to network connection. It manages the SSID and automatically connects to the already registered SSID.

There are also systemd-networkd etc., but for the time being I am currently using this.

NetworkManager dispatch function

Now, NetworkManager has a dispatcher feature that allows you to" execute a command to divide a network as an event. " In the sample etc. posted on the ArchLinux Wiki, examples such as "Disable wireless when making a wired connection (+ vice versa)" and "Continue to VPN connection when connecting to a specific network" are written. I am. This time, referring to these scripts, I made the above script "Declare the used SSID and ʻIP address to the specified Slack channel when connecting to the network".

What the dispatcher receives

As far as I know by actually using it, Disptcher will pass the following information when executing the command.

Align information and dispatch

Based on the conditions you want to trigger, organize where to get information and behavior.

Now that you have the information you need, you can write the code. Please refer to the code as it was written first.

Supplement

Don't forget to shebang and grant execute permissions as the script will be called directly.

URLs

Recommended Posts

I want to be notified of the connection environment when the Raspberry Pi connects to the network
I want to run the Python GUI when starting Raspberry Pi
I sent the data of Raspberry Pi to GCP (free)
I tried to automate the watering of the planter with Raspberry Pi
Use Raspberry Pi to solve the problem of insufficient mobile Wi-Fi connection
I want to use Python in the environment of pyenv + pipenv on Windows 10
I tried to build an environment of Ubuntu 20.04 LTS + ROS2 with Raspberry Pi 4
I want to prevent the speaker connected to the Raspberry Pi (jessie) from bouncing when the OS is restarted (Python script)
I want to grep the execution result of strace
I want to fully understand the basics of Bokeh
I want to increase the security of ssh connections
When I tried to do socket communication with Raspberry Pi, the protocol was different
I talked to Raspberry Pi
I want to use only the normalization process of SudachiPy
I want to get the operation information of yahoo route
I want to disable interrupts on Raspberry Pi (≒ DI / EI)
I want to judge the authenticity of the elements of numpy array
Change the message displayed when logging in to Raspberry Pi
Keras I want to get the output of any layer !!
I want to know the legend of the IT technology world
Make a note of what you want to do in the future with Raspberry Pi
I tried to move ROS (Melodic) with the first Raspberry Pi (Stretch) at the beginning of 2021
I want to get the name of the function / method being executed
When I start the virtual environment of conda, the prompt of bash collapses
I want to manually assign the training parameters of the [Pytorch] model
I want to read the html version of "OpenCV-Python Tutorials" OpenCV 3.1 version
I want to output the beginning of the next month with Python
When you want to save the result of the callback function somewhere
I want to check the position of my face with OpenCV!
When generating a large number of graphs with matplotlib, I do not want to display the graph on the screen (jupyter environment)
I want to know the population of each country in the world.
Periodically log the value of Omron environment sensor with Raspberry Pi
About the error I encountered when trying to use Adafruit_DHT from Python on a Raspberry Pi
I want to save the trouble of inputting when debugging Paiza's skill check example in a local environment such as Jupyter [Python]
I want to display the number of num_boost_rounds when early_stopping is applied using XGBoost callback (not achieved)
I want to solve the problem of memory leak when outputting a large number of images with Matplotlib
I made an npm package to get the ID of the IC card with Raspberry Pi and PaSoRi
I want to separate the processing between test time and production environment
[I touched the Raspberry Pi (1)] I summarized the basic operations of Minecraft Pi Edition (2015.5.23 pre-release)
I don't want to admit it ... The dynamical representation of Neural Networks
Note: I want to do home automation with Home Assistant + Raspberry Pi + sensor # 1
Python Note: When you want to know the attributes of an object
I tried how to improve the accuracy of my own Neural Network
(Python Selenium) I want to check the settings of the download destination of WebDriver
I want to batch convert the result of "string" .split () in Python
I want to explain the abstract class (ABCmeta) of Python in detail.
When you want to change the HTTP headers of Flask's test client
I want to sort a list in the order of other lists
IPv6 should be disabled when ssh of Raspberry Pi 4 is very slow
I want to express my feelings with the lyrics of Mr. Children
I want to analyze the emotions of people who want to meet and tremble
I connected the thermo sensor to the Raspberry Pi and measured the temperature (Python)
I want to use the Qore SDK to predict the success of NBA players
I want to leave an arbitrary command in the command history of Shell
I want to stop the automatic deletion of the tmp area with RHEL7
Logging the value of Omron environment sensor with Raspberry Pi (USB type)
Python: I want to measure the processing time of a function neatly
I want to pin Spyder to the taskbar
I want to output to the console coolly
I want to handle the rhyme part1
I want to handle the rhyme part3