[英]How to check sub string present in a file ?
I want to write some rules in a file with a shell script . 我想用shell脚本在文件中写一些规则。 But Before adding any rule i want to check some conditions . 但是在添加任何规则之前,我要检查一些条件。 This is my file: 这是我的文件:
Example : 范例:
i wrote some rule like : 我写了一些规则,如:
/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
Now if the file contains same port and IP at the time of adding new rule , the script should print rule exist already . 现在,如果在添加新规则时文件包含相同的端口和IP,则脚本应该已经存在打印规则。 If only port present in the existing file , script should print port already in use . 如果现有文件中仅存在端口,则脚本应打印已在使用的端口。 Otherwise , i want to print success . 否则,我要打印成功。
that is 那是
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 .
I tried to write simple shell script with arguments as IP and port: 我试图用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
You can use grep
to check the contents of the file. 您可以使用grep
来检查文件的内容。 Note that .
注意.
is special in regular expressions, so I used parameter expansion to replace it with \\.
在正则表达式中是特殊的,因此我使用参数扩展将其替换为\\.
that matches the dot literally. 从字面上匹配点。
#!/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
This is just an example. 这只是一个例子。 In reality, port and destination might appear in different order in the config file, so the expressions would be more complex. 实际上,端口和目标在配置文件中的显示顺序可能不同,因此表达式会更复杂。 It might be easier to generate the file from a file that only contains the required information in a given format (ie two columns, destination and port). 从仅包含给定格式(即两列,目标和端口)中包含所需信息的文件生成文件可能会更容易。
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.