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

问题描述 投票:0回答:2

我有一个 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. 启动原型
  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
2个回答
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
身份运行,它将转储现有配置。


0
投票

保持启动原型不变并更改所需字段。

IP 网络掩码 网关 DNS

对于两种 IP 配置,其余部分将使用相同的方法

© www.soinside.com 2019 - 2024. All rights reserved.