淺析Suse中的sftp批量傳送文件
我學習Suse經(jīng)常的遇到一些問題,喜歡總結(jié)一下,就這樣知識就慢慢的積累起來了,前兩天我想傳一些文件,可在Suse中我不會去操作,于是我上網(wǎng)找了一下,就學會了在shell腳本里使用sftp批量傳送文件,希望看完本文之后你能過學會在shell腳本里使用sftp批量傳送文件。
主要步驟如下:
1.為運行shell腳本的本地用戶生成密鑰對
2.將其中的公鑰分發(fā)到sftp欲登錄的遠程服務器上
3.編寫并以上面的本地用戶運行shell腳本
一.生成密鑰對
在shell腳本中使用sftp時必須用到密鑰對(公鑰和私鑰).可使用下列方式生成(SSH 2.X版本),這里本地用戶記為:local_user:
$ ssh-keygen –d
屏幕提示:
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 ...
# 密鑰指紋
二.分發(fā)公鑰
為了使用密鑰,必須將公鑰分發(fā)到欲登錄的遠程服務器上,這里遠程服務器記為remote_host,欲登錄的遠程用戶記為remote_user
1.copy公鑰到欲登錄的遠程服務器的遠程用戶的家目錄下,例如:
copy id_dsa.pub到remote_host:/home/remote_user/.ssh/
若目錄/home/remote_user/.ssh/不存在,請先創(chuàng)建之.
2.將copy來的公鑰文件改名為authorized_keys
3.修改公鑰文件的訪問權(quán)限
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命令前加一個"-"以防止其執(zhí)行錯誤時sftp執(zhí)行過程被終止.
以下為腳本示例:
#!/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
這樣你就完成了在shell腳本里使用sftp批量傳送文件的所有步驟,希望你能學好Suse。
【編輯推薦】