本文系统CentOS6.0
1.方法1:简便方法
upload ()
{
/usr/bin/expect << EOD
spawn bash -c "scp -r /tmp/log1/* [email protected]:/tmp/log2"
for {} {1} {} {
"*(yes/no)?" { send "yes/n"; continue }
"*assword:" { send "password/n"; continue }
-re . { exp_continue }
eof { break }
}
EOD
}
由于expect和bash的关键字不一样,所以使用bash -c进行关键字转换,否则会出现找不到文件的提示。
2.方法2,用于密码又特殊字符的情况
TMP_EXPECT_FILE="/tmp/test_scp$$"
LOCAL_IP=`grep "IP" $(cd "$(dirname "$0")";pwd)/TEMP_IPFILE | awk -F"=" '{print $2}'`
#generate expect
echo '#!/usr/bin/expect
set LOCAL_IP [lindex $argv 0]
set REMOTE_IP [lindex $argv 1]
set CP_FILE [lindex $argv 2]
set REMOTE_DIR [lindex $argv 3]
set USER [lindex $argv 4]
set PASSWD [lindex $argv 5]
set timeout 5
set timeout -1 用于无限时间
spawn scp -o BindAddress=$LOCAL_IP -o "RSAAuthentication no" -o "PublicKeyAuthentication no" $CP_FILE$USER@$REMOTE_IP:$REMOTE_DIR
expect {
"*Connection refuse*" { exit 1 }
"*yes/no*" { send "yes/n";exp_continue }
*assword*" { send "$PASSWD/n" }
}
expect {
"*assowrd*" { send "PWSSWD/n"; exp_continue }
"*:~*" { exit 0 }
"*denied*" { exit 1 }
"*try again*" { exit 1 }
"*Last login:*" { exit 0 }
}
expect timeout { exit 1}
expect eof
' > ${TMP_EXPECT_FILE}
chmod u+x ${TMP_EXPECT_FILE} || return 1
expect -d -f "${TMP_EXPECT_FILE}" "$LOCAL_IP" "$REMOTE_IP" "$CP_FILE" "$REMOTE_DIR" "$USER" "$PASSWD" 2>&1 >> $LOG
return $?
Expect是Unix系统中用来进行自动化控制和测试的软件工具,由Don Libes制作,作为Tcl脚本语言的一个扩展,应用在交互式软件中如telnet,ftp,Passwd,fsck,rlogin,tip,ssh等等。该工具利用Unix伪终端包装其子进程,允许任意程序通过终端接入进行自动化控制;
1、安装
1 yum install expect expect-devel -y
2、编写Script
#!/usr/bin/expect
if {$argc < 2} {
send_user "usage: $argv0 src_file username ip dest_file password\n"
exit
}
set src_file [lindex $argv 0]
set username [lindex $argv 1]
set host_ip [lindex $argv 2]
set dest_file [lindex $argv 3]
set password [lindex $argv 4]
spawn scp -r $src_file $username@$host_ip:$dest_file
expect {
"(yes/no)?"
{
send "yes\n"
expect "*assword:" {send "$password\n"}
}
"*assword:"
{
send "$password\n"
}
}
expect "100%"
expect eof
3、用法实例:
[root@master ~]# ./allscp.sh install.log root 192.168.100.145 /tmp/ 123456
你也可以使用其他帐号;
上面实现了对单台机器复制;
4、批量服务器复制
#!/bin/bash
src_file=$1
username=$2
host_list=$3
dest_file=$4
password=$5
cat $host_list | while read line
do
host_ip=`echo $line | awk '{print $1}'`
./allscp.sh $src_file $username $host_ip $dest_file $password
done
用法实例:
希望大家有更好的介意~
推荐阅读:
批量scp脚本——从多台机器拷贝文件 http://www.linuxidc.com/Linux/2013-06/86034.htm
Linux scp 和 SSH 命令 http://www.linuxidc.com/Linux/2013-03/80645.htm
Linux系统常用的cpio命令及scp命令 http://www.linuxidc.com/Linux/2013-01/77719.htm
Linux cp scp命令使用 http://www.linuxidc.com/Linux/2012-12/76840.htm
Linux服务器 scp 不需要密码配置 http://www.linuxidc.com/Linux/2012-12/75886.htm