gpt4 book ai didi

linux - 获取动态 IP 然后 Grep 和 Echo 主机文件

转载 作者:太空狗 更新时间:2023-10-29 11:07:44 26 4
gpt4 key购买 nike

我在我们公司有一台 dns & apachi 服务器,它的 IP 地址是动态的我已经尝试执行以下操作:

#!/bin/bash
# Get the dynamic IP (dirty, I know)
IP=`host -t a mychangingip.myip.com | perl -nle '/((?:\d+\.?){4})/ && print $1' | head -n1`
# Update the hosts file
if test -n "$IP"; then
grep -v www.thesite.com /etc/hosts > /tmp/hosts
echo "$IP www.thesite.com" >> /tmp/hosts
cp /tmp/hosts /etc/hosts
fi

到目前为止这一步工作正常,但是当我尝试:

#!/bin/bash
# Get the dynamic IP (dirty, I know)
IP=`host -t a mychangingip.myip.com | perl -nle '/((?:\d+\.?){4})/ && print $1' | head -n1`
# Update the hosts file
if test -n "$IP"; then
grep -v www.thesite.com /etc/hosts > /tmp/hosts
grep -v portal.thesite.com /etc/hosts > /tmp/hosts
echo "$IP www.thesite.com" >> /tmp/hosts/
echo "$IP portal.thesite.com" >> /tmp/hosts
cp /tmp/hosts /etc/hosts
fi

它没有按预期工作,只更新了一个条目

最佳答案

替换:

grep -v www.thesite.com /etc/hosts > /tmp/hosts
grep -v portal.thesite.com /etc/hosts > /tmp/hosts

与:

grep -v www.thesite.com /etc/hosts > /tmp/hosts2
grep -v portal.thesite.com /etc/hosts2 > /tmp/hosts

或者,将这两行替换为:

grep -v 'www.thesite.com\|portal.thesite.com' /etc/hosts > /tmp/hosts

进一步简化

考虑替换这五行:

grep -v www.thesite.com /etc/hosts > /tmp/hosts
grep -v portal.thesite.com /etc/hosts > /tmp/hosts
echo "$IP www.thesite.com" >> /tmp/hosts/
echo "$IP portal.thesite.com" >> /tmp/hosts
cp /tmp/hosts /etc/hosts

用这一行:

sed -i.bak "/www.thesite.com|portal.thesite.com/ s/[^[[:space:]]*/$IP/" /etc/hosts

关于linux - 获取动态 IP 然后 Grep 和 Echo 主机文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38471681/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com