<强>1。文件
一个文件/etc/ssh/ipblock
包含如下所示的行:
2012-01-01 12:00 192.0.2.201
2012-01-01 14:15 198.51.100.123
2012-02-15 09:45 192.0.2.15
2012-03-12 21:45 192.0.2.14
2012-04-25 00:15 203.0.113.243
<强>2。命令
命令的输出iptables -nL somechain
看起来像这样:
Chain somechain (2 references) target prot opt source destination DROP all -- 172.18.1.4 anywhere DROP all -- 198.51.100.123 anywhere DROP all -- 172.20.4.16 anywhere DROP all -- 192.0.2.125 anywhere DROP all -- 172.21.1.2 anywhere
<强>3。手头的任务
- 首先,我想获取 iptables 链(字段 4)中存在但文件中不存在的 IP 地址列表 A。
- 然后我想获取文件中存在但不在 iptables 链中的 IP 地址列表 B。
- 列表 A 中的 IP 地址应以相同的样式(日期、时间、IP)附加到文件中
- 列表 B 中的 IP 地址应添加到 iptables 链中
iptables -A somechain -d IP -j DROP
<强>4。背景
我希望扩展我的 awk-fu,所以我一直试图让它与可以在没有参数的情况下执行的 awk 脚本一起使用。但我失败了。
我知道我可以使用 getline
获取命令的输出命令,这样我就可以通过这种方式获取时间和日期。我还知道可以使用 getline foo < file
读取文件。但我曾多次尝试将这一切合并到一个可用的 awk 脚本中,但都失败了。
我意识到我可以让它与其他编程语言或 shell 脚本一起使用。但这可以通过不带参数运行的 awk 脚本来完成吗?
最佳答案
我认为这几乎正是您所寻找的。这项工作是否全部在一个文件中,我想代码几乎是不言自明的......
易于适应、可扩展...
用法:
./foo.awk CHAIN ip.file
foo.awk:
#!/usr/bin/awk -f
BEGIN {
CHAIN= ARGV[1]
IPBLOCKFILE = ARGV[2]
while((getline < IPBLOCKFILE) > 0) {
IPBLOCK[$3] = 1
}
command = "iptables -nL " CHAIN
command |getline
command |getline
while((command |getline) > 0) {
IPTABLES[$4] = 1
}
close(command)
print "not in IPBLOCK (will be appended):"
command = "date +'%Y-%m-%d %H:%M'"
command |getline DATE
close(command)
for(ip in IPTABLES) {
if(!IPBLOCK[ip]) {
print ip
print DATE,ip >> IPBLOCKFILE
}
}
print "not in IPTABLES (will be appended):"
# command = "echo iptables -A " CHAIN " -s " //use for testing
command = "iptables -A " CHAIN " -s "
for(ip in IPBLOCK) {
if(!IPTABLES[ip]) {
print ip
system(command ip " -j DROP")
}
}
exit
}
关于bash - 将文件内容与命令输出进行比较,然后执行命令并追加文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11809883/