2024年1月21日 星期日

以 scp 指令複製檔案與目錄

Purpose:
這裡介紹如何在 Linux 系統上以 scp 指令複製檔案與目錄,並提供一些參考範例。
若要在不同的 Linux 主機之間複製檔案,最常用的方法就是使用 scp 指令,它可以透過 SSH 安全加密傳輸的方式,將本地端的檔案或目錄複製到遠端,或是將遠端的資料複製到本地端

Fundamental:
SCP(安全複製協定)是一個超好用的SSH命令列實用程式,不僅允許您在兩台電腦之間互傳檔案,還可以在檔案傳輸過程中進行加密,通常可作為遠端備份使用。

SCP檔案傳輸的命令列語法

scp [OPTION] [user@]SRC_HOST:]file1 [user@]DEST_HOST:]file2

OPTION:代表scp選項,例如密碼、SSH配置、SSH埠、限制、遞迴複製等。
[user@]SRC_HOST:]file1:您想要複製的原始檔案或者目錄。
[user@]DEST_HOST:]file2:儲存已復製的原始檔案或目錄的特定路徑。

1. 執行以下命令列即可將本機電腦中的檔案複製到遠端電腦:
scp file.txt remote_username@10.10.0.2:/remote/directory
file.txt - 想要傳輸的目標檔案的名稱
Remote_username - 遠端裝置的使用者名稱
10.10.0.2 - 將它替換為IP位址
/remote/directory - 想要將檔案複製到的目標位置(如果未提供遠端目錄,則檔案會被複製到遠端使用者的主目錄)

2. 執行以下命令列即可將遠端電腦中的檔案複製到本機電腦:
scp remote_username@10.10.0.2:/remote/file.txt /local/directory
輸入使用者名稱與密碼即可開啟傳輸檔案。

3. 若要複製整個目錄以及其下的所有檔案,則加上 -r 參數:
# 複製目錄
scp -r /path/folder1 myuser@192.168.0.1:/path/folder2

4. 保留檔案時間與權限
若要讓檔案在複製之後,還可保留原本的修改時間、存取時間與權限,可以加上 -p 參數:
# 保留檔案時間與權限
scp -p /path/file1 myuser@192.168.0.1:/path/file2

5.資料壓縮
若要將資料壓縮之後再傳送,減少網路頻寬的使用量,可以加上 -C 參數:
# 資料壓縮
scp -C /path/file1 myuser@192.168.0.1:/path/file2

6. file commands
mkdir 建立目錄(mkdir 指令)
rm 刪除檔案
rmdir 刪除或移除目錄(rmdir 指令)
檔案的權限字元為:『-rwxrwxrwx』, 這九個權限是三個三個一組的!其中,我們可以使用數字來代表各個權限,各權限的分數對照表如下:
r:4
w:2
x:1
每種身份(owner/group/others)各自的三個權限(r/w/x)分數是需要累加的,例如當權限為: [-rwxrwx---] 分數則是:
owner = rwx = 4+2+1 = 7
group = rwx = 4+2+1 = 7
others= --- = 0+0+0 = 0

 chmod 777 test

-rw-r--r--  1 mendel mendel 2355143 Jun  6  2019 project-teachable.tgz
drwxrwxrwx  2 mendel mendel    4096 Jan 21 01:36 test

7. cp [option] [source] [destination]

The source is the file or directory you want to copy, while the destination represents the location where the copy should be placed. The destination can be a directory path or a new filename if the file needs to be renamed.

Use the listed cp command options below to specify different behaviors:

OPTION DESCRIPTION
-v Displays additional information about the copying process.
-p Forces the system to preserve source file attributes (modification time, access time, user ID (UID), group ID (GID), file flags, file mode, access control lists (ACLs), and extended attributes (EAs)).
-f If the destination file/directory exists, replaces it with the source.
-i Prompts for confirmation before overwriting a file.
-r Copies all files in a directory.
-u Replaces files only if they satisfy the update condition. For example, when the destination file does not exist or when the source file is newer than the destination file.




沒有留言:

張貼留言