Expect是一个免费的编程工具语言,用来实现自动和交互式任务进行通信,而无需人的干预。
使用前需要先安装expect的rpm包,centos6.5 64位上的版本是expect-5.44.1.15-5.el6_4.x86_64
另外,可扩容是建立在/是逻辑卷的前提下:
通过df -h查看磁盘信息,例如:
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/VolGroup-LogVol01 35G 9.3G 24G 29% /
tmpfs 7.8G 0 7.8G 0% /dev/shm
/dev/sda1 194M 34M 150M 19% /boot
再通过lvdisplay查看逻辑卷信息:
--- Logical volume ---
LV Path /dev/VolGroup/LogVol01
LV Name LogVol01
VG Name VolGroup
LV UUID cxD3nz-8GOa-pye4-sHYn-78yn-sCbK-OQcVCZ
LV Write Access read/write
LV Creation host, time localhost.localdomain, 2015-03-27 08:16:39 +0800
LV Status available
# open 1
LV Size 35.05 GiB
Current LE 8974
Segments 1
Allocation inherit
Read ahead sectors auto
- currently set to 256
Block device 253:0
--- Logical volume ---
LV Path /dev/VolGroup/LogVol00
LV Name LogVol00
VG Name VolGroup
LV UUID tp3pqG-VW3I-rVnD-WvZ3-MwS0-caIf-LmpeCl
LV Write Access read/write
LV Creation host, time localhost.localdomain, 2015-03-27 08:16:50 +0800
LV Status available
# open 1
LV Size 2.00 GiB
Current LE 512
Segments 1
Allocation inherit
Read ahead sectors auto
- currently set to 256
Block device 253:1
可以看到/所在逻辑卷是/dev/mapper/VolGroup-LogVol01,磁盘容量是35.05G。
假设新增的磁盘是sdb、此前系统中已经存在2个分区,以下脚本将完成分区动作,新创建的分区为sdb1:
#!/usr/bin/expect spawn fdisk /dev/sdb expect "):" send "n\n" expect "4)" send "p\n" expect ":" send "1\n" expect ":" send "\n" expect ":" send "\n" expect "):" send "p\n" expect "):" send "w\n" expect eof exit END
上述脚本执行完成后,可能需要重启系统生效。
接下来是将sdb1划入/
#!/usr/bin/expect set timeout 3600 spawn mkfs.ext4 /dev/sdb1 expect ‘override‘ sleep 5 spawn pvcreate /dev/sda3 expect ‘successfully created‘ sleep 5 spawn vgextend VolGroup /dev/sda3 expect ‘successfully extended‘ sleep 5 spawn fdisk -l /dev/sda3 set accum {} expect { {:*GB} { set accum "${accum}$expect_out(0,string)" } } puts "\n" puts "###########################################" puts "###### sda3 has $accum free space ######" puts "###########################################" puts "\n" puts "Please Type the Percentage of free space (1 to 100,defaul 100), then Type ENTER:" puts "请输入100以内的正整数,将sda3可用磁盘空间按百分比 新增给 / 使用,并以回车结束。直接回车则默认为100%:" expect_user "\n" { set raw $expect_out(buffer) # remove final carriage return set response [string trimright "$raw" "\n%"] } if {$response==""} {set response 100} puts "$response" spawn lvextend -l +$response%FREE /dev/mapper/VolGroup-LogVol01 expect ‘successfully resized‘ sleep 5 spawn resize2fs /dev/mapper/VolGroup-LogVol01 expect ‘blocks long‘ #set timeout 5 puts "Resize Complete!" exit END
上述脚本会让你输入一个数字,决定将新增磁盘多少百分比的空间扩容至/中,直接回车默认为100%。
附:expect_out用法
expect -re ".*" {}
会自动清空expect_out缓存内的内容
expect_out(buffer)输入的所有内容
expect_out(0,string)与输入内容相匹配的部分