python and resolving ips from a csv file.

Problem: I have a CSV file where I have source and destination IPs. I want to resolve only destination IPs.

Format of my CSV file: (let`s call it test.csv) (it`s tab separated…) 118340.86 187

The solution is pretty simple with python:

#!/usr/bin/env python
import csv
import socket

reader = csv.reader(open(“./test.csv”, “rb”), delimiter=” “)
for row in reader:
host, aliases, ips = socket.gethostbyaddr(row[1])
print row[0] + ” ” + host + ” ” + row[2] + ” ” + row[3]

First we import the necessary libs. (socket and csv)

Then we open the file to read with as a csv object. (Careful because our delimiter is not comma, but TAB)

for each row we get the second row (row[1]), convert it to host, alias and ip by gethostbyaddr method.

The last line is to create the new tab separated format. (Just pipe it to a file and you have your new CSV file. [tab separated… but oh well..])


Leave a Reply