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

wribegjk  于 2023-11-18  发布在  Shell
关注(0)|答案(2)|浏览(201)

我有一个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
    1.启动
    1.网关
  2. 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


感谢您的帮助!
谢谢你,谢谢

dfddblmv

dfddblmv1#

在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运行,则会转储现有配置。

2j4z5cfb

2j4z5cfb2#

保持 Boot 原型不变,并更改所需字段。
IP子网掩码网关DNS
两种IP配置将使用相同的Rest

相关问题