expect 分发系统
实现远程自动登录
#!/usr/bin/expect
set host "192.168.200.128" #定义变量
set passwd "123456"
spawn ssh root@$host
expect{
"yes/no" {send"yes\r";exp_continue} #\r表示回车
"password:" {send "$passwd\r"}
}
interact #登录后停留在远程主机界面
远程登录后执行指定命令并退出 #!/usr/bin/expect set user "root" set passwd "123456" spawn ssh $user@192.168.200.128 expect { "yes/no" {send "yes\r"} "password:" {send "$passwd\r"} } expect "]" #匹配root用户或者普通用的提示符 send "touch /tmp/exp.txt" #执行的命令 expect "]" send "echo test > /tmp/exp.txt\r" #执行的命令 expect "]*" send "exit\r" #退出远程主机
expect脚本参数传递
#!/usr/bin/expect set user [lindex $argv 0] #代表第1个参数 用户 set host [lindex $argv 1] #代表第2个参数 主机地址 set passwd "123456" set cm [lindex $argv 2] #代表第3个参数 执行的命令 spawn ssh $user@$host expect{ "yes/no" {send "yes\r"} "password:" {send $"passwd\r"} } expect "]" send "$cm\r" expect "]" send "exit\r" 执行格式 bash shellname root 192.168.100.100 "ls-l;w"
expect 脚本自动同步文件 #!/usr/bin/expect set passwd "123456" spawn rsync -av root@192.168.100.100:/tmp/test.txt /tmp/ #从远程主机192.168.100.100 同步文件至本机/tmp/ expect{ "yes/no" {send "yes\r"} "password:" {send "$passwd\r"} } expect eof # 不立即退出带同步结束后退出
指定host与需要同步的文件 #!/usr/bin/expect set passwd "123456" set host [lindex $avgr 0] set file [lindex $avgr 1] spawn rsync -avR $file root@$host:$file expect { "yes/no" {send "yes\r"} "password" {send"$passwd\r" } } expect eof
构建文件分发系统
核心命令 rsync -avR --files-from=filelist / /root@host:/ #文件列表分发
#!/usr/bin/expect
set passwd "123456"
set host [lindex $avgr 0]
set file [lindex $avgr 1]
spawn rsync -avR --files-from=$file / root@host:/
expect{
"yes/no" {send "yes\r"}
"password" {send "$passwd\r"}
}
expect eof
文件系统分发结合的文件与脚本
自定义 iplist
192.168.200.130
192.168.200.131
192.168.200.132
自定义 filelist
/tmp/123
/awk/132
/shell/123
定义同步脚本 rsync.sh
#!/bin/bash
for ip in cat /usr/local/sbin/ip.list
do
echo $ip
./exp6.exp $ip /usr/local/sbin/file.list #exp6.exp 为shell
done
远程批量执行命令 注:下面的列子中批量执行需要各个主机密码相同 #!/usr/bin/expect set host [lindex $argv 0] set passwd "123456" set cm [lindex $argv 1] spawn ssh root@$host expect{ "yes/no" {send"yes\r"} "password:"{send "$passwd\r"} } expect "]" send $cm\r expect "]" send "exit\r"
#!/bin/bash
for ip in cat /usr/local/sbin/ip.list
do
echo $ip
./exp7.exp $ip "w;free -m;ls"
done