scp脚本免输入密码(利用expect解释器)

expect交互:

spawn启动指定进程(发送命令) -> expect获取指定关键字 -> send发送回应 -> 执行完成 -> 继续或退出

1.先贴脚本

主要是做远程创建目录,然后将本地文件或文件夹scp上传(指定服务器传输,免输入密码)

./scp.sh port host username password src_file desk_file

#!/usr/bin/expect
set timeout 10

# if {[llength $argv] != 6} {
    # puts "参数不全!"
    # exit 1
# }

set port [lindex $argv 0]
set host [lindex $argv 1]
set username [lindex $argv 2]
set password [lindex $argv 3]
set src_file [lindex $argv 4]
set dest_file [lindex $argv 5]


#创建目录
spawn ssh -p $port $username@$host "mkdir -p $dest_file"

expect {
    "(yes/no)?" {
        send "yes\n"
        exp_continue	
    }
    "*assword:" {
        send "$password\n"
    }
}
#scp传输
spawn scp -P $port $src_file $username@$host:$dest_file


expect {
    "(yes/no)?" {
        send "yes\n"
        exp_continue
    }
    "*assword:" {
        send "$password\n"
    }
}

expect {
    "100%" {
        exp_continue
    }
    eof
}

2.安装expect

yum安装

yum install -y tcl
yum install -y expect

源码安装

下载

依赖tcl:

https://www.tcl.tk/software/tcltk/download84.html

expect:

https://sourceforge.net/projects/expect/files/

解压

tar -zxvf tcl8.4.20-src.tar.gz
tar -zxvf expect5.45.3.tar.gz

安装tcl

cd tcl8.4.20/unix/
./configure --prefix=/usr/tcl --enable-shared
make
make install
cp tclUnixPort.h ../generic

安装expect

cd /root/expect5.45.3/
./configure --prefix=/usr/expect --with-tcl=/usr/tcl/lib --with-tclinclude=/root/tcl8.4.20/generic
make
make install
ln -s /usr/tcl/bin/expect /usr/bin/expect

写入环境变量

1、vi /etc/profile
# 写入下面内容内容
2、export PATH=$PATH:/usr/bin/
# 更新配置文件
3、source  /etc/profile

简单测试

[root@zhangsan ~]# expect
expect1.1> send "hello world\n"
hello world

安装成功!放心食用

如果执行脚本报错,那有可能是脚本编码不是uinx,需转换一下

可以使用 dos2unix 命令来将脚本文件转换为 UNIX 格式,这将删除 Windows 换行符并使其在 Linux 上能够正确解释

dos2unix scp.sh

如果 dos2unix 命令不可用,你也可以使用 sed 命令来去除 \r

sed -i 's/\r$//' scp.sh

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

糕手慕辰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值