2017-07-25 71 views
0

我想用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 
+0

試試'man grep'來學習如何使用'grep'。 – choroba

+0

可疑的設計,因爲你必須處理無盡的文件操作和字符串處理。想想另外一種方法:你可以在數據庫中維護所有規則來簡化維護,因爲你可以處理結構化數據而不是全面規則的字符串表示。而且你實現了一個「應用」功能,將數據庫的內容轉儲到所述文件中,所以採用單向方式而不是雙向處理。 – arkascha

+0

所以我應該將所有規則複製到一個文件並搜索特定的端口? –

回答

0

您可以使用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 

這只是一個例子。實際上,端口和目標可能在配置文件中以不同的順序出現,所以表達式會更復雜。從只包含給定格式所需信息的文件(即兩列,目的地和端口)生成文件可能更容易。

+0

grep -F「固定字符串」避免轉義元字符 –

+0

@NahuelFouilleul:不幸的是,有'。*'。當然,你可以將'grep -F'管道到'grep'。 – choroba

+0

謝謝。它工作正常 –

0
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,我們就可以集中精力分隔片數據的端口和15日針對IP地址的第11屆空間,並檢查它,根據一定的端口和IP打印所需的文本傳遞的參數條件並在成功時運行iptables命令。

相關問題