暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

shell修改 主机IP 及 hostname

原创 楚枫默寒 2025-04-08
60

hostname_ip_set.sh (Centos6~7,Kylin)

1、自动判断IP是否合法

2、根据子网掩码位数自动计算网络掩码

#!/bin/bash
    
#==============================================================#
# File    :  hostname_ip_set.sh
# Ctime   :  2024/05/10
# Mtime   :  2025/03/26
# Version :  3.3.0
# Copyright (C) 2022-2099 
#==============================================================#
    
#字体颜色
HL='\033[37;1m'
RED='\033[31;1m'
GREEN='\033[32;1m'
YELLOW='\033[33;1m'
BLUE='\033[34;1m'
PURPLE='\033[35;1m'
AZURE='\033[36;1m'
END='\033[0m'
    
#定义的一些常量
HOST_NAME='/etc/sysconfig/network'
HOSTNAME=`hostname`
ETH0='/etc/sysconfig/network-scripts/ifcfg-eth0'
NET_HOSTNAME='/etc/hosts'
    
#IP4判断
regex="\b(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])\b"
    
menu_message() {
echo -e "${YELLOW}
1. Modify Host IP  
2. Modify Host IPV6
3. Modify Host NAME
${END}"
}
 
function get_os_info() {
    clear
    local os_file
    RULES='/etc/udev/rules.d/70-persistent-ipoib.rules'
    libc_version=$(ldd --version | head -n 1 | awk '{print $NF}' | cut -d '.' -f 2)
    # 获取 os 类型
    if [[ -e /etc/os-release ]]; then
        os_type=$(grep -oP '^ID="?(\K[^"]+|[^"]+$)' /etc/os-release)
        pretty_name=$(grep '^PRETTY_NAME=' /etc/os-release | cut -d'"' -f2)
    else
        os_file=$(if [[ -f "/etc/system-release" ]]; then echo /etc/system-release; else echo /etc/redhat-release; fi)
        os_type=$(grep -oP '^[A-Za-z]+' "$os_file")
        pretty_name=$(cat /etc/system-release)
    fi
    # 获取 os 版本
    if ((libc_version >= 12 && libc_version <= 16)); then
        os_version=6
        RULES='/etc/udev/rules.d/70-persistent-net.rules' 
    elif ((libc_version >= 17 && libc_version <= 27)); then
        os_version=7
    elif ((libc_version >= 28 && libc_version <= 33)); then
        os_version=8
    elif ((libc_version >= 34 && libc_version <= 38)); then
        os_version=9
    elif ((libc_version >= 39)); then
        os_version=10
    fi
    
    #克隆虚拟机后,获取MAC地址
    A_MAC_eth0=`cat ${RULES} | grep --color=auto 'eth0' | cut -d '"' -f 8`
    A_MAC_Current=`ifconfig | grep --color=auto 'HWaddr' | cut -b 39-55`
    
    #将MAC地址中的字母替换为小写
    MAC_eth0=`tr '[A-Z]' '[a-z]' <<<"$A_MAC_eth0"`
    MAC_Current=`tr '[A-Z]' '[a-z]' <<<"$A_MAC_Current"`
    
    #打印获取到的MAC地址
    echo "(1) Comparing MAC addresses"
    echo -e "${GREEN} $MAC_eth0 \n $MAC_Current${END}\n"
    
    #检查MAC地址是否需要修改
    if [[ $MAC_eth0 == $MAC_Current ]]; then
        echo -e "${PURPLE}MAC address does not need to be modified!${END}\n"
    elif [[ $MAC_eth0 != $MAC_Current ]]; then
        echo -e "${YELLOW}Please modify the MAC address to: ${RED}${MAC-Current}${YELLOW}!${END}"      
        echo -e "${YELLOW}The areas that need to be modified include ${RED}${ETH0}${YELLOW} and the MAC address of eth0 in ${RED}${RULES}${YELLOW}!${END}"
        #修改ifcfg-eth0中的MAC地址
        echo -e "${YELLOW}Modify the MAC address in ifcfg eth0 to ${RED}${MAC_Current}${YELLOW}...${END}"
        sed -i "2c HWADDR=${MAC_Current}" ${ETH0}
        #修改后的ifcfg-eth0
        cat ${ETH0} | grep --color=auto "HWADDR"
        echo -e "${YELLOW}MAC address modification completed in ifcfg eth0!${END}"
        #修改70-persistent-net.rules文件,将eth0的MAC地址改为eth1的
        #查看70-persistent-net.rules的信息
        #cat ${RULES} | grep --color=auto "eth0"
        echo -e "${YELLOW}modify 70-persistent-net.rules file${END}"
        sed -i '8,$c SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="'${MAC_Current}'", ATTR{type}=="1", KERNEL=="eth*", NAME="eth0"' ${RULES}
        #cat ${RULES} | grep --color=auto "eth0"
    fi
    
    #首先读取ifcfg-eth0文件
    echo -e "${GREEN}${ETH0} The content is as follows:\n\n${YELLOW}$(cat ${ETH0})${END}\n"
 
}
    
# 辅助函数:判断是否为合法 IP 地址
is_valid_ip() {
    [[ $1 =~ $regex ]]
}
    
# 函数:计算子网掩码
# 参数:IP地址, 子网掩码的位数
calculate_subnet_mask() {
    local IP=$1
    local MASK_BITS=24
 
    # 计算掩码的整数表示
    local MASK_INT=0
    for i in $(seq 1 $MASK_BITS); do
        MASK_INT=$(($MASK_INT + 2**(32-$i)))
    done
    
    # 将掩码整数转换为点分十进制格式
    local MASK_DOTTED=$(printf "%d.%d.%d.%d" \
        $(($MASK_INT >> 24 & 255)) \
        $(($MASK_INT >> 16 & 255)) \
        $(($MASK_INT >> 8 & 255)) \
        $(($MASK_INT & 255)))
 
    echo $MASK_DOTTED
}
    
function set_hostname() {
    clear
    read -p "The current host name is ${HOSTNAME},Do you want to modify it(y/n):" yn
    if [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then
        read -p "Please enter a new host name:" N_hostname
        case ${os_version} in
            6)
            sed -i '/HOSTNAME=/d' ${HOST_NAME}
            echo "HOSTNAME=${N_hostname}" >> ${HOST_NAME}
            sed -i "/$HOSTNAME/d"  ${NET_HOSTNAME}
            echo ${IP}"    "${N_hostname} >> ${NET_HOSTNAME}
            ;;
            *)
            hostnamectl set-hostname ${N_hostname}
            ;;
        esac
    fi
}
    
function set_hostip(){
    clear
    read -p "Enter IP address:" IP
    if ! is_valid_ip "${IP}"; then
        echo "IP ${IP} not available!"
        exit 1
    fi
    read -p "Enter GATEWAY address:" GATE
    if ! is_valid_ip "${GATE}"; then
        echo "GATEWAY ${GATE} not available!"
        return 1
    fi
    
    MASKIP=$(calculate_subnet_mask $IP)
    
    if [[ ${IP} ]] && [[ ${MASKIP} ]] && [[ ${GATE} ]];then
        N_IPADDR=`grep -R 'IPADDR='  ${ETH0}`
        N_NETMASK=`grep -R 'NETMASK='  ${ETH0}`
        N_GATEWAY=`grep -R 'GATEWAY='  ${ETH0}`
        sed -i "s@"${N_IPADDR}"@IPADDR="${IP}"@g" ${ETH0}
        sed -i "s@"${N_NETMASK}"@NETMASK="${MASKIP}"@g" ${ETH0}
        sed -i "s@"${N_GATEWAY}"@GATEWAY="${GATE}"@g" ${ETH0}
        echo -e "\n${GREEN}The new IP information is IP: ${IP} MASKIP: ${MASKIP} GATEWAY: ${GATE}. \n${PURPLE}Effective after restart!${END}\n"
    else
        echo -e "${RED}IP is error! ${END}\n"
    fi
}
    
function set_hostipv6(){
    clear
    read -p "Enter IPv6 address:" IPV6
    read -p "Enter GATEWAY(IPv6) address:" GATEV6
    if [[ -n ${IPV6} ]] && [[ -n ${GATEV6} ]];then
        sed -i '/IPV6/d' ${ETH0}
        echo "IPV6INIT=yes" >> ${ETH0}
        echo "IPV6_AUTOCONF=no" >> ${ETH0}
        echo "IPV6ADDR=${IPV6^^}" >> ${ETH0} 
        echo "IPV6_DEFAULTGW=${GATEV6^^}" >> ${ETH0} 
        echo "IPV6_FAILURE_FATAL=no" >> ${ETH0} 
        echo "IPV6_PRIVACY=no" >> ${ETH0} 
        echo -e "\n${GREEN}
        The new IPv6 information is 
        IPv6        : ${IPV6^^} 
        IPv6 GATEWAY: ${GATEV6^^}. \n
        ${PURPLE}Effective after restart!${END}"
    else
        echo -e "${RED}IP or GATE is error! ${END}\n"
    fi
}
    
function reboot_host(){
    clear
    read -p "Configuration completed,Do you want to restart(y/n):" yn
    if [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then
        echo -e "${PURPLE}About to restart the system...${END}"
        reboot
    elif [ "$yn" == "N" ] || [ "$yn" == "n"  ]; then
        echo -e "${PURPLE}After modifying the MAC address,Please manually restart the system...${END}"
    fi
}
    
function main(){
    clear
    while [ true ] ;do
    menu_message
    read -p "Please enter the project number(Exit menu with any key):" OP_NO
        case ${OP_NO} in 
            1)
            clear
            get_os_info
            set_hostip
            ;;
            2)
            clear
            get_os_info
            set_hostipv6
            ;;
            3)
            clear
            set_hostname
            ;;
            *)
            clear
            break 
            ;;
        esac
    done
    reboot_host
}
    
main "$@"

Shell脚本判断IP是否合法性(多种方法)

shell如何跟据IP算掩码

文章转载自楚枫默寒,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论