检查是否已经使用了命令行参数



我正在尝试检查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)

如果文件不太大,则可以:

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]])在此处记录在这里。

类似:

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

otherIps包含ipFile上IP地址的list,然后您需要检查theIp是否已经在otherIps上,如果是的,请退出脚本。

最新更新