簡體   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