/etc/hostsファイルにdig出力を書き込むには?

/etc/hostsファイルにdig出力を書き込むには?

私はシェル初心者であり、これは例であり、実装方法がわかりません。

どんな助けでも事前にありがとう!

ステップ1:ドメイン名解決Aレコードを取得しますdig

dig @8.8.8.8 liveproduseast.akamaized.net +short | tail -n1

ステップ2:取得したIPアドレスとドメイン名を以下のように1行にまとめます。

23.1.236.106 liveproduseast.akamaized.net

ステップ3:ファイルの最後の行に追加します/etc/hosts

127.0.0.1  localhost loopback
::1        localhost
23.1.236.106 liveproduseast.akamaized.net

ステップ4:ジョブを自動化し、6時間ごとに実行するように設定します。解析されたIPが変更されたら、ファイルに更新します/etc/hosts(以前に追加したIPを置き換えます)。

crontab -e
6 * * * * /root/test.sh 2>&1 > /dev/null

ベストアンサー1

1つの方法は、古いIPを新しいIPに置き換えることです。

$ cat /root/test.sh
#!/bin/sh

current_ip=$(awk '/liveproduseast.akamaized.net/ {print $1}' /etc/hosts)
new_ip=$(dig @8.8.8.8 liveproduseast.akamaized.net +short | tail -n1 | grep '^[.0-9]*$')

[[ -z $new_ip ]] && exit

if sed "s/$current_ip/$new_ip/" /etc/hosts > /tmp/etchosts; then
    cat /tmp/etchosts > /etc/hosts
    rm /tmp/etchosts
fi

sed部分でGNUを使用している場合は、単に次のことができます。

sed -i "s/$current_ip/$new_ip/" /etc/hosts

またはすでにmoreutilsインストールされている場合

sed "s/$current_ip/$new_ip/" /etc/hosts | sponge /etc/hosts

説明する

grep '^[.0-9]*$'IPアドレスをキャプチャし、そうでない場合は何も印刷しません。

awk '/liveproduseast.akamaized.net/ {print $1}' /etc/hosts

「liveproduseeast.akamaized.net」を含む行を見つけて、最初の列であるIPを取得します。

sed "s/what to replace/replacement/" file

置き換える内容の最初の項目を代替値に置き換えます。

これを行うことができないことは注目に値します。

sed "s/what to replace/replacement/" file > file

詳細は:https://stackoverflow.com/questions/6696842/how-can-i-use-a-file-in-a-command-and-redirect-output-to-the-same-file-without-t

おすすめ記事