2013-01-15 62 views
0

從Nslookup的數據與文件,所以基本上我有一個CSV文件的設置是這樣的:替換CSV數據使用python

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。這可能嗎?

回答

1

你正在做的事通常被稱爲「ping掃描」,GooglePingSweeper這個詞的谷歌搜索以大量的點擊回來。

我發現這個網上,我想,如果我要求我寫的是在說謊,我做你要找什麼在老的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() 
+0

感謝輸入,但pingsweep是不是我想要的。如果我嘗試發現在線主機,服務等,我會利用pingings。我不是,我已經有一個csv文件中的設備列表。我需要將這一切以相同格式輸出到csv文件,並將主機名替換爲相應的IP,同時保留已經單獨列出的IP。 – Marq

+0

問題,你是否反對使用for/if命令來完成它?假設你的行有奇偶校驗,並且兩行文件中#8433行相同,並且所有數據都放在同一列中,你可能已經知道你可以在一行或更少行的命令行中執行此操作。 – HopeItHelps

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