使用python将来自nslookup的数据替换为CSV文件中的数据

时间:2013-01-15 02:45:48

标签: python

所以基本上我有一个像这样的CSV文件设置:

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

我需要更正此列表,以便将主机名替换为IP。我想我会让Python打开csv,然后将nslookup用于存在主机名而不是IP的行,并用该IP替换它们,并将其输出到新的更正的csv。这可能吗?

2 个答案:

答案 0 :(得分:1)

你正在做的事情通常被称为“ping扫”,并且搜索PythonPingSweeper这个术语带来了大量的点击。

我在网上找到了这个,如果我声称我写了它就会撒谎,我会在旧的DOS批处理中找到你想要的东西但Python不是我的东西:

如果我打破一些礼貌规则,请在此处附加脚本,然后默默抱怨,因为那些人​​通常抱怨没有上下文的单行URL响应。

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

答案 1 :(得分:0)

将给定文件(或stdin)的第一列中的主机名转换为ip并将结果打印到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()