Python: Append and remove A record with dnspython

This article will describe appending A record to zone file and removing A record from zone file with dnspython.

1 Install dnspython

Install python-dnspython package in case of Ubuntu. Install python-dns package in case of CentOS.

$ sudo apt install -y python-dnspython # Ubuntu
$ sudo yum install -y python-dns       # CentOS

Install dnspython with pip in case of the distribution which has no package for dnspython.

$ sudo pip install dnspython

2 Append A record to zone file

The following script will append A record to zone file.

$ cat dns-append-example.py
#!/usr/bin/env python

import os

import dns.rdataset
import dns.rdtypes.IN.A
import dns.zone

conf = 'example.zone'
hostname = 'foobar'
ipaddr = '192.168.11.250'


def append():
    zone = dns.zone.from_file(conf, os.path.basename(conf))
    rdataset = zone.find_rdataset(hostname, dns.rdatatype.A, create=True)
    rdata = dns.rdtypes.IN.A.A(dns.rdataclass.IN, dns.rdatatype.A, ipaddr)
    rdataset.add(rdata, 86400)
    zone.to_file(conf)


append()
  • dns.zone.from_file creates zone object from zone file.
  • zone.find_rdataset finds rdataset object which has 'foobar' as hostname. If not exist, rdataset object will be created.
  • rdata object has A record which has 192.168.11.250 as IP address. rdata object can have other record like NS record.
  • Write zone object to zone file.

zone file is as below.

$ cat example.zone
$TTL 86400

@ IN SOA my.net root.my.net (
  2017021902
  3600
  900
  604800
  86400
)

@ IN NS ubuntu-16.04

Run python script.

$ python dnspython-append-example.py

A record is appended.

$ cat example.zone
@ 86400 IN SOA my.net root.my.net 2017021902 3600 900 604800 86400
@ 86400 IN NS ubuntu-16.04
foobar 86400 IN A 192.168.11.250

3 Remove A record from zone file

The following script will remove A record from zone file.

$ cat dnspython-remove-example.py
#!/usr/bin/env python

import os

import dns.rdataset
import dns.rdtypes.IN.A
import dns.zone

conf = 'example.zone'
hostname = 'foobar'


def remove():
    zone = dns.zone.from_file(conf, os.path.basename(conf))
    zone.delete_rdataset(hostname, dns.rdatatype.A)
    zone.to_file(conf)


remove()
  • zone.delete_rdataset remove rdataset object which has 'foobar' as hostname.

zone file is as below.

$ cat example.zone
@ 86400 IN SOA my.net root.my.net 2017021902 3600 900 604800 86400
@ 86400 IN NS ubuntu-16.04
foobar 86400 IN A 192.168.11.250

Run python script.

$ python dnspython-remove-example.py

A record is appended.

$ cat example.zone
@ 86400 IN SOA my.net root.my.net 2017021902 3600 900 604800 86400
@ 86400 IN NS ubuntu-16.04