2014-06-06 52 views
0

我有一個shell腳本來改變IP地址(在CentOS上),而不是手動改變它。下面是該腳本:需要幫助修改一個Shell腳本來改變CentOS上的IP地址

#!/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

等。

任何機構可以讓我知道我應該如何修改腳本來添加這些細節?我的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

在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

感謝您的回答!可以請讓我知道我可以使用system-config-network-cmd -i自動化進程嗎?我的觀點是自動化流程,而不是手動配置流程。 –

+0

答案顯示的代碼可以放在shell腳本中......'system-config-network-cmd -i'在stdin上接受它的命令;請搜索「Bash Here文檔」以獲取關於它如何工作的解釋。 – 6EQUJ5

+0

我編輯了使用你的shell變量的答案,希望能夠顯示我的意思 – 6EQUJ5