Python實作遠程檔案傳輸(socket) (paramiko)
環境
Python 3.7.4
socket
paramiko==2.7.1
CentOS Linux release 8.1.1911 (Core)
實作代碼
<host name>為遠程計算機主機名(云服務器公網IP),<port>為埠號,云服務器默認為22,使用其他埠需要到安全組配置放開埠,<user name>為登錄用戶名,阿里云默認為root,<public key path>為登錄云服務器的密鑰檔案路徑
import os
import paramiko
class SCPTransmitter():
```
Description:
upload local files to remote server or download remote file to local dirctory by Secure Copy and SSH File Transfer Protocol
Attributes:
None
```
def __init__(self):
self.hostname = '<host name>'
self.port = <port>
self.username = <user name>
self.public_key = paramiko.RSAKey.from_private_key_file('<public key path>')
self.scp = paramiko.Transport(self.hostname, self.port)
self.scp.connect(username=self.username, pkey=self.public_key)
self.sftp = paramiko.SFTPClient.from_transport(self.scp)
```
Description:
download remote files from remote server
Args:
remote_path:
remote dirctory of files wanna download
local_path:
local path to save files
Returns:
None
```
def download(self, remote_path, local_path):
try:
remote_files = self.sftp.listdir(remote_path)
for file in remote_files:
local_file = local_path + file
print(local_file)
remote_file = remote_path + file
print(remote_file)
self.sftp.get(remote_file, local_file)
print("Successfully")
except IOError:
return ("remote_path or local_path is not exist")
```
Description:
upload local files to remote server
Args:
remote_path:
remote dirctory to save files
local_path:
local directory of files wanna upload
```
def upload(self, remote_path, local_path):
try:
local_files = os.listdir(local_path)
print(local_files)
for file in local_files:
local_file = local_path + file
print(local_file)
remote_file = remote_path + file
print(remote_file)
self.sftp.put(local_file, remote_file)
print("Successfully")
except IOError:
return ("remote_path or local_path is not exist")
if __name__ == "__main__":
remote_path = '/home/remote/'
local_path = './res/remote/'
transmitter = SCPTransmitter()
transmitter.upload(remote_path, local_path)
最后
- 由于博主水平有限,不免有疏漏之處,歡迎讀者隨時批評指正,以免造成不必要的誤解!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/167068.html
標籤:其他
下一篇:雙螺旋式艾默生流量計的作業特點
