Python实现远程文件传输

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)

最后

  • 由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!
  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值