#!/usr/bin/expect set passwd "123456" spawn rsync -av root@192.168.87.132:/tmp/12.txt /tmp/ //使用rsync工具来进行文件同步,拉文件。 expect{ "yes/no" {send "yes\r"} "password: " {send "$passwd\r"} } expect eof
#!/usr/bin/expect //5.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 ##执行脚本 ./5.expect 192.168.87.132 "/tmp/12.txt" //还能够使用循环语句同步一系列文件
需求:工做中须要对web服务器进行版本更新或者文件更新,须要更新上百台服务器,这时就须要自动同步文件的功能。web
实现思路:准备一台模版机器,包含有须要分发的最新文件,使用expect脚本批量的把文件同步到目标机器上。shell
核心命令: rsync -av --files-from=list.txt / root@host:/bash
实现脚本以下:服务器
#!/usr/bin/expect //rsync.expect set passwd "123456" set host [lindex $argv 0] set file [lindex $argv 1] spawn rsync -avR --files-from=$file / root@$host:/ ##-R,若是目标机器没有多级目录,则会建立多级目录 expect { "yes/no" {send "yes\r"} "password: " {send "$passwd\r"} } expect eof ##文件列表: /tmp/list.txt :内容以下 对方机器也要有对应路径的目录,不然要使用rsync -R选项 /tmp/12.txt /tmp/shell/1.sh /etc/fst.txt /root/111/222/aaa.txt ##ip.list //目标机器的ip列表,内容以下 192.168.87.130 192.168.87.132 192.168.87.134 192.168.87.136 ##主脚本 rsync.sh:调用rsync.expect脚本 #!/bin/bash for ip in `cat /tmp/ip.list` do ./rsync.expect $ip /tmp/list.txt done ##执行主脚本 -x 查看执行过程 sh -x rsync.sh
能够使用expect脚本进行自动化执行批量的命令,提升远程机器的运维效率运维
#!/usr/bin/expect //exe.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" ##主脚本 exe.sh #!/bin/bash for i in `cat /tmp/ip.list` do ./exe.expect $ip "hostname" //执行 hostname 命令 done
也能够执行多个命令:ssh
./exe.expect $ip "w;free -m;ls /tmp/" //命令之间使用分号;间隔