eygle.com   eygle.com
eygle.com eygle
eygle.com  
 

« IT人物之 - 惠普CEO Mark Hurd | 文摘首页 | 数据库因ora-600[ktbair1]和ora-7445[ksmudr]宕机处理 »

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

原文链接: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


历史上的今天...

By eygle on 2009-10-01 09:19 | Comments (1) | 软件工具 | 2420 |

1 Comment

rsync 和scp 使用起来会更方便。


CopyRight © 2004~2020 云和恩墨,成就未来!, All rights reserved.
数据恢复·紧急救援·性能优化 云和恩墨 24x7 热线电话:400-600-8755 业务咨询:010-59007017-7040 or 7037 业务合作: marketing@enmotech.com