Mittwoch, 14. Dezember 2011

Bash: Converting IPs to Hostnames within a file or stream

I recently stumbled upon an interesting problem.

Imagine you have many IP addresses in a file or piped input. How to reverse DNS these entries, that is, how to substitute them with host names?

Example:

Blah;10.1.73.70:8800;10.1.73.69:8800;10.1.73.68:8800;10.1.73.67:8800;10.1.73.66:8800
Lalalala;10.1.73.70:8800;10.1.73.69:8800;10.1.73.68:8800;10.1.73.67:8800;10.1.73.66:8800;1
...

Well... took me a few hours, but once again, Perl magic to the rescue:

cat file | perl -pe 'sub rep{$host=`host $_[0]`;$host=~'s#\\n##g';$host=~'s#\(.+\ \|\.$\)##g';return $host} s#([^0-9]+)?([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)#$1.rep($2)#eg';

So, for "LALALA---8.8.8.8---BLAAAAH---4.2.2.2---LALALA" you'd get "LALALA---google-public-dns-a.google.com---BLAAAAH---vnsc-bak.sys.gtei.net---LALALA".

Cool or cool?

Keine Kommentare:

Kommentar veröffentlichen