简体   繁体   中英

How do I append lines in a bash script using sed command?

The problem with my infrastructure is the SMTP server IP Address is dynamic.. I use Vyatta firewall & I'm trying to write a script which will check for the SMTP IP every 60mins and if the SMTP IP is changed it should automatically update the firewall rules (configuration)..

#!/bin/bash

SMTP=$(nslookup smtp.sendgrid.net | awk -F': ' 'NR==6 { print $2 }')
SMTP_IP=x.x.x.x

if [ $SMTP != $SMTP_IP ]
then
???
else
echo "GREEN"
fi

My Firewall rules looks like this:

    rule 979 {
        destination {
            address "Current SMTP IP"
        }
        outbound-interface bond1
        source {
            address 10.x.x.x
        }
        translation {
            address 200.x.x.x
        }
    }

I would like my script to update the firewall rules from the previous rule.. Example:

.
.
.    
rule 978 {
    destination {
        address "NEW SMTP IP"
    }
    outbound-interface bond1
    source {
        address 10.x.x.x
    }
    translation {
        address 200.x.x.x
    }
}

I'm a Network guy & have some basic knowledge in scripting. Can someone help me in solving this using a bash script ???

If I understand your question, you want to substitute one IP address for another in your rules on the "address" line under the word "destination". Something like this:

#! /usr/bin/awk -f

/destination/ { N = NR + 1 }

NR == N && /address/ && index($0, OLD_IP) {
    pos = index($0, OLD_IP)
    print substr($0, 1, pos), NEW_IP
    next
}
{ print }

We look for a line with "destination", and record the next line number. On the next line, we look for "address", and see if the old IP address appears there. If it does, we print a modified rule using the new IP address. Else just print.

Invoked as

$ awk -v OLD_IP=x.x.x.x -v NEW_IP=${SMTP} -f rules.awk firewall_rules

it should do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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