非互動方式遠程登入linux主機並更換IP地址

來源:互聯網
上載者:User

問題分析:

根據開發組同事反應,通過VCenter對RHEL6.0以下版本的系統進行複製的時候,無法使用進階選項進行IP的指定操作,從而通過CloudStack對新的執行個體指定IP也是不能實現的,而且,不能夠使用DHCP伺服器解決該問題,否則會導致新虛擬機器IP地址跟指定IP的不一致,也可能導致整個系統中IP地址分配的混亂。
解決思路:

給RHEL6.0以下系統製作的模板均指定一個固定的保留IP地址,比如192.168.3.0/24網段中,保留192.168.3.240~192.168.3.250給此類模板系統。

不管是通過VCenter複製虛擬機器還是CloudStack建立執行個體,只要是通過該固定IP地址啟動的所有虛擬機器,均會成功以原有IP地址啟動,並正常跟網段內其他IP地址通訊,需要保證同一時間不允許同一IP地址的模板同時啟動。

下文以模板固定IP為:10.196.18.250的系統,在控制節點,如cloudstackmanagement節點上面/etc/hosts中進行解析:

10.196.18.250        vm250

1.啟動vm250 ,通過檢測機制判斷其啟動成功,程式中去對10.196.18.250進行簡單的串連測試,ping 通即可。

2.在啟動執行個體的過程中,同時將IP地址資訊寫入本地目錄中,按照如下格式儲存:

假設檔案名稱為:ifcfg-eth0.001,內容為如下

DEVICE=eth0

ONBOOT=on

BOOTPROTO=static

IPADDR=10.196.28.208

NETMASK=255.255.255.0

GATEWAY=10.196.28.254

3.呼叫指令碼檔案:ChangeIP.sh ,該指令檔完成兩項任務:

【1】將ifcfg-eth0.Id 拷貝到vmId指定目錄中,重新命名為ifcfg-eth0

【2】通過cloudstack management 登陸vmId,重啟網路服務,使得新的網路設定檔生效。

使用方法:./ChangeIP.sh  id_of_ifcfg-eth0  id_of_vm

如:        ./ChangeIP.sh  001 250  ,將ifcfg-eth0.001 檔案拷貝紙vm250系統中,並重新啟動網路服務,使得新執行個體的最終IP地址為10.196.28.208

#!/bin/bash 
#description: change ip on instances
#Usage: ./ChangeIP.sh fileId vmId
# flush the caches of remote hosts
>~/.ssh/known_hosts
#define the network configfile location
dist=/etc/sysconfig/network-scripts/ifcfg-eth0
# define a function which copy the new ifcfg-eth0 file
# from cloudstack management or from other host to new
# instance boot from vm_fixip without interactive
function scp_file(){
expect -c "
set timeout -1
spawn -noecho scp $1 $2
expect "yes/no"
send \"yes\r\"
expect "password:"
send \"password\r\"
expect eof
"
}
scp_file ifcfg-eth0.$1 root@vm$2:$dist
# this function named res_new means restart network
# on new instance loading from new network config file
# without interactive
function res_net(){
expect -c "
set timeout -1
spawn -noecho ssh $1 $2
expect "password:"
send \"password\r\"
expect eof
"
}
res_net root@vm$2 "service network restart > /dev/null 2>&1 &"
sleep 2
exit 0

查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/OS/Linux/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.