expect脚本同步文件、指定host和要同步的文件、 构建文件分发系统及批量远程执行命令

1、 expect脚本同步文件

一、vi 1.expect
内容以下:shell

#!/usr/bin/expect
set passwd "123456"
spawn rsync -av root@192.168.1.31:/tmp/12.txt /tmp/
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof  #expect eof的做用是等待脚本中的命令执行完后再退出。

二、chmod +x 1.expect
三、执行:./1.expectvim

二 expect脚本指定host和要同步的文件

一、vi 2.expect
脚本内容:bash

#!/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

二、chmod a+x 2.expect
3、本脚本只能同步一个文件.ssh

root@a shell]# touch /tmp/3.txt
[root@a shell]# ./2.expect 192.168.1.31 "/tmp/3.txt"
spawn rsync -av /tmp/3.txt root@192.168.1.31:/tmp/3.txt
root@192.168.1.31's password: 
sending incremental file list
3.txt

sent 69 bytes  received 31 bytes  66.67 bytes/sec

3、 构建文件分发系统

准备一台模板机器,把要分发的文件准备好,而后使用expect脚本批量把须要同步的文件分发到目标机器(把多个文件分发到多台机器时须要建立文件、IP列表,即本文中的list.txt、iplist.txt)。
建立 分发系统
一、建立一个文件列表文件备用:
在tmp目录下建立多个文件,要保证客户端有一样的目录。
[root@a ~]# vim /tmp/list.txt
/tmp/test1.txt
/tmp/test2.txtide

二、建立一个IP列表文件备用:ui

[root@a ~]# vim /tmp/iplist.txt
192.168.1.31 #该文件下能够指定多个IP
三、建立rsync.expect脚本:
[root@a ~]# vim rsync.expectspa

#!/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

四、给权限code

[root@a ~]# chmod a+x rsync.expect
[root@a ~]# 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.txtip

  • for ip in 'cat /tmp/iplist.txt'
  • ./rsync.expect 192.168.1.18 /tmp/list.txt
    spawn rsync -avR --files-from=/tmp/list.txt / root@192.168.1.48:/
    building file list ... done
    tmp/
    tmp/test1.txt
    tmp/test2.txt

sent 163 bytes received 53 bytes 432.00 bytes/sec
total size is 13 speedup is 0.06rem

4、 批量远程执行命令

1、建立exe.expect
[root@a ~]# 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@a ~]# chmod a+x exe.expect

[root@a ~]# vim exe.sh

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

执行:sh exe.sh

相关文章
相关标签/搜索