在shell脚本里使用sftp批量传送文件

转至:https://blog.csdn.net/istronger/article/details/52141530?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.edu_weight&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.edu_weight

大家对普通ftp传送文件应该不陌生,只需掌握部分命令即可完成操作。但本文要讲的是使用SFTP+批量的方式来实现传送文件。之所以采用SFTP是出于安全信任的角度考虑的,而既然是批量传送,那肯定是一次性无中断地自动传送,非交互模式的,期间无需人工干预,否则就变成手工机械传了。

      综上所述,我们接下来要实现的是免登录SFTP传送文件。实施的主要步骤如下:

1.为运行shell脚本的本地用户生成密钥对,用于免密登录

2.将其中的公钥分发到sftp欲登录的远程服务器上,实现免密登录的全信任

3.编写shell脚本

4.本地用户执行shell

一.生成密钥对

在shell脚本中使用sftp时必须用到密钥对(公钥和私钥).可使用下列方式生成(SSH 2.X版本),这里本地用户记为:local_user:

$ ssh -keygen –d (默认生成DSA密钥,不可以用于数据加解密)

屏幕提示:

Generating public/private dsa key pair.

Enter file in which to save the key (/home/local_user/.ssh/id_dsa): 

# 按回车保存为: /home/local_user/.ssh/id_dsa,即当前用户local_user的私钥

Enter passphrase (empty for no passphrase): 

# 按回车,表示读取密钥时不需要密钥的密码

Enter same passphrase again: 

# 确认密钥的密码,必须和上面的输入相同

Your identification has been saved in /home/local_user/.ssh/id_dsa.

# 私钥保存信息

Your public key has been saved in /home/local_user/.ssh/id_dsa.pub.

# 公钥保存信息

The key fingerprint is:

ec:41:e8:08:38:0b:f8:1e:bc:92:98:32:fc:d7:69:7d ...

# 密钥指纹

另:$ ssh -keygen –t rsa (生成RSA密钥,可以用于数据加解密)

二.分发公钥

为了使用密钥,必须将公钥分发到欲登录的远程服务器上,这里远程服务器记为remote_host,欲登录的远程用户记为remote_user

1. copy公钥到欲登录的远程服务器的远程用户的家目录下(若目录/home/remote_user/.ssh/不存在,请先创建之.)例如:

copy id_dsa.pub到remote_host:/home/remote_user/.ssh/

   2. 将copy来的公钥文件改名为authorized_keys(经测试这一步一定要做)

3. 修改公钥文件的访问权限

chmod 644 authorized_keys

三.批模式执行示例

目标: 从远程服务器remote_host:/home/remote_user/data/传送下列文件到本地计算机的当前目录: /home/local_user/data/:

20050201

20050202

20050203

20050204

20050205

利用sftp提供的一个选项-b,用于集中存放sftp命令(该选项主要用于非交互模式的sftp. 

因此对于上面的目标,可以生成如下的shell文件:

cd /home/remote_user/data/

lcd /home/local_user/data/

-get 20050201 

-get 20050202 

-get 20050203 

-get 20050204 

-get 20050205 

quit

这里存为: sftp_cmds.sh

说明: get命令前加一个"-"以防止其执行错误时sftp执行过程被终止.

执行脚本:

#!/bin/sh

sftp -b ./sftp_cmds.shremote_user@remote_host

四.Over

原文地址:https://www.cnblogs.com/my-first-blog-lgz/p/13589881.html