Skip to content

Instantly share code, notes, and snippets.

@dymk
Created December 31, 2022 19:01
Show Gist options
  • Save dymk/d06425d932c96916f27eed9bfc5bb7cc to your computer and use it in GitHub Desktop.
Save dymk/d06425d932c96916f27eed9bfc5bb7cc to your computer and use it in GitHub Desktop.
Watch for avahi state changes, and remove the `-2` suffix from the hostname
import dbus, avahi
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib
import time
class Runner():
def __init__(self, avahi_server):
self.avahi_server = avahi_server
def on_state_change(self, state, error):
if state == avahi.SERVER_COLLISION:
print(f"[state: collision] collided, waiting 5s...")
time.sleep(5)
elif state == avahi.SERVER_RUNNING:
hostname = self.avahi_server.GetHostName()
print(f"[state: running] hostname changed: {hostname}")
if hostname.endswith("-2"):
hostname = str(hostname)[0:-2]
print(f"removing `-2` suffix: {hostname}")
self.avahi_server.SetHostName(hostname)
def main():
DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
object = bus.get_object("org.freedesktop.Avahi","/")
avahi_server = dbus.Interface(object, 'org.freedesktop.Avahi.Server')
runner = Runner(avahi_server)
avahi_server.connect_to_signal('StateChanged', runner.on_state_change)
print("Starting main loop")
loop = GLib.MainLoop()
loop.run()
if __name__ == '__main__':
main()
[Unit]
Description="Watch for avahi name collisions and try to remove the -2 suffix"
After=network.target
[Service]
ExecStart=python3 /root/avahi-suffix-remover.py
StandardOutput=journal
Environment=PYTHONUNBUFFERED=1
Restart=always
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment