Hack and / - Dynamic Config Files with Nmap

Port scans aren't just for script kiddies and network troubleshooting. You also can use them to scan your network for clients and build your server configs dynamically.
Perl to the Rescue

Once I started working on the regular expressions to parse through this output and generate the syntax I needed, I realized I should ditch vim and just write a script that built the entire configuration file for me and run that script with cron. That way, I'd never have to add a new server again. The only challenge was that I had multiple subnets I wanted to scan, and I discovered that sometimes nmap didn't resolve the IP addresses into hostnames for me. Listing 1 shows the resulting script.

Other than the hashes and a little fun with regular expressions, the bulk of this script is basic Perl. Once I tested it a few times by hand and was comfortable with it, I went ahead and copied the script into /etc/cron.daily. Of course, on my real network, I've added a few other fancy touches. For instance, every server on my network has a DNS TXT record that says what the server does. It is a useful practice for many reasons, but in this case, I found that because I used the same TXT record for similar servers, I could look it up and use that to group servers together under that heading.

Although this script worked great for Munin configs, you also could use the same procedure to scan for any number of services and build a configuration. I could see scripts that generate configuration files for Nagios, programs that poll SNMP or any other program that monitors multiple servers over a known port.

Kyle Rankin is a Systems Architect in the San Francisco Bay Area and the author of a number of books, including The Official Ubuntu Server Book, Knoppix Hacks and Ubuntu Hacks. He is currently the president of the North Bay Linux Users' Group.


Kyle Rankin is Chief Security Officer at Purism, a company focused on computers that respect your privacy, security, and freedom. He is the author of many books including Linux Hardening in Hostile Networks, DevOps Troubleshooting and The Official Ubuntu