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

网友投稿 792 2022-10-24

本站部分文章、图片属于网络上可搜索到的公开信息,均用于学习和交流用途,不能代表睿象云的观点、立场或意见。我们接受网民的监督,如发现任何违法内容或侵犯了您的权益,请第一时间联系小编邮箱jiasou666@gmail.com 处理。

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

原文链接:

http://bbs.chinaunix.net/archiver/tid-508290.html

主要步骤如下:

1.为运行shell脚本的本地用户生成密钥对

2.将其中的公钥分发到sftp欲登录的远程服务器上

3.编写并以上面的本地用户运行shell脚本

一.生成密钥对

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

$ ssh-keygen -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 ...

# 密钥指纹

二.分发公钥

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

1.copy公钥到欲登录的远程服务器的远程用户的家目录下,例如:

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

若目录/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

方式1: 批模式

sftp提供了一个选项-b,用于集中存放sftp命令(该选项主要用于非交互模式的sftp).因此对于上面的目标,可以生成如下的命令文件:

cd /home/remote_user/data/

lcd /home/local_user/data/

-get 20050201 .

-get 20050202 .

-get 20050203 .

-get 20050204 .

-get 20050205 .

quit

这里存为: sftp_cmds.txt

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

以下为脚本示例:

#!/bin/sh

sftp -b ./sftp_cmds.txt remote_user@remote_host

方式二:

#!/bin/sh

sftp remote_user@remote_host << EOF

cd /home/remote_user/data/

lcd /home/local_user/data/

-get 20050201 .

-get 20050202 .

-get 20050203 .

-get 20050204 .

-get 20050205 .

quit

EOF

上一篇:有品日报 | 麦瑞克/麦酷酷获融资;网易投资剧本杀;维密与中国供应商成立合资企业;YIN隐推出烎虎礼盒
下一篇:中国代工厂吞下维密
相关文章

 发表评论

暂时没有评论,来抢沙发吧~