Jan 31, 2020 - Update A record for domain using OVH API

Comments

Update A record for domain using OVH API

I recently noticed that the external IP of my broadband connection doesn’t actually change very often, once every one or two months. So I figured I could just point one of my domains to my ‘home server’; no need to use a ‘dynamic DNS’ provider.

If you use the ‘Pong script’ which I posted earlier, then this Python script can update the A record of your domain’s nameserver to point to your current external IP address, given that you use the OVH nameservers. Just call it with a cron job.

Note: You need install python-ovh:

pip install python-ovh

And you need to generate API access keys for the script: https://eu.api.ovh.com/createToken/

For this step be careful to grant three permissions:

GET /domain/zone/<YOUR DOMAIN>/record
GET /domain/zone/<YOUR DOMAIN>/record/*
PUT /domain/zone/<YOUR DOMAIN>/record/*

And here’s the script:

import json
import ovh
import sys
import socket
import re


DOMAIN = "example.com"
OVH_ENDPOINT = "ovh-eu"
OVH_APP_KEY = ""
OVH_APP_SEC = ""
OVH_CON_KEY = ""

# Using https://floki.blog/2019/10/netcat_pong
# (adjust get_current_ip() method if you're using
# something else)
PONG_HOST = "External IP"
PONG_PORT = 12345


def get_current_ip():
    """
    Get the current external IP using the 'PONG_HOST'.
    :return: See above
    """
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((PONG_HOST, PONG_PORT))
    data = s.recv(1024)
    s.close()
    new_ip = data.decode("utf-8").strip()
    if not re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$").match(new_ip):
        raise Exception("Could not get current IP")
    return new_ip

def get_current_arecord_ip(client):
    """
    Get the current IP and record ID which is set in the
    A record of the nameserver for the domain
    :param client: The OVH API client
    :return: (record_id, ip) tuple
    """
    path = "/domain/zone/{}/record".format(DOMAIN)
    result = client.get(path,
                        fieldType='A',
                        subDomain='' # you can use a subdomain too
                        )

    if len(result) != 1:
        raise Exception("Could not get current A record IP")

    record_id = result[0]
    path = "/domain/zone/{}/record/{}".format(DOMAIN,record_id)
    result = client.get(path)
    return record_id, result['target']

def update_arecord(client, record_id, ip):
    """
    Update the A record with the given ID with the provided IP
    :param client: The OVH API client
    :param record_id: The ID of the A record
    :param ip: The IP to update the record with
    :return:
    """
    path = "/domain/zone/{}/record/{}".format(DOMAIN,record_id)
    result = client.put(path,
                        target=ip
                        )

def main():
    ip = get_current_ip()

    client = ovh.Client(
        endpoint=OVH_ENDPOINT,
        application_key=OVH_APP_KEY,
        application_secret=OVH_APP_SEC,
        consumer_key=OVH_CON_KEY,
    )
    record_id, old_ip = get_current_arecord_ip(client)

    if ip != old_ip:
        print("Updating A record to IP {}".format(ip))
        update_arecord(client, record_id, ip)
    else:
        print("No update required")


if __name__ == "__main__":
    main()

Jan 9, 2020 - Using sed to edit config files

Comments

Using sed to edit config files

If you have a script which installs something, you often also want to automatically adjust a config file after installation. You can use the unix tool ‘sed’ for that.

Here are some examples, which assume that you have a parameter called ‘Test’ in the config file which is set to a value using ‘=’ character, e.g. test.conf

# This is some fake config file
Test = 123

Now you can use ‘sed’ to comment that line out, in or change the value:

# comment out
sed -i -e '/^[[:blank:]]*Test/ s/^#*/#/' test.conf

# comment in
sed -i -e '/^[[:blank:]]*#[[:blank:]]*Test/ s/^[[:blank:]]*#*//' test.conf

# set the value to 'abc'
sed -i -e '/^[[:blank:]]*Test[[:blank:]]*=/ s/=.*/= abc/' test.conf

With the ‘-i’ option the file is edited in-line. If you don’t use it the (modified) file content is printed out on the command line; good for testing.

The ‘[[:blank:]]’ fields are included so that the expression also works for messy config files, where you could have things like

  #  Test
Test    =123
   Test    = 123
# etc.

Dec 27, 2019 - Raspberry PI - Get started

Comments

Raspberry PI - Get started

Default tasks when setting up a new Raspberry PI.

Get Raspbian

Download from raspberrypi.org

Transfer it onto the SD card

Plug in the SD card and run fdisk -l to find out which device it is. If it is mounted, unmount it umount /dev/sdc1 I assume for now it is /dev/sdc. You have to use yours, make sure to get this right!!

Then write the image to the SD card:

dd if=2019-09-26-raspbian-buster-full.img of=/dev/sdc bs=512k

Setup Wifi and SSH before the first boot

Most often you don’t want to connect a keyboard and monitor. You just want plug it in the power socket somewhere and get going. Therefore you need to setup Wifi and enable the SSH server before you boot it up.

Simply remove the SD card and put it back in again. Then the /boot partition of the card should get mounted.

Run wpa_passphrase YOUR_SSID and note the output. Then create the file wpa_supplicant.conf in the boot parition and adjust it accordingly:

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country="Two letter country code, e.g. GB"

network={
    ssid="Your SSID"
    psk="Your PASSWORD"
}

Enable the SSH server by creating an empty file ssh in the boot partition.

Umount the SD card partitions again, put the card into the Raspberry Pi and start it up.

Change the password

Run nmap -sn 192.168.1.0/24 to find out the IP address of the Pi. Then log in with the default password which is ‘raspberry’: ssh pi@192.168.1.xxx

And change it: passwd

Update system

sudo apt update
sudo apt upgrade

Install X2Go (optional)

If you also want to use the desktop, install the X2Go server.

Create the file /etc/apt/sources.list.d/x2go.list:

# X2Go Repository (release builds)
deb http://packages.x2go.org/raspbian buster main
# X2Go Repository (sources of release builds)
deb-src http://packages.x2go.org/raspbian buster main

Add the key:

sudo apt-key adv --recv-keys --keyserver keys.gnupg.net E1F958385BFE2B6E

Install:

sudo apt update && sudo apt install x2goserver x2goserver-xsession

Start x2goserver and enable it at boot time:

sudo systemctl start x2goserver
sudo systemctl enable x2goserver

Install the client on your PC accordingly, the package is called x2goclient. Then you can remotely log into the desktop running on the Raspberry Pi. The default Raspbian desktop image comes with the ‘LXDE’ desktop. You can skip the ‘Setup’ tasks which pop up on the first desktop login, you’ve already done them.