6

I need to change some hosts entries - for example, there's a desire to update hosts to have active.vm host match the IP of currently booted VM (with some testing appliance). Guest software within VM reports machine's address back to host, and I need to update /etc/hosts based on that information - there's always some time for writing another daemon/cronjob, but wanted to use something existing for fixing hosts entries with a dumb syntax of hostname current_ip.

Someone had recommended me the bind-tools package, but - its nsupdate|host don't suit the task at all. ..

Upd: still looking for something from bind suite, but at least dynamic regeneration seems to be the best solution, and augtool is nice too.

Upd: due to my laziness, dynamic regeneration is not planned to use right now, so started using augtool at the cronjob, that reads webserver's access logs for latest IP - at the VMs which run Windows, whole monitoring solution is just a webbrowser which loads specific url from host machine and has a small reload interval

JdeBP
  • 3,970
  • 17
  • 17
kagali-san
  • 1,921
  • 5
  • 17
  • 20

2 Answers2

11

I'd rather not touch /etc/hosts in terms of parsing and such. I'd simply create a directory called /etc/hosts.d/ and make up some script that takes:

  • ip
  • name
  • aliases

creates one (1) file with one (1) line. The filename will be <ip>.host and then cat /etc/hosts.d/*host > /tmp/hosts.new && mv /tmp/hosts.new /etc/hosts. Maybe add an incron event that watches the /etc/hosts.d/ directory and regenerates /etc/hosts whenever something happens, that way you'll get rid of old entries too.

Axel Beckert
  • 398
  • 2
  • 17
Martin M.
  • 6,428
  • 2
  • 24
  • 42
9

Take a look at augeas. It has a ready-made parser/serializer for the hosts file (that's even in their quick tour guide) and comes with a simple tool to make changes (augtool).

Bobkare
  • 106
  • 1
  • hm, it's in Gentoo portage tree, so will try it.. but somehow I feel that syntax of `augtool> set /files/etc/hosts/*[alias[1] = 'active.vm']/ipaddr 1.1.1.1` will not be tolerated by it. Will test.. – kagali-san Jun 19 '11 at 19:55
  • it actually worked, but had to use `alias =` instead of addressing `alias[1]` or `alias[2]`.. it didn't supported them, so editing the entry by other than first name was impossible (not a problem, but will ask for a correct syntax on a list) – kagali-san Jun 19 '11 at 20:17
  • When you use `alias` in this expression, it matches *any* `alias` subnode, not just the firs the first one. – raphink Dec 12 '11 at 19:35
  • there's even a `brew` for it. – chovy Oct 11 '13 at 17:30