简体   繁体   English

如何审查Python文件中的IP地址?

[英]How to censor IP addresses in a file with Python?

I have a log file containing some Whois entries with relative IP addresses which I want to censor like: 81.190.123.123 in 81.190.xxx.xxx .我有一个日志文件,其中包含一些 Whois 条目,这些条目具有我想要审查的相对地址 IP: 81.190.123.123中的81.190.xxx.xxx

Is there a way to make such a conversion and rewrite the file contents without modifying the rest?有没有办法在不修改rest的情况下进行这样的转换并重写文件内容?

Thank you for the help!感谢您的帮助!

As mentioned above, you can do this with sed : 如上所述,您可以使用sed执行此操作:

sed -E -e 's/([0-9]+\.[0-9]+)\.[0-9]+\.[0-9]+/\1.xxx.xxx/g'

This uses a regular expression match to look for IP addresses and replace the last two octets with xxx . 这使用正则表达式匹配来查找IP地址,并用xxx替换最后两个八位字节。 Using the -i switch, you can do this all at once: 使用-i开关,您可以一次完成所有操作:

sed -i.bak -E -e 's/([0-9]+\.[0-9]+)\.[0-9]+\.[0-9]+/\1.xxx.xxx/g' file.txt

If Python is not actually one of your requirements, this also solves the problem: 如果Python实际上不是您的要求之一,这也解决了这个问题:

sed -i 's/\([0-9]\{1,3\}\)\.\([0-9]\{1,3\}\)\.[0-9]\{1,3\}\.[0-9]\{1,3\}/\1.\2.xxx.xxx/g' mylogfile.log

Or Perl, which lets you get rid of most of the ugly backslashes: 或Perl,它可以让你摆脱大多数丑陋的反斜杠:

perl -i -pe 's/(\d{1,3})\.(\d{1,3})\.\d{1,3}\.\d{1,3}/$1.$2.xxx.xxx/g' mylogfile.log

But this does not have the "inline" flag -i . 但是这没有“内联”标志-i

If you do want to use Python then use the fileinput module to process a file or files line by line. 如果您确实想使用Python,请使用fileinput模块逐行处理文件或文件。

import fileinput
for line in fileinput.input(["filename"], inplace=1, backup='.bak'):
    print processed(line)
fileinput.close()

fileinput with the inplace=1 will rename the input file and read from the renamed file while directing stdout to a new file of the same name. 使用inplace = 1的fileinput将重命名输入文件并从重命名的文件中读取,同时将stdout指向同名的新文件。 You can use the backup parameter to prevent the temporary file being deleted automatically. 您可以使用backup参数来防止临时文件被自动删除。

If the input is important you'll need to take care to handle exceptions to prevent the input being lost in case of an error. 如果输入很重要,则需要注意处理异常以防止输入在发生错误时丢失。

import re
ip = "123.456.789.123"
ip = ip[::-1]
ip = re.sub("([0-9]{1,3})", "xxx", ip, count=2)
ip = ip[::-1]

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

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