2016-12-18 39 views
0

我試圖檢查IP地址(參數)的反向查找。然後將結果寫入txt文件。 如何檢查IP地址(參數)是否已經在文件中註冊?如果是這樣,我需要擺脫腳本。檢查命令行參數是否已被使用

我的腳本:

import sys, os, re, shlex, urllib, subprocess 

cmd = 'dig -x %s @192.1.1.1' % sys.argv[1] 

proc = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE) 
out, err = proc.communicate() 

# Convert to list of str lines 
out = out.decode().split('\n') 

# Only write the line containing "PTR" 
with open("/tmp/test.txt", "w") as f: 
for line in out: 
    if "PTR" in line: 
     f.write(line) 
+0

「你在文件中註冊」是什麼意思? – 2ps

+0

@ 2ps:我認爲OP意味着IP存在於他正在寫內容的文件中 –

+0

腳本將挖掘結果寫入txt文件。我想檢查參數IP是否寫入日誌中。如果是這樣,我需要擺脫腳本 – OmZ

回答

0

喜歡的東西:

otherIps = [line.strip() for line in open("<path to ipFile>", 'r')] 
theIp = "192.168.1.1" 
if theIp in otherIps: 
    sys.exit(0) 

otherIps包含IP地址的上ipFile一個list,那麼你需要檢查是否theIp已經在otherIps,如果是的話,退出腳本。

1

如果文件不是太大,你可以這樣做:

with open('file.txt','r') as f: 
    content = f.read() 
if ip in content: 
    sys.exit(0) 

現在,如果該文件是大,你要避免可能出現的內存問題,您可以使用mmap像這樣:

import mmap 
with open("file.txt", "r+b") as f: 
    # memory-map the file, size 0 means whole file 
    mm = mmap.mmap(f.fileno(), 0) 
    if mm.find(ip) != -1: 
     sys.exit(0) 

mmap.find(string[, start[, end]])有詳細記錄here