如何远程登录linux主机并更换IP地址

时间:2022-06-24 08:48:45

问题分析:

根据开发组同事反应,通过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 "yesr"
expect "password:"
send "passwordr"
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 "passwordr"
expect eof
"
}
res_net root@vm$2 "service network restart > /dev/null 2>&1 &"
sleep 2
exit 0