0

所以基本上我有一个这样的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。这可能吗?

4

2 回答 2

1

您所做的通常被称为“ping 扫描”,并且在谷歌上搜索 PythonPingSweeper 一词时获得了大量点击。

我在网上找到了这个,如果我声称我写了它,我会撒谎,我做了你在旧 DOS Batch 中寻找的东西,但 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()
于 2013-01-15T02:55:25.963 回答
0

要将给定文件(或标准输入)中第一列中的主机名转换为 ip 并将结果打印到标准输出:

#!/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()
于 2013-01-15T04:51:42.980 回答