【问题标题】:Need help to modify a Shell Script to change ip addresses on CentOS需要帮助来修改 Shell 脚本以更改 CentOS 上的 IP 地址
【发布时间】:2014-07-27 06:10:46
【问题描述】:

我有一个 shell 脚本来更改 IP 地址(在 CentOS 上),而不是手动更改它。这是脚本:

#!/bin/bash
# changeip.sh

usage(){
    clear
    echo "Usage: $0 newip"
    echo "Example: $0 127.0.0.1"
    exit 1
}

new_ip_value=$1
local_ip_value=$(ifconfig eth0|awk '/inet addr/ {split ($2,A,":"); print A[2]}')

# call usage() function if filename not supplied
    [[ $# -eq 0 ]] && usage


echo "/etc/hosts"
echo "----------------------------------------------------------"
sed -ie 's/'$local_ip_value'/'$new_ip_value'/g' /etc/hosts
sed 's/'$local_ip_value'/'$new_ip_value'/g' /etc/hosts
echo ""
echo "/etc/sysconfig/network-scripts/ifcfg-eth0"
echo "----------------------------------------------------------"
sed -ie 's/'$local_ip_value'/'$new_ip_value'/' /etc/sysconfig/network-scripts/ifcfg-eth0
sed 's/'$local_ip_value'/'$new_ip_value'/' /etc/sysconfig/network-scripts/ifcfg-eth0
echo "The IP of $local_ip_value has successfully been changed to $new_ip_value."
service network restart

exit

我需要添加更多参数,例如:

  1. BOOTPROTO
  2. 开机
  3. 网关
  4. DNS1

等等。

任何人都可以让我知道我应该如何修改脚本以添加这些细节吗?我的 ifcfg-eth0 最终应该是这样的:

# vi /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE="eth0"
BOOTPROTO=none
NM_CONTROLLED="yes"
ONBOOT=yes
TYPE="Ethernet"
IPADDR=192.168.1.2
GATEWAY=192.168.1.1

感谢任何帮助!

谢谢!

【问题讨论】:

    标签: bash shell networking centos


    【解决方案1】:

    在 CentOS 上更改 IP 地址的更好方法是使用system-network-config-cmd 工具。

    例如:

    #!/bin/bash
    
    # Shell script input parsing here
    
    system-config-network-cmd -i <<EOF
    DeviceList.Ethernet.eth0.type=Ethernet
    DeviceList.Ethernet.eth0.BootProto=static
    DeviceList.Ethernet.eth0.OnBoot=True
    DeviceList.Ethernet.eth0.NMControlled=True
    DeviceList.Ethernet.eth0.Netmask=192.168.1.255
    DeviceList.Ethernet.eth0.IP=${new_ip_value}
    DeviceList.Ethernet.eth0.Gateway=192.168.1.1
    ProfileList.default.ActiveDevices.1=eth0
    EOF
    
    service network stop
    service network start
    

    如果您以system-config-network-cmd -e 运行,它将转储现有配置。

    【讨论】:

    • 感谢您的回答!请让我知道我可以使用 system-config-network-cmd -i 自动化该过程吗?我的重点是自动化流程,而不是手动配置。
    • 答案显示了您可以放入 shell 脚本的代码...system-config-network-cmd -i 在标准输入上接受其命令;搜索“Bash Here Document”以了解其工作原理。
    • 我编辑了答案以使用你的 shell 变量,希望能说明我的意思
    • 再次感谢您的回复!我现在的理解是,将配置放在一个文件中,比如 config.sh 并运行它。运行脚本后,它会要求我输入我想要的静态 IP 地址。如果我错了,请纠正我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多