我意識到這個答案很晚,考慮到你的問題在四年前問過。但是,它可能會幫助其他人。
下使用宣佈一項服務的avahi/DBUS:
import avahi
import dbus
from time import sleep
class ServiceAnnouncer:
def __init__(self, name, service, port, txt):
bus = dbus.SystemBus()
server = dbus.Interface(bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_SERVER)
group = dbus.Interface(bus.get_object(avahi.DBUS_NAME, server.EntryGroupNew()),
avahi.DBUS_INTERFACE_ENTRY_GROUP)
self._service_name = name
index = 1
while True:
try:
group.AddService(avahi.IF_UNSPEC, avahi.PROTO_INET, 0, self._service_name, service, '', '', port, avahi.string_array_to_txt_array(txt))
except dbus.DBusException: # name collision -> rename
index += 1
self._service_name = '%s #%s' % (name, str(index))
else:
break
group.Commit()
def get_service_name(self):
return self._service_name
if __name__ == '__main__':
announcer = ServiceAnnouncer('Test Service', '_test._tcp', 12345, ['foo=bar', '42=true'])
print announcer.get_service_name()
sleep(42)
使用的avahi-瀏覽以驗證它確實發佈:
[email protected]:~$ avahi-browse -a -v -t -r
Server version: avahi 0.6.30; Host name: els-mifr-03.local
E Ifce Prot Name Type Domain
+ eth0 IPv4 Test Service _test._tcp local
= eth0 IPv4 Test Service _test._tcp local
hostname = [els-mifr-03.local]
address = [10.9.0.153]
port = [12345]
txt = ["42=true" "foo=bar"]