1、expect脚本同步文件web
自动同步文件 ,把远程的文件同步到本机shell
cd /usr/local/sbin
vim
1.脚本内容:bash
#!/usr/bin/expect
set passwd "123456"
spawn rsync -av root@192.168.136.134:/tmp/12.txt /tmp/ssh
expect {
"yes/no" { send "yes\r" }
"password:" { send "$passwd\r" }
}ide
expect eof测试
(使用expect eof 会在登陆后停留一会再退出,若是不添加这行或者interact,则登陆后立马退出)spa
2.编写完脚本后,修改脚本权限:orm
chmod a+x syn.expect图片
3.执行脚本:
./syn.expect
2、expect脚本指定host和要同步的文件
指定host和要同步的文件:(从本机到远程)
脚本内容:
#!/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
#!/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
2.修改脚本权限:chmod a+x syn_1.expect
3.执行脚本:
./rsy_1.expect 192.168.136.134 "/tmp/test.com.log"
(第一个参数是主机,第二个参数是要同步的文件)
3、构建文件分发系统
首先要有一个要同步的文件列表和一个同步机器的ip列表:
1.建立同步文件列表:
vim /tmp/list.txt
/tmp/12.txt
/root/111/4913
....
(文件中是写要同步的本机同步文件路径(绝对路径),要同步的文件的路径在对方机器上要有,不然要在同步命令中加上-R。rsync -avR)
2.建立同步机器ip列表(由于实际中远程同步的机器不止一台)
vim /tmp/ip.list
192.168.136.134
192.168.136.136
...
在这些同步的机器,这里测试是保证它们的密码都是同样的。不然就是要每一个主机登录
密码都要设定。或者设定密钥认证,这样就能够省略脚本中输入密码的那行内容:"password:" { send "$passwd\r" }
3.建立脚本:
vim /usr/local/sbin/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
(rsync -avR 这个-R选项能使同步机器不存在的文件路径级联建立)
编写完脚本要修改权限 chmod a+x /usr/local/sbin/rsync.expect
4.建立一个shell脚本去执行expect脚本内容:
vim /usr/local/sbin/rsync.sh
rsync.sh 内容
#!/bin/bash
for ip in `cat /tmp/ip.list`
do
echo $ip
./rsync.expect $ip list.txt
done
5.执行shell脚本
sh -x /usr/local/sbin/rsync.sh
4、批量远程执行命令
1.expect脚本内容:vim /usr/local/sbin/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"
2.编写shell执行expect脚本
vim /usr/local/sbin/exe.sh
#!/bin/bash
for ip in `cat /tmp/ip.list`
do
echo $ip
./exe.expect $ip "w;free -m;ls /tmp"
done
执行w;free -m;ls /tmp命令