expect生产环境案例

expect生产环境案例

5.1 实现自动交互的脚本
[root@G ~]# vim zd.exp
#!/usr/bin/expect
if { $argc != 2 } {
puts "usage: expect $argv0 ip command"
exit
}
#
set ip [lindex $argv 0]
set cmd [lindex $argv 1]
set password "666666"
#
spawn ssh root@$ip $cmd
expect {
"yes/no" {send "yes\r";exp_continue} &> /dev/null
"*password" {send "$password\r"} &> /dev/null
}
expect eof
脚本后加上ip和命令
[root@G ~]# expect zd.exp 192.168.4.5 uptime
spawn ssh root@192.168.4.5 uptime
root@192.168.4.5's password:
05:15:09 up 15 min, 2 users, load average: 0.00, 0.00, 0.00


5.2 利用for循环查看多台
现有2台服务器,需要用管理机去查看

ip地址 主机名 角色
     
192.168.4.4 G 管理机
192.168.4.5 b1 被管理机
192.168.4.6 b2 被管理机



[root@G ~]# vim pl.sh
#!/bin/bash
if [ $# -ne 1 ];then
echo $"USAGE:$0 cmd"
exit 1
fi
cmd=$1
for n in 5 6
do
expect zd.exp 192.168.4.$n "$cmd"
done

[root@G ~]# sh pl.sh uptime
spawn ssh root@192.168.4.5 uptime
root@192.168.4.5's password:
01:00:21 up 36 min, 2 users, load average: 0.00, 0.00, 0.00
spawn ssh root@192.168.4.6 uptime
root@192.168.4.6's password:
01:00:21 up 35 min, 2 users, load average: 0.00, 0.00, 0.00


5.3 免交互发送文件
[root@G ~]# vim scpfile.exp
#!/usr/bin/expect
if { $argc != 3 } {
puts "usage: expect $argv0 file host dir"
exit
}
#
set file [lindex $argv 0]
set host [lindex $argv 1]
set dir [lindex $argv 2]
set password "666666"
spawn scp -rp -P22 $file root@$host:$dir
expect {
"yes/no" {send "yes/r";exp_continue}
"*password" {send "$password\r"}
}
expect eof

发送文件
[root@G ~]# expect scpfile.exp abc 192.168.4.6 /root/
spawn scp -rp -P22 abc root@192.168.4.6:/root/
root@192.168.4.6's password:
查看发送结果
[root@G ~]# expect zd.exp 192.168.4.6 ls
spawn ssh root@192.168.4.6 ls
root@192.168.4.6's password:
abc
anaconda-ks.cfg
install.log
install.log.syslog


5.4 利用shell循环批量发送文件
[root@G ~]# vim scpfile.sh
#!/bin/bash
if [ $# -ne 2 ];then
echo $"USAGE:$0 file dir"
exit 1
fi
#
file=$1
dir=$2
for n in 5 6
do
expect scpfile.exp $file 192.168.4.$n $dir
done

[root@G ~]# sh scpfile.sh wangluyu /root/
spawn scp -rp -P22 wangluyu root@192.168.4.5:/root/
root@192.168.4.5's password:
spawn scp -rp -P22 wangluyu root@192.168.4.6:/root/
root@192.168.4.6's password:

上一篇:shell入门(五)


下一篇:shell expect 拷贝文件夹有问题