expect怎么实现单台、多台服务器批量scp传输文件

2023-06-26,

本篇内容介绍了“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"
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
  ./allscp.sh $src_file $username $host_ip $dest_file $password
done

3.服务器信息文件

代码如下:

cat /root/soft_shell/server_list.conf

格式为:

代码如下:

ip 用户名 密码 源文件 目标文件地址

ps:以上3个文件,相信大家都看出来了,都是放在同一文件夹下面的.我本地测试只用ssh密码,没有加上ssh key,如果要用上跟我们公司正式环境一样的安全方式(ssh密码+key,才能登录服务器),那么请自己修改脚本文件,我比较懒这里就不说得那么详细了.

最后来张效果图吧,免得大家说我脚本有问题.

“expect怎么实现单台、多台服务器批量scp传输文件”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注本站网站,小编将为大家输出更多高质量的实用文章!