简单练习使用shell编写通过scp+expect批量拷贝文件到远程服务器,以下测试环境为vmware+CentOS 5.5

使用前确定安装了expect软件,如没安装可直接通过yum安装。
 
如有以下服务器ip列表:
[root@server shell]# cat iplist.txt 
192.168.50.80
192.168.209.128
192.168.209.129
192.168.209.130
192.168.50.50

编写代码

 
  
  1. #!/bin/bash 
  2. file=$1 
  3. user=$2 
  4. passwd=$3 
  5.  
  6. if [ $# -ne 3 ]; then 
  7.         echo $"Usage: $0 file ip dst password" 
  8.         exit 1 
  9. fi 
  10. while read ip 
  11. do 
  12.  
  13. expect << END 
  14. spawn scp $file $user@$ip:/root 
  15. expect { 
  16.         "yes/no?" {send "yes\r";exp_continue} 
  17.         "password:" {send "$passwd\r"} 
  18.  
  19. expect eof 
  20.  
  21. END 
  22. done<iplist.txt 

例:拷贝文件test.tar.gz到所有服务器的/root目录下
[root@server shell]# sh sshcp.sh test.tar.gz root redhat
spawn scp test.tar.gz root@192.168.50.80:/root
root@192.168.50.80's password: 
test.tar.gz                                                     100%   87KB  86.8KB/s   00:00    
spawn scp test.tar.gz root@192.168.209.128:/root
root@192.168.209.128's password: 
test.tar.gz                                                     100%   87KB  86.8KB/s   00:00    
spawn scp test.tar.gz root@192.168.209.129:/root
root@192.168.209.129's password: 
test.tar.gz                                                     100%   87KB  86.8KB/s   00:00    
spawn scp test.tar.gz root@192.168.209.130:/root
root@192.168.209.130's password: 
test.tar.gz                                                     100%   87KB  86.8KB/s   00:00    
spawn scp test.tar.gz root@192.168.50.50:/root
root@192.168.50.50's password: 

test.tar.gz                                                     100%   87KB  86.8KB/s   00:00 

使用方法:sh sshcp.sh 拷贝文件 登录用户 密码