Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux 不同用戶間複製檔案兩大實用方法(/tmp 中轉 / scp 本地傳輸)

編輯:關於 Linux

Linux 對家目錄權限嚴格,普通用戶無法直接讀寫他人家目錄。本文介紹兩種無需 root 權限即可完成跨用戶複製的方法:利用 /tmp 公共目錄中轉,或使用 scp 透過 SSH 本地傳輸。

情境

  • 用戶 foo 擁有 /home/foo/file.txt。
  • 需複製至用戶 bar 的 /home/bar/。
  • 雙方無 root 權限,且不在同一群組。

方法一:/tmp 中轉法(簡單、通用)

# 以 foo 身份
cp file.txt /tmp/

# 切換至 bar
su - bar
cp /tmp/file.txt ~/

# 退回 foo 清理
exit
rm /tmp/file.txt

為何用 cp 而非 mv? 複製到 /tmp 的檔案擁有者仍為 foo,bar 僅有讀取權限,無寫入/移動權限。即使修改權限讓 bar 可寫,移動過去擁有者仍為 foo,只有 root 能 chown。缺點是需複製兩次,耗時較久。

方法二:scp 本地傳輸法(單次傳輸、保留權限)

以 bar 身份拉取:

scp foo@localhost:/home/foo/file.txt ./
# 輸入 foo 密碼,檔案直接傳至 bar 家目錄,擁有者自動變為 bar

以 foo 身份推送:

scp file.txt bar@localhost:/home/bar/
# 輸入 bar 密碼

優點:單次傳輸、目標檔案擁有者自動為接收用戶、加密傳輸安全。前提:雙方需知道對方密碼,且 SSH 服務正常運行。

跨用戶複製示意圖

補充:其他方法

  • tar cf - file.txt | ssh bar@localhost "tar xf - -C ~/"(串流傳輸,無臨時檔)。
  • 設定 SSH 金鑰免密碼登入,自動化腳本更順暢。
  • 若有 sudo 權限:sudo -u bar cp /home/foo/file.txt /home/bar/ && sudo chown bar:bar /home/bar/file.txt。
Copyright © Windows教程網 All Rights Reserved