简单练习使用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
编写代码
- #!/bin/bash
- file=$1
- user=$2
- passwd=$3
- if [ $# -ne 3 ]; then
- echo $"Usage: $0 file ip dst password"
- exit 1
- fi
- while read ip
- do
- expect << END
- spawn scp $file $user@$ip:/root
- expect {
- "yes/no?" {send "yes\r";exp_continue}
- "password:" {send "$passwd\r"}
- }
- expect eof
- END
- 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 拷贝文件 登录用户 密码