标签:expect
expect脚本同步文件[root@centos7-3 shell]# vi 1.expect
#!/usr/bin/expect
set passwd "123456"
spawn rsync -av root@192.168.1.83:/tmp/12.txt /tmp/
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof
[root@centos7-3 shell]# chmod +x 1.expect
执行:
说明: expect eof的作用是等待脚本中的命令执行完后再退出。
[root@centos7-3 shell]# vi 2.expect
#!/usr/bin/expect
set passwd "123456"
set host [lindex $argv 0]
set file [lindex $argv 1]
spawn rsync -av $file root@$host:$file
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof
[root@centos7-3 shell]# chmod a+x 2.expect
[root@centos7-3 shell]# touch /tmp/3.txt
[root@centos7-3 shell]# ./2.expect 192.168.1.83 "/tmp/3.txt"
spawn rsync -av /tmp/3.txt root@192.168.1.83:/tmp/3.txt
root@192.168.1.83‘s password:
sending incremental file list
3.txt
sent 69 bytes received 31 bytes 66.67 bytes/sec
注: 本脚本只能同步一个文件。
首先要有一台模板机器,把要分发的文件准备好,然后只要使用expect脚本批量把需要同步的文件分发到目标机器即可(把多个文件分发到多台机器时需要创建文件、IP列表,即本文中的list.txt、iplist.txt)。
创建 分发系统
创建一个文件列表文件备用:
[root@test ~]# vim /tmp/list.txt
/tmp/12.txt
/tmp/3.txt
#该文件下可以添加多个文件
注意:此处要保证客户端有同样的目录。
创建一个IP列表文件备用:
[root@test ~]# vim /tmp/iplist.txt
192.168.1.83
#该文件下可以指定多个IP
创建rsync.expect脚本:
[root@test ~]# vim rsync.expect
#!/usr/bin/expect
set passwd "123456"
set host [lindex $argv 0]
set file [lindex $argv 1]
spawn rsync -avR --files-from=$file / root@$host:/
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
#expect eof
[root@test ~]# chmod a+x rsync.expect
[root@test ~]# vim rsync.sh
#!/bin/bash
for ip in `cat /tmp/iplist.txt`
do
./rsync.expect $ip /tmp/list.txt
done
执行:
sh -x rsync.sh
++ cat /tmp/iplist.txt
+ for ip in ‘`cat /tmp/iplist.txt`‘
+ ./rsync.expect 192.168.1.48 /tmp/list.txt
spawn rsync -avR --files-from=/tmp/list.txt / root@192.168.1.48:/
building file list ... done
tmp/
tmp/12.txt
tmp/3.txt
sent 163 bytes received 53 bytes 432.00 bytes/sec
total size is 13 speedup is 0.06
创建exe.expect
[root@test ~]# vim exe.expect
#!/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"
[root@test ~]# chmod a+x exe.expect
[root@test ~]# vim exe.sh
#!/bin/bash
for ip in `cat /tmp/iplist.txt`
do
./exe.expect $ip "hostname"
done
执行:
sh exe.sh
expect脚本同步文件、expect脚本指定host和要同步的文件、构建文件分发系统、批量远程执行
标签:expect
原文地址:http://blog.51cto.com/jacksoner/2074185