需要帮助修改Shell脚本以更改CentOS上的IP地址

时间:2014-06-06 03:56:42

标签: bash shell networking centos

我有一个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. ONBOOT
  3. GATEWAY
  4. DNS1
  5. 等等。

    任何机构都可以让我知道我应该如何修改脚本来添加这些细节吗?我的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
    

    感谢任何帮助!

    谢谢!

1 个答案:

答案 0 :(得分: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运行,则会转储现有配置。