天天看点

远程登录linux主机更换IP地址【非交互】

根据开发组同事反应,通过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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

<code>#!/bin/bash</code>

<code>#description: change ip  on instances</code>

<code>#Usage: ./ChangeIP.sh fileId vmId</code>

<code># flush the caches of remote hosts</code>

<code>&gt;~/.</code><code>ssh</code><code>/known_hosts</code>

<code>#define the network configfile location</code>

<code>dist=</code><code>/etc/sysconfig/network-scripts/ifcfg-eth0</code>

<code># define a function which copy the new ifcfg-eth0 file</code>

<code># from cloudstack management or from other host to new</code>

<code># instance boot from vm_fixip  without interactive</code>

<code>function</code> <code>scp_file(){</code>

<code>expect -c "</code>

<code>set</code> <code>timeout -1</code>

<code>spawn -noecho </code><code>scp</code> <code>$1 $2</code>

<code>expect </code><code>"yes/no"</code>

<code>send \"</code><code>yes</code><code>\r\"</code>

<code>expect </code><code>"password:"</code>

<code>send \"password\r\"</code>

<code>expect eof</code>

<code>"</code>

<code>}</code>

<code>scp_file   ifcfg-eth0.$1        root@vm$2:$dist</code>

<code># this  function named res_new means restart network</code>

<code># on new instance  loading from new network config file</code>

<code># without interactive</code>

<code>function</code> <code>res_net(){</code>

<code>spawn -noecho </code><code>ssh</code>  <code>$1 $2</code>

<code>res_net  root@vm$2 </code><code>"service network restart &gt; /dev/null 2&gt;&amp;1 &amp;"</code>

<code>sleep</code> <code>2</code>

<code>exit</code> <code>0</code>

<code></code>

本文转自 暗黑魔君 51CTO博客,原文链接:http://blog.51cto.com/clovemfong/1272062,如需转载请自行联系原作者

继续阅读