简体   繁体   English

删除文本文件中的ip地址并替换为python中的随机ip地址

[英]Remove ip address in a text file and replace it with the random ip address in python

import fileinput
import re
for line in fileinput.input('./log'):
    ips = re.findall(r'[0-9]+(?:\.[0-9]+){3}', line.rstrip())
    for ip in ips:
        re.sub(ip,'0.0.0.0',line.rstrip())
    print(line)

I tried this to replace ip address ith 0.0.0.0 but it dint work我试图用这个来替换 0.0.0.0 的 ip 地址,但它确实有效

So I have tested the above with a mixture of some other suggestions and the below finally worked for me所以我用其他一些建议的混合测试了上面的内容,下面的内容最终对我有用


import fileinput
import re
from random import randint

filename = '/path/to/some/dir/syslog_.log'

for line in fileinput.input(filename):
    ips = re.findall(r'src=[0-9]+(?:\.[0-9]+){3}', line.rstrip())
    print(ips)
    with fileinput.FileInput(filename, inplace=True,backup='.bak') as file:
        for line in file:
            try:
                rand_ip = 'src=' + '%d.%d.%d.%d' % (randint(0,255),randint(0,255),randint(0,255),randint(0,255))
                print(line.replace(ips[0], rand_ip), end='')
            except Exception as e:
                raise
            else:
                pass
            finally:
                pass

The original file is cleared completely but a .bak file is created with all the original data + the new generated IP's.原始文件被完全清除,但会创建一个 .bak 文件,其中包含所有原始数据 + 新生成的 IP。 also the try except is just a template that needs to be filled but this is working with large files - I have tested with 2G file. try except 也只是一个需要填充的模板,但这适用于大文件 - 我已经用 2G 文件进行了测试。

f = open('filename.txt','w')
from random import randint
# Ugly part:
str = '%d.%d.%d.%d' % (randint(0,255),randint(0,255),randint(0,255),randint(0,255))
f.write(str)
f.close()

I guess you did no researches.我猜你没有研究。 See How to Ask: https://stackoverflow.com/help/how-to-ask请参阅如何提问: https : //stackoverflow.com/help/how-to-ask

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM