简体   繁体   中英

Replace Data in CSV File with data from nslookup using python

So basically I have a CSV file setup like this:

IP or HostName, Device Name,  Device Description
10.10.10.10,    Device A,     Firewall
10.10.10.11,    Device B,     Firewall
10.10.10.12,    Device C,     Firewall
VBHOST12C,      Device D,     VM

I need to correct this list so that the hostname is replaced with an IP. I figured I would have Python open the csv, then utilize nslookup for the lines where there is a hostname instead of an IP, and replace them with that IP, and output it to a new corrected csv. Is this possible?

What you're doing is commonly called a "ping sweep" and googling for the term PythonPingSweeper came back with a ton of hits.

I found this online, I would be lying if I claimed I wrote it, I do what you're looking for in old DOS Batch but Python aint my thing:

If I'm breaking some rules of courtesy be appending the script here then complain in silence since those are the same people that usually gripe about single line URL responses without context.

https://gist.github.com/4404340

#!/usr/bin/python

import time
import subprocess
import socket


class CannotResolve(Exception):
  pass


def resolve(host):
  start = time.time()
  try:
    ip = socket.gethostbyname(host)
  except Exception, e:
    import traceback
    traceback.print_exc()
    raise CannotResolve("Cannot resolve %s: %s" % (host, e))
  else:
    end = time.time()
    return (ip, (end-start)*1000)


def ping(host):
  cmd = ['ping', '-c', '1', host]
  start = time.time()
  try:
    p = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
    so, se = p.communicate()

  except Exception:
    # On error, return 0
    print "Error running %s" % cmd
    print "stderr:\n%s" % se
    return 0

  else:
    end = time.time()
    return (end-start)*1000


class Connection(object):
  def __init__(self, host, port):
    self.host = host
    self.port = port

  def connect(self):
    retries = 10

    for x in range(retries):
      try:
        self.sock = socket.socket()
        self.sock.connect( (self.host, self.port) )

      except Exception:
        import traceback
        traceback.print_exc()
        print "Retry %s" % (x+1)
        time.sleep(1)
      else:
        return True

      print "Giving up after %s attempts" % retries

  def send(self, msg):
    print "Send: %r" % msg
    self.connect()
    retries = 10
    for x in range(retries):
      try:
        self.sock.sendall(msg)
      except Exception:
        import traceback
        traceback.print_exc()
        print "Retry %s" % (x+1)
        time.sleep(1)
      else:
        return True
    print "Giving up after %s attempts" % retries


def main():
  delay = 1

  hosts = ["google.com", "stackoverflow.com"]

  conn = Connection('127.0.0.1', 2003)
  while True:
    for h in hosts:
      now = int(time.time())

      hostname = socket.gethostname()

      print "Resolving %s" % h
      try:
        ip, speedms = resolve(h)
      except CannotResolve, e:
        print "Cannot resolve", e
        # Zero values
        conn.send(
          "pings.%s.dns_%s %s %d\n" % (
            hostname, h.replace(".", "_"), 0, now))
        conn.send(
          "pings.%s.ping_%s %s %d\n" % (
            hostname, h.replace(".", "_"), 0, now))

        continue # Next host

      else:
        conn.send(
          "pings.%s.dns_%s %s %d\n" % (
            hostname, h.replace(".", "_"), speedms, now))


      now = int(time.time())
      print "Pinging %s (%s)" % (ip, h)
      p = ping(h)
      print "done"

      conn.send(
        "pings.%s.ping_%s %s %d\n" % (
          hostname, h.replace(".", "_"), p, now))

      time.sleep(delay)


if __name__ == '__main__':
  main()

To convert hostname in the first column in given files (or stdin) to ip and print the result to stdout:

#!/usr/bin/env python
import csv
import fileinput
import socket
import sys
from multiprocessing import Pool

def ip(row):
    try:
        row[0] = socket.gethostbyname(row[0])
    except EnvironmentError:
        pass # return row as is if can't resolve address
    return row

def main():
    pool = Pool(20) # use concurrent connections
    rows = pool.imap(ip, csv.reader(fileinput.input()))
    csv.writer(sys.stdout).writerows(rows)

if __name__=="__main__":
    main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM