繁体   English   中英

如何检查文件中存在的子字符串?

[英]How to check sub string present in a file ?

我想用shell脚本在文件中写一些规则。 但是在添加任何规则之前,我要检查一些条件。 这是我的文件:

范例:

我写了一些规则,如:

/home/Desktop/myfile.txt

iptables -t nat -A PREROUTING -p tcp -m tcp --dport 666 -j DNAT --to-destination 192.168.19.55
iptables -t nat -A PREROUTING -p tcp -m tcp --dport 633 -j DNAT --to-destination 192.168.19.44
iptables -t nat -A PREROUTING -p tcp -m tcp --dport 656 -j DNAT --to-destination 192.168.19.88

现在,如果在添加新规则时文件包含相同的端口和IP,则脚本应该已经存在打印规则。 如果现有文件中仅存在端口,则脚本应打印已在使用的端口。 否则,我要打印成功。

那是

case 1 : if i add 666 port with 192.168.19.55 IP , the script should print rule already exist .
case 2 :  if i add 666 port with 192.168.66.55 IP , the script should print port already used  .
case 3 : otherwise script print success . 

我试图用IP和端口作为参数编写简单的shell脚本:

#!/bin/shell
if [ $# -eq 2 ] 
then
    //How to check the above conditions with file /home/Desktop/myfile.txt ??
    //Need to add this rule to the myfile.txt 
    iptables -t nat -A PREROUTING -p tcp -m tcp --dport $2 -j DNAT --to-destination $1
else
    echo "invalid arguments"
fi

您可以使用grep来检查文件的内容。 注意. 在正则表达式中是特殊的,因此我使用参数扩展将其替换为\\. 从字面上匹配点。

#!/bin/bash

config=/home/Desktop/myfile.txt

ip=$1
port=$2

if grep -q -- "--dport $port .*--to-destination ${ip//./\\.}$" "$config"; then
    echo Rule already exists. >&2
    exit 1

elif grep -q -- "--dport $port " "$config"; then
    echo Port already used. >&2
    exit 1

else
    echo iptables -t nat -A PREROUTING -p tcp -m tcp --dport $port -j DNAT --to-destination $ip
fi

这只是一个例子。 实际上,端口和目标在配置文件中的显示顺序可能不同,因此表达式会更复杂。 从仅包含给定格式(即两列,目标和端口)中包含所需信息的文件生成文件可能会更容易。

awk -v port=$1 -v ip=$2 '($11 == port && $15 == ip) { print "rule already exists"  } ($11 == port && $15 != ip) { print "Port already in use" } ($11 != port && $15 != ip) { print "success";system("iptables -t nat -A PREROUTING -p tcp -m tcp --dport "$2" -j DNAT --to-destination "$1) }' myfile.txt

使用awk,我们可以集中第11个以空格分隔的端口数据和第15个以ip地址存储的数据,并根据所传递的用于端口和IP的参数进行检查,并根据特定条件打印所需的文本,然后在iptables命令上运行成功。

暂无
暂无

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

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