我有一个现有的脚本,它可以提取域的端口信息并将其存储到一个名为portscan.txt的文本文件中。示例:
portscan.txt文件:
somedomain.com:80
somedomain.com:443我只想在符合某些条件的情况下才删除这些资料。这些条件包括:
注:因此,基本上,上面提供的示例文件应该被删除,但如果有2行,我不想删除该文件,但是端口是8080或8443 (或其他端口),如下所示:
somedomain.com:8443
somedomain.com: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 ]]; then
if [[ $ports != 443 ]]; then
echo "I need to delete this"
fi
else
echo "I will NOT delete this..."
fi这是脚本的第二次呈现,我尝试嵌套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我尝试了((,因为我读到这更好地用于算术函数--这正是我认为我需要的,但当它应该是"This 和那个或那个“时,我对条件参数不那么了解。
希望这是有意义的,任何帮助都将不胜感激!
发布于 2021-11-24 16:17:43
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"如果文件有第3行,或者看到“非标准”端口,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或者,更简洁checkfile() {
(( $(wc -l < "$1") > 2 )) || grep -qv -e ':80 -e ':443或者,更简洁A3 "$1" && return 0
# delete the file
return 1
}或者,更简洁A3 -e ':443 -e ':443或者,更简洁A3 "$1" && return 0
# delete the file
return 1
}或者,更简洁
A3 "$1" } -e ':443
或者,更简洁
A3 "$1" && return 0 # delete the file return 1 }
或者,更简洁
A3
发布于 2021-11-24 16:04:40
好的,试试这个
[~/my_learning/lint]$ cat file.txt
somedomain.com:80
somedomain.com:443
[~/my_learning/lint]$ cat file_dont_delete.txt
somedomain.com:8443
somedomain.com:443
[~/my_learning/lint]$ for file in file.txt file_dont_delete.txt
do
num_of_lines=$(wc -l $file| xargs | awk '{print $1}')
port_scan=$(awk -F':' '{ if (($2 == "443") || ($2 == "80")) print "matched" }' $file | wc -l | xargs)
if [ $num_of_lines -le 2 ] && [ $num_of_lines -eq $port_scan ] ; then
echo "$file can be deleted"
else
echo "$file can't be deleted"
fi
done
# Output
file.txt can be deleted
file_dont_delete.txt can't be deleted我遵循以下条件
matching。谢谢您给我这个编写shell代码的机会。
发布于 2021-11-25 14:06:05
纯bash解决方案,封装在一个函数中,易于阅读:
#!/bin/bash
possiblyDeleteFile() {
local count=0
local rLine port
local otherPort=false
while IFS= read -r -d'' rLine; do
port="${rLine#*:}"
((count++))
if [ "$port" != 80 ] && [ "$port" != 443 ]; then
otherPort=true
fi
done < "$1"
if [ $count -le 2 ] && ! $otherPort; then
echo "Deleting file $1"
rm -- "$1"
fi
}
possiblyDeleteFile "$1"https://askubuntu.com/questions/1377370
复制相似问题