小豹子的网络记事本

记录每一个有意思的细节

Linux - 几种方法来实现scp拷贝时无需输入密码

前言

在实际工作中,经常会将本地的一些文件传送到远程的机器上。scp是一个很好用的命令,缺点是需要手工输入密码。

如何在shell脚本中实现传输文件,而不用手工输入密码呢?接下来介绍三种方法。

 

一、建立SSH的信任关系(不推荐)

过程较繁琐,故不考虑这种情况,有兴趣可以参考博客最后给出的链接。

 

二、使用sshpass工具(推荐)

2.1 sshpass工具的安装(介绍两种方式)

先检查系统有没有sshpass

whereis sshpass

a. yum安装

yum install sshpass

b. 源码安装

sshpass安装包下载地址:https://sourceforge.net/projects/sshpass/files/

解压安装

tar -zxvf sshpass-1.06.tar.gz
cd sshpass-1.06
./configure
make
make install

 

2.2 sshpass工具的使用

测试是否安装成功

man sshpass

使用 sshpass -p password scp file user@ip:dir, 示例如下

sshpass -p oracle scp /home/oracle/single.txt oracle@192.168.56.12:/home/oracle

 

三、使用expect工具

3.1 expect工具的安装(介绍两种方式)

先检查系统有没有expect

whereis expect

a. yum安装

yum install expect

b. 源码安装

expect工具是依赖tcl的,所以也需要安装tcl

tcl安装包下载地址:https://sourceforge.net/projects/tcl/files/Tcl/8.4.19/tcl8.4.19-src.tar.gz

解压安装

tar zxvf tcl8.4.19-src.tar.gz
cd tcl8.4.19/unix  
./configure
make
make install

 

expect安装包下载地址:http://sourceforge.net/projects/expect/files/Expect/5.45/expect5.45.tar.gz

解压安装

tar -zxvf expect5.45.tar.gz
cd expect5.45
./configure --with-tcl=/usr/local/lib --with-tclinclude=../tcl8.4.19/generic
make
make install
ln -s /usr/local/bin/expect /usr/bin/expect

 

3.2 expect工具的使用  

测试是否安装成功

expect

出现下面界面就表示安装成功

expect1.1> 
expect1.1> exit

 

通过一个示例,演示如何使用expect

a.先创建一个脚本

vi test.exp

#!/usr/bin/expect
set timeout -1
spawn scp /home/oracle/single.txt oracle@192.168.56.12:/home/oracle
expect "*password:"
send "oracle\n"  #这里填远程用户的密码
expect "100%"
expect eof

b.测试运行脚本

chmod +x test.exp
expect test.exp

c.将脚本加到crontab里

crontab -e

* * * * * expect /home/oracle/test.exp &> /home/oracle/test.log

expect比sshpass用起来更复杂,但expect功能更加强大,并不仅仅适用于scp,还适用于其它很多需要交互的命令。

 

参考文档:
《几种方法来实现scp拷贝时无需输入密码》:https://blog.csdn.net/nfer_zhuang/article/details/42646849
《sshpass的安装使用》:https://blog.csdn.net/qq_30553235/article/details/78711491
《Expect工具的安装及使用方法》:https://blog.csdn.net/wangtaoking1/article/details/78268574

 

posted @ 2018-12-19 17:15  小豹子加油  阅读(931)  评论(0编辑  收藏  举报