Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
expect批量scp传输文件
1.单台传输脚本
cat /root/soft_shell/allscp.sh
#!/usr/bin/expect
if {$argc < 2} {
send_user "usage: $argv0 src_file username ip dest_file password\n"
exit
}
##set key [lindex $argv 0]
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 -i $key $src_file $username@$host_ip:$dest_file
spawn scp $src_file $username@$host_ip:$dest_file
expect {
"(yes/no)?"
{
send "yes\n"
expect "password:" {send "$password\n"}
}
"password:"
{
send "$password\n"
}
}
expect "100%"
expect eof
2.多台传输脚本
cat /root/soft_shell/mainscp.sh
#!/bin/bash
host_list="server_list.conf"
src_file=$1 #设置目标文件变量(此变量为执行命令时的第一个参数)
dest_file=$2 #设置目标文件变量(此变量为执行命令时的第二个参数)
cat $host_list | while read line
do
host_ip=`echo $line|awk '{print $1}'`
username=`echo $line|awk '{print $2}'`
password=`echo $line|awk '{print $3}'`
#src_file=`echo $line|awk '{print $4}'`
#dest_file=`echo $line|awk '{print $5}'`
##key=`echo $line|awk '{print $6}'`
./allscp.sh $key $src_file $username $host_ip $dest_file $password #调用拷贝文件shell
./dep.sh $username $host_ip $password #调用执行命令shell
done
3.服务器信息文件
cat /root/soft_shell/server_list.conf
格式为:
ip 用户名 密码 源文件 目标文件地址
执行命令脚本
#!/usr/bin/expect -f
set timeout 300
set username [lindex $argv 0]
set host_ip [lindex $argv 1]
set password [lindex $argv 2]
spawn ssh $username@$host_ip
expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "$password\r" }
}
expect -re "\](\$|#) "
send "cd /tmp && ./zabbix_install.sh\r"
expect -re "\](\$|#) "
send "exit\r"
ps:以上3个文件,相信大家都看出来了,都是放在同一文件夹下面的.我本地测试只用ssh密码,没有加上ssh key,如果要用上跟我们公司正式环境一样的安全方式(ssh密码+key,才能登录服务器),那么请自己修改脚本文件,我比较懒这里就不说得那么详细了.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.