shell-8

一、expect脚本同步文件

1、编辑同步脚本4.expect

#! /usr/bin/expect
set passwd "root1234"
spawn rsync -av [email protected]:/tmp/hk.txt /tmp                   #将131 上hk.txt 考到 本地tmp下
expect {
"yes/no" { send "yes\r" }
"password:" { send "$passwd\r" }
}
expect eof

2、给予权限

chmod a+x 4.except

3、expect eof   和 interact 

如果注释掉 expect eof,脚本执行不完就会退出,expect eof 和 interact 表示登录成功后停留一段时间,可以执行一些命令。

4、set timeout  的作用

#!/usr/bin/expect
set user [lindex $argv 0]
set host [lindex $argv 1]
set passwd "root1234"
set cm [lindex $argv 2]
spawn ssh $user@$host
expect {
"yes/no" { send "yes\r" }
"password:" { send "$passwd\r" }
}
expect "]*"
send "$cm\r"
set timeout 5                                                         #set timeout 5 设置5秒超时 ,set timeout -1 永久超时
expect "]*"
send "exit\r"

set timeout 要和 expect eof 共同作用

二、指定host和要同步的文件

1、编辑脚本5.expect

#!/usr/bin/expect
set passwd "root1234"
set host [lindex $argv 0]
set file [lindex $argv 1]
spawn rsync -av $file root@$host:$file              #$file 要写绝对路径,从本机考到131 机器
expect {
"yes/no" { send "yes\r" }
"password:" { send "$passwd\r" }
}
expect eof

2、给与权限

三、构建文件分发系统

1、编辑rsync.expect

#!/usr/bin/expect
set passwd "root1234"
set host [lindex $argv 0]
set file [lindex $argv 1]                                                            #此处的file  是一个文件列表文件 
spawn rsync -avR --files-from=$file / root@$host:/                    # 都是根目录
expect {
"yes/no" { send "yes\r" }
"password:" { send "$passwd\r" }
}
expect eof

2、创建文件列表  list.txt

/tmp/hk.txt
/opt/2.log
/root/test.txt
/root/111/ss.txt

3、创建ip.list

192.168.134.131
127.0.0.1

4、创建 rsync.sh

#!/bin/bash
for ip in `cat /opt/ip.txt`                                     #遍历IP
do
./rsync.expect $ip /opt/file.txt                          
done
5、给予权限

chmod a+x rsync.expect

 四、批量远程执行命令

1、创建 exe.expect脚本

#!/usr/bin/expect
set host [lindex $argv 0]
set passwd "root1234"
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、创建exe.sh

#!/bin/bash
for ip in `cat /opt/ip.txt`
do
./exe.expect $ip "hostname"
done

猜你喜欢

转载自www.cnblogs.com/wbjy123linux/p/8955424.html