在 Python 中使用 SCP 協議

Manav Narula 2023年1月30日
  1. 在 Python 中使用 SCP 模組使用 SCP 協議
  2. 在 Python 中使用 subprocess.run() 函式使用 SCP 協議
在 Python 中使用 SCP 協議

SCP,安全複製協議,安全地將檔案從遠端伺服器移動到主機,反之亦然。該協議基於 SSH 協議。

SCP 協議使用此安全 shell (SSH) 通過網路安全地傳輸檔案,並從所有端點進行適當的身份驗證。

本教程將演示如何在 Python 中使用 SCP 協議共享和接收檔案。

在 Python 中使用 SCP 模組使用 SCP 協議

Python 中的 SCP 模組可以使用 SCP1 協議傳輸檔案。SCP1 協議使用 SSH1 進行單個檔案傳輸。

SCP 模組使用 Paramiko 庫通過 SSH 安全地連線遠端主機和伺服器。

讓我們看一個在 Python 中使用 SCP 上傳和檢索檔案的示例。

from paramiko import SSHClient
from scp import SCPClient

ssh_ob = SSHClient()
ssh_ob.load_system_host_keys()
ssh_ob.connect("sample.com")
scp = SCPClient(ssh_ob.get_transport())

scp.put("sampletxt1.txt", "sampletxt2.txt")
scp.get("sampletxt2.txt")
scp.put("sample", recursive=True, remote_path="/home/sample_user")

scp.close()

我們現在將分析上述程式碼中發生的事情。

我們使用 paramiko.SSHClient 類來建立到 SSH 伺服器的安全連線。scp.SCPClient 通過使用 SSH 連線的傳輸返回一個物件,該連線使用 get_transport() 函式返回。

我們使用 scp.put() 函式將檔案上傳到伺服器,並使用 scp.get() 函式檢索檔案。傳輸檔案後,我們使用 close() 函式關閉連線。

我們還可以使用 putfo() 函式通過 SCP 模組上傳類似檔案的物件。

例子:

import io
from paramiko import SSHClient
from scp import SCPClient

ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect("sample.com")
scp = SCPClient(ssh.get_transport())

f = io.BytesIO()
f.write(b"content")
f.seek(0)
scp.putfo(f, "/sample_dir/sampletxt.txt")

scp.close()
fl.close()

在上面的示例中,我們使用 io.BytesIO() 建構函式來建立記憶體中的檔案物件。我們以位元組為單位寫入了一些資料,並使用 scp.putfo() 函式將其上傳到文字檔案。

在 Python 中使用 subprocess.run() 函式使用 SCP 協議

subprocess 模組可以從 Python 程式遠端執行 bash 命令。我們可以使用 subprocess.run() 函式來執行給定的命令。

我們可以使用 SCP bash 命令通過 SSH 傳輸檔案。這可以使用前面討論的 subprocess.run() 函式來執行。

例子:

import subprocess

subprocess.run(["scp", "sample.txt", "user@server:/path/sample.txt"])

在上面的示例中,我們使用 SCP 命令傳輸了一個文字檔案。我們需要在源上生成 SSH 金鑰並預先將其安裝在目標上,以使用你的金鑰對 SCP 進行身份驗證。

subprocess.run() 函式是在 Python 3.5 中引入的。我們還可以使用其他函式來執行 SCP bash 命令,例如 subprocess.Popen()os.system() 等。

總之,我們可以通過使用 SCP 模組或從不同的功能執行 bash 命令 SCP 來將 SCP 協議與 Python 一起使用。擁有用於傳輸檔案的身份驗證所需的金鑰至關重要。

作者: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn