본문 바로가기
DB,서버,OS 등

[linux] Bash Script 로 hosts 등록하기

by bryan.oh 2021. 9. 6.
반응형

 

아래와 같이 manage-etc-hosts.sh 를 생성하여 작성하고

#!/bin/sh

# PATH TO YOUR HOSTS FILE
ETC_HOSTS=/etc/hosts

# Hostname to add/remove.
HOSTNAME=$1

# IP FOR HOSTNAME
IP=$2

function removehost() {
    if [ -n "$(grep $HOSTNAME /etc/hosts)" ]
    then
        echo "$HOSTNAME Found in your $ETC_HOSTS, Removing now...";
        sudo sed -i".bak" "/$HOSTNAME/d" $ETC_HOSTS
    else
        echo "$HOSTNAME was not found in your $ETC_HOSTS";
    fi
}

function addhost() {
    HOSTNAME=$1
    HOSTS_LINE="$IP\t$HOSTNAME"
    if [ -n "$(grep $HOSTNAME /etc/hosts)" ]
        then
            echo "$HOSTNAME already exists : $(grep $HOSTNAME $ETC_HOSTS)"
        else
            echo "Adding $HOSTNAME to your $ETC_HOSTS";
            sudo -- sh -c -e "echo '$HOSTS_LINE' >> /etc/hosts";

            if [ -n "$(grep $HOSTNAME /etc/hosts)" ]
                then
                    echo "$HOSTNAME was added succesfully \n $(grep $HOSTNAME /etc/hosts)";
                else
                    echo "Failed to Add $HOSTNAME, Try again!";
            fi
    fi
}

실행은 첫번째 파라메터로 host, 두번째 파라메터는 실제 접속할 ip

./manage-etc-hosts.sh addhost hello-bryan.tistory.com 10.10.10.10

 

이렇게 설정한 서버에서 hello-bryan.tistory.com 을 입력하면 10.10.10.10 으로 이동함.

 

펌 : https://gist.github.com/irazasyed/a7b0a079e7727a4315b9

 

 

728x90
반응형

댓글