How to update WireGuard peer endpoint address using DNS on MikroTik RouterOS

Update 2022-12-30: Updated code, now uses variables

Assuming your peer comment is peer1 and the correct endpoint DNS record is peer1.mydomain.com, you can use this RouterOS script to update the endpoint based on the DNS record:

:local PEERCOMMENT 
:local DOMAIN 

:set PEERCOMMENT "peer1"
:set DOMAIN "peer1.mydomain.com"

:if ([interface wireguard peers get number=[find comment=$PEERCOMMENT] value-name=endpoint-address] != [/resolve $DOMAIN]) do={
    interface wireguard peers set number=[find comment=$PEERCOMMENT] endpoint-address=[/resolve $DOMAIN]
}

Modify the variables to suit your Wireguard config: Set PEERCOMMENT to the comment of the peer that should be updated and set DOMAIN to the DNS domain name that should be used to update the peer’s IP address

After that, add it as a new script in System -> Scripts, then add a Scheduler to run the script e.g. every 30 seconds under System -> Scheduler

Script settings

Scheduler settings

Related posts which might make the process easier to understand:

Posted by Uli Köhler in MikroTik, Wireguard

How to check if WireGuard Peer endpoint address equals DNS record using RouterOS scripting on MikroTik

Assuming your peer comment is peer1 and the correct endpoint DNS record is peer1.mydomain.com:

([interface wireguard peers get number=[find comment=peer1] value-name=endpoint-address] = [resolve peer1.mydomain.com])

This will return true if the peer endpoint is the same as the DNS record.

Example

[admin@CoreSwitch01] > :put ([interface wireguard peers get number=[find comment=peer1] value-name=endpoint-address] = [resolve peer1.mydomain.com])
true
Posted by Uli Köhler in MikroTik, Wireguard

RouterOS scripting: How to get Wireguard peer endpoint address on MikroTik

We assume that the peer you want to find info about has comment=peer1.mydomain.com. Use

Use

interface wireguard peers get number=[find comment=peer1.mydomain.com] value-name=endpoint-address

or use :put [...] to print the value:

:put [interface wireguard peers get number=[find comment=peer1.mydomain.com] value-name=endpoint-address]

Example

[admin@CoreSwitch01] > :put [interface wireguard peers get number=[find comment=peer1.mydomain.com] value-name=endpoint-address]
12.245.102.141

 

Posted by Uli Köhler in MikroTik, Wireguard

How to resolve DNS name in MikroTik RouterOS scripting/command line

In order to resolve a DNS name use

resolve <domain name>

Use

:put [resolve <domain name>]

to resolve a domain name and print the IP address.

Example

:put [resolve techoverflow.net]

Output:

[admin@CoreSwitch01] > :put [resolve techoverflow.net]
172.67.166.211
Posted by Uli Köhler in MikroTik

How to deduplicate your IMAP emails

IMAPDdedup is a tool to deduplicate IMAP emails, i.e. delete identical emails from your IMAP account. By default, it will only delete mails within the same folder and use the Message-ID header to find duplicate emails. It is also pretty fast, since it only needs to load the message headers, not the complete messages.

First, clone it using

git clone https://github.com/quentinsf/IMAPdedup.git

Then run it using

python3 IMAPDdedup/imapdedup.py -s [server] -w [password] -r -S -u [username] [Folder]

For example:

python3 IMAPdedup/imapdedup.py -s imap.your-server.de -w Hiethi3lah -r -S -u [email protected] INBOX

 

Posted by Uli Köhler in E-Mail

How to set username & password in Paho-MQTT

Set username & password in Paho-MQTT using

client.username_pw_set("myusername", "aeNg8aibai0oiloo7xiad1iaju1uch")

You need to call that before calling connect()!

Example of how to connect with username & password:

client = mqtt.Client("mqtt-test") # client ID "mqtt-test"
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set("myusername", "aeNg8aibai0oiloo7xiad1iaju1uch")
client.connect('127.0.0.1', 1883)
client.loop_forever()  # Start networking daemon

 

Posted by Uli Köhler in MQTT, Python

How to fix Paho-MQTT result code 5

When you see result code 5 in paho-mqtt this means Unauthorized! Typically it means you don’t have the correct username and password set.

Set username & password using

client.username_pw_set("myusername", "aeNg8aibai0oiloo7xiad1iaju1uch")

Example of how to connect with username & password:

client = mqtt.Client("mqtt-test") # client ID "mqtt-test"
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set("myusername", "aeNg8aibai0oiloo7xiad1iaju1uch")
client.connect('127.0.0.1', 1883)
client.loop_forever()  # Start networking daemon

 

Posted by Uli Köhler in MQTT, Python

Python MQTT subscribe minimal example (Paho-MQTT)

#!/usr/bin/env python3
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    # This will be called once the client connects
    print(f"Connected with result code {rc}")
    # Subscribe here!
    client.subscribe("my-topic")

def on_message(client, userdata, msg):
    print(f"Message received [{msg.topic}]: {msg.payload}")

client = mqtt.Client("mqtt-test") # client ID "mqtt-test"
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set("myusername", "aeNg8aibai0oiloo7xiad1iaju1uch")
client.connect('127.0.0.1', 1883)
client.loop_forever()  # Start networking daemon

 

Posted by Uli Köhler in MQTT, Python

How to fix Python ModuleNotFoundError: No module named ‘paho’

Problem:

When running your Python script, you see an error message like

Traceback (most recent call last):
  File "test.py", line 2, in <module>
    import paho.mqtt.client as mqtt
ModuleNotFoundError: No module named 'paho'

Solution:

Install the paho-mqtt package using

pip3 install paho-mqtt

or

pip install paho-mqtt
Posted by Uli Köhler in MQTT, Python

How to fix HomeAssistant [homeassistant.components.mqtt] Unable to connect to the MQTT broker: Connection Refused: not authorised.

Problem:

When starting up HomeAssistant, e.g. using docker-compose up, you see this error message:

homeassistant    | 2021-12-27 19:55:46 WARNING (Recorder) [homeassistant.components.recorder.util] The system could not validate that the sqlite3 database at //config/home-assistant_v2.db was shutdown cleanly                                                                                  
homeassistant    | 2021-12-27 19:55:47 ERROR (Thread-3) [homeassistant.components.mqtt] Unable to connect to the MQTT broker: Connection Refused: not authorised.                                                                                                                                 
homeassistant    | 2021-12-27 19:55:47 WARNING (Thread-3) [homeassistant.components.mqtt] Disconnected from MQTT server 127.0.0.1:1883 (5)
homeassistant    | 2021-12-27 19:55:48 ERROR (Thread-3) [homeassistant.components.mqtt] Unable to connect to the MQTT broker: Connection Refused: not authorised.                                                                                                                                 
h

Solution:

Your configuration.yml does not have the correct username and/or password for your MQTT server.

This is an example section that works if the MQTT server has the correct user:

mqtt:
  broker: "127.0.0.1"
  username: "homeassistant"
  password: "ep2ooy8di3avohn1Ahm6eegheiResh"

Also check if the MQTT server such as Mosquitto has the correct user with the correct password.

Posted by Uli Köhler in Home-Assistant

Simple HomeAssistant docker-compose setup

First, create a directory where HomeAssistant will reside. I use /opt/homeassistant.

Create docker-compose.yml:

version: '3.5'
services:
  homeassistant:
    container_name: homeassistant
    restart: unless-stopped
    image: ghcr.io/home-assistant/home-assistant:stable
    network_mode: host
    privileged: true
    environment:
      - TZ=Europe/Berlin
    volumes:
      - ./homeassistant_config:/config
    depends_on:
      - mosquitto
  mosquitto:
    image: eclipse-mosquitto
    network_mode: host
    volumes:
      - ./mosquitto_conf:/mosquitto/config
      - ./mosquitto_data:/mosquitto/data
      - ./mosquitto_log:/mosquitto/log

Now start homeassistant so it creates the default config files:

docker-compose up

Once you see

homeassistant    | [services.d] done.

Press Ctrl+C to abort.

Now we’ll create the Mosquitto MQTT server config file in mosquitto_conf/mosquitto.conf:

persistence true
persistence_location /mosquitto/data/
log_dest file /mosquitto/log/mosquitto.log

listener 1883
## Authentication ##
allow_anonymous false
password_file /mosquitto/config/mosquitto.passwd

Now create the mosquitto password file and fix the permissions using

touch mosquitto_conf/mosquitto.passwd
chown -R 1883:1883 mosquitto_conf

We can now start create the homeassistant mosquitto user using

docker-compose run mosquitto mosquitto_passwd -c /mosquitto/config/mosquitto.passwd homeassistant

Enter a random password that will be used for the homeassistant user

Now we can edit the homeassistant config homeassistant_config/configuration.yml. This is my config – ensure to insert the random MQTT password we used before instead of ep2ooy8di3avohn1Ahm6eegheiResh:

# Configure a default setup of Home Assistant (frontend, api, etc)
default_config:

http:
  use_x_forwarded_for: true
  trusted_proxies:
  - 127.0.0.1
  ip_ban_enabled: true
  login_attempts_threshold: 5

mqtt:
  broker: "127.0.0.1"
  username: "homeassistant"
  password: "ep2ooy8di3avohn1Ahm6eegheiResh"

# Text to speech
tts:
  - platform: google_translate

group: !include groups.yaml
automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml

Now we can start the server using

docker-compose up

You can also use our script to generate a systemd service to autostart the docker-compose config on boot:

curl -fsSL https://techoverflow.net/scripts/create-docker-compose-service.sh | sudo bash /dev/stdin

Now login to the web interface on port 8123 and configure your HomeAssistant!

Posted by Uli Köhler in Container, Docker, Home-Assistant, MQTT

How to fix rpm-ostree error: Unknown “ex” subcommand “apply-live”

When running

rpm-ostree ex apply-live

you will see the following error message in newer versions of CoreOS:

error: Unknown "ex" subcommand "apply-live"

 

 

The new equivalent of rpm-ostree ex apply-live is

rpm-ostree ex livefs --i-like-danger

 

Posted by Uli Köhler in CoreOS

How to move all OOXML (Word .docx/Excel .xlsx) files to other directory based on file content, ignoring the filename

This command will identify all OOXML files such as .xlsx or .docx in a directory recursively using the file command (looking for application/vnd.openxmlformats-officedocument MIME types) and move those to a different directory.

mkdir -p ../Documents && find . -type f -exec sh -c '
    case $( file -bi "$1" ) in (application/vnd.openxmlformats-officedocument*) exit 0; esac
    exit 1' sh {} \; -exec mv -v --backup=numbered {} ../Documents \;

 

Based on this StackExchange post. Also see How to move all images to other directory based on file content, ignoring the filename and How to move all videos to other directory based on file content, ignoring the filename and How to move all PDF files to other directory based on file content, ignoring the filename

Posted by Uli Köhler in Linux

How to move all audio files to other directory based on file content, ignoring the filename

This command will identify all audio files such as MP3s in a directory recursively using the file command (looking for audio/* MIME types) and move those to a different directory.

mkdir -p ../Audio && find . -type f -exec sh -c '
    case $( file -bi "$1" ) in (audio/*) exit 0; esac
    exit 1' sh {} \; -exec mv -v --backup=numbered {} ../Audio \;

Based on this StackExchange post. Also see How to move all images to other directory based on file content, ignoring the filename and How to move all videos to other directory based on file content, ignoring the filename

Posted by Uli Köhler in Linux

How to delete all “Apple binary property list” files from directory

In backups you often see files like

0899d5d3c7f86344a8c085a053f5ca106482e6b8: Apple binary property list
089ce36beb618daa09263be95bd70880bd974dae: Apple binary property list
08b86c8bffdf6b12a0e4bd9f6807316afac51b53: Apple binary property list

without filename extension, that are not useful when you just care about the backupped files themselves and not any Apple-related metadata.

You can remove them using

file * | grep "Apple binary property list" | cut -f1 -d: | xargs rm -v

 

Posted by Uli Köhler in Linux

How to move all videos to other directory based on file content, ignoring the filename

This command will identify all video files such as MP4s in a directory recursively using the file command (looking for video/* MIME types) and move those to a different directory.

mkdir -p ../Videos && find . -type f -exec sh -c '
    case $( file -bi "$1" ) in (video/*) exit 0; esac
    exit 1' sh {} \; -exec mv -v --backup=numbered {} ../Videos \;

Based on this StackExchange post. Also see How to move all images to other directory based on file content, ignoring the filename and How to move all audio files to other directory based on file content, ignoring the filename and How to move all PDF files to other directory based on file content, ignoring the filename

Posted by Uli Köhler in Linux

How to move all images to other directory based on file content, ignoring the filename

This command will identify all image files in a directory recursively using the file command (looking for image/* MIME types) and move those to a different directory.

mkdir -p ../Images && find . -type f -exec sh -c '
    case $( file -bi "$1" ) in (image/*) exit 0; esac
    exit 1' sh {} \; -exec mv -v --backup=numbered {} ../Images \;

 

Based on this StackExchange post. Also see How to move all audio files to other directory based on file content, ignoring the filename and How to move all videos to other directory based on file content, ignoring the filename and How to move all PDF files to other directory based on file content, ignoring the filename

Posted by Uli Köhler in Linux

How to move files from deep subdirectory structure to toplevel directory on Linux

This command line approach is rather primitive but will not overwrite files.

Run this repeatedly until all files are gone:

mv --backup=numbered **/* . && rmdir *

 

Posted by Uli Köhler in Linux

How to remove all .thumb files on the command line

find . -name "*.thumb" -type f -exec rm -v {} \;

 

Posted by Uli Köhler in Linux

How to optimize all JPG/JPEG files in a directory using jpegoptim

This is very useful in optimizing photo archives etc without changing the directory structure:

find . -name "*.jpg" -exec jpegoptim {} \;
find . -name "*.jpeg" -exec jpegoptim {} \;
find . -name "*.JPG" -exec jpegoptim {} \;
find . -name "*.JPEG" -exec jpegoptim {} \;
Posted by Uli Köhler in Linux
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Cookie settingsACCEPTPrivacy &amp; Cookies Policy