Linux – how to modify /etc/hosts from shell scripts

bashcrondomain-name-systemhosts-filelinux

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

Best Answer

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).