Jus*_*hek 13 command-line bash networking text-processing
我有一个现有的脚本,可以提取域的端口信息并将其存储到名为portscan.txt. 例子:
portscan.txt文件:
somedomain.com:80
somedomain.com:443
Run Code Online (Sandbox Code Playgroud)
我只想在满足某些条件时删除该信息。这些条件包括:
注意:所以基本上,上面提供的示例文件应该被删除,但如果有 2 行,但端口是 8080 或 8443(或任何其他端口),我不想删除该文件,示例如下:
somedomain.com:8443
somedomain.com:443
Run Code Online (Sandbox Code Playgroud)
不应删除此内容。
我尝试编写这个脚本,这就是我所拥有的:
#!/bin/bash
lines=$(cat portscan.txt | wc -l)
ports=$(cat portscan.txt | grep -Pv '(^|[^0-9])(80|443)($|[^0-9])')
if [[ $lines < 3 ]] && [[ $ports != 80 ]]; then
if [[ $ports != 443 ]]; then
echo "I need to delete this"
fi
else
echo "I will NOT delete this..."
fi
Run Code Online (Sandbox Code Playgroud)
这是脚本的第二次渲染,我尝试嵌套if语句,因为我无法执行如下条件:
IF portscan.txt 少于两行并且端口不是80或443
我还尝试以更简单的方式进行此操作,如下所示:
#!/bin/bash
lines=$(cat portscan.txt | wc -l)
ports=$(cat portscan.txt | grep -Pv '(^|[^0-9])(80|443)($|[^0-9])')
if [[ $lines < 3 ]] && (( $ports != 80||443 )); then
echo "I need to delete this"
else
echo "I will NOT delete this..."
fi
Run Code Online (Sandbox Code Playgroud)
我尝试过,((因为我读到这更适合与算术函数一起使用——这是我认为我需要的,但我对条件参数的 bash 不太了解,而它应该是这样的:“这个和那个或那个”。
希望这是有道理的,任何帮助将不胜感激!
checkfile() {
awk '
BEGIN {
FS = ":"
status = 1
ports[80] = 1
ports[443] = 1
}
NR == 3 || !($2 in ports) {status = 0; exit}
END {exit status}
' "$1"
}
file=portscan.txt
checkfile "$file" || echo rm -- "$file"
Run Code Online (Sandbox Code Playgroud)
如果文件有第三行,或者看到“非标准”端口,则该 awk 命令将以状态 0 退出。
如果函数返回非零(文件有 <= 2 行并且只有“标准”端口),则打印 rm 命令。
echo如果结果看起来正确,则删除。
交替:
checkfile() {
# if more than 2 lines, keep the file
(( $(wc -l < "$1") > 2 )) && return 0
# if a "non-standard" port exists, keep the file
grep -qv -e ':80$' -e ':443$' "$1" && return 0
# delete the file
return 1
}
Run Code Online (Sandbox Code Playgroud)
或者,更简洁地说
checkfile() {
(( $(wc -l < "$1") > 2 )) || grep -qv -e ':80$' -e ':443$' "$1"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1268 次 |
| 最近记录: |