脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python使用sftp实现传文件夹和文件

Python使用sftp实现传文件夹和文件

2021-10-16 10:08白天丶 Python

这篇文章主要为大家详细介绍了Python使用sftp实现传文件夹和文件,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

利用python的sftp实现文件上传,可以是文件,也可以是文件夹。

版本python2.7.13 应该不用pip安装更多的插件,都是自带的

不多说 上代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# -*- coding:utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import paramiko
import os
 
_xfer_file = 'file'
_xfer_dir  = 'dir'
 
class mainwindow(object):
    # 构造方法
    def __init__(self, arg):
        # 超类调用
        super(mainwindow, self).__init__()
 
        # 赋值参数[字典]
        # 参数格式 arg = {'ip':'填ip','user':'用户名','password':'密码','port':22}
        self.arg = arg
        # 赋值参数[ftp]
        self.sftp = none
 
        # 调试日志
        print self.arg
 
 
    # 启动程序
    def startup(self):
        # 连接ftp
        if self.sftp != none:
            print u'您已经成功连接了'
        tmpstr = u'开始连接...用户名:'+self.arg['user']+u'  密码:'+self.arg['password']+' ip:'+self.arg['ip']+u' 端口:'+str(self.arg['port'])
        print tmpstr
        try:
            transport = paramiko.transport((self.arg['ip'], self.arg['port']))
            transport.connect(username=self.arg['user'], password=self.arg['password'])
            self.sftp = paramiko.sftpclient.from_transport(transport)
            print (u'连接成功 '+self.arg['ip'])
        except exception as e:
            print u'连接失败:'+str(e)
 
    # 关闭程序
    def shutdown(self):
        # 关闭ftp
        if self.sftp:
            self.sftp.close()
            print '### disconnect sftp server: %s!'%self.arg['ip']
            self.sftp = none
 
    # 处理上传
    def upload(self, source, target, replace):
        ### 操作数据
        # 来源路径
        source = source.replace('\\', '/')
        # 目标路径
        target = target.replace('\\', '/')
 
 
        ### 验证数据
        if not os.path.exists(source):
            print u'来源资源不存在,请检查:' + source
            return
 
 
        ### 格式数据
        # 格式化目标路径
        self.__makepath(target)
 
 
        ### 处理数据
        # 文件媒体数据(文件类型, 文件名称)
        filetype, filename = self.__filetype(source)
        # 判断文件类型
        if filetype == _xfer_dir:
            # 1.目录
            self.uploaddir(source, target, replace)
        elif filetype == _xfer_file:
            # 2.文件
            self.uploadfile(source, filename, replace)
 
 
    # 传送目录
    def uploaddir(self, source, target, replace):
        ### 验证数据
        # 判断目录存在
        if not os.path.isdir(source):  
            print u'这个函数是用来传送本地目录的'
            return
 
        ### 处理数据
        # 遍历目录内容,上传资源
        for file in os.listdir(source):
            # 资源路径
            filepath = os.path.join(source, file)
 
            # 判断资源文件类型
            if os.path.isfile(filepath):
                # 1.文件
                self.uploadfile(filepath, file, replace)
            elif os.path.isdir(filepath):
                # 2.目录
                try:
                    self.sftp.chdir(file)
                except:
                    self.sftp.mkdir(file)
                    self.sftp.chdir(file)
                self.uploaddir(filepath, file, replace)
 
        ### 重置数据
        # 返回上一层目录
        self.sftp.chdir('..')
 
    # 传送文件
    def uploadfile(self, filepath, filename, replace):
        ### 验证数据
        # 验证文件类型
        if not os.path.isfile(filepath):
            print u'这个函数是用来传送单个文件的'
            return
        # 验证文件存在
        if not os.path.exists(filepath):
            print u'err:本地文件不存在,检查一下'+filepath
            return
        # 验证ftp已连接
        if self.sftp == none:
            print u'sftp 还未链接'
            return
 
 
        ### 处理数据
        # 判断文件存在是否覆盖
        if not replace:
            if filename in self.sftp.listdir():
                print u'[*] 这个文件已经存在了,选择跳过:' + filepath + ' -> ' + self.sftp.getcwd() + '/' + filename
                return
        # 上传文件
        try:
            self.sftp.put(filepath, filename)
            print u'[+] 上传成功:' + filepath + ' -> ' + self.sftp.getcwd() + '/' + filename
        except exception as e:
            print u'[+] 上传失败:' + filepath + ' because ' + str(e)
 
 
    # 获得文件媒体数据({文件/目录, 文件名称})
    def __filetype(self, source):
        # 判断文件类型
        if os.path.isfile(source):
            # 1.文件
            index = source.rfind('/')
            return _xfer_file, source[index+1:]
        elif os.path.isdir(source): 
            # 2.目录
            return _xfer_dir, ''
 
 
    # 创建目标路径
    # 说明: 目标路径不存在则依次创建路径目录
    def __makepath(self, target):
        # 切换根目录
        self.sftp.chdir('/')
 
        # 分割目标目录为目录单元集合
        data = target.split('/')
        # 进入目标目录, 目录不存在则创建
        for item in data:
            try:
                self.sftp.chdir(item)
                print u'要上传的目录已经存在,选择性进入合并:' + item
            except:
                self.sftp.mkdir(item)
                self.sftp.chdir(item)
                print u'要上传的目录不存在,创建目录:' + item
 
 
 
 
if __name__ == '__main__':
    # """
    # 先熟悉一下sftp有哪些用法  sftp.listdir(可以传参可以为空) 返回当前目录下清单列表
    # mkdir 创建目录对应rmdir   sftp.put(本地路径,远程要存的文件名) chdir进入子目录
    # """
    arg = {'ip':'填ip','user':'填用户名','password':'填密码','port':22}
 
    me  = mainwindow(arg)
    me.startup()
    # 要上传的本地文件夹路径
    source = r'e:\xampp\backup\mysql\cto'
    # 上传到哪里 [远程目录]
    target = r'/home/www/cto/wp-superdo/backup/db'
    replace = false
 
    me.upload(source, target, replace)
    me.shutdown()
 
 
 
def main(source, target, replace=false):
    arg = {'ip':填ip,'user':填用户名,'password':填密码,'port':22}
 
    me  = mainwindow(arg)
    me.startup()
 
    me.upload(source, target, replace)
    me.shutdown()

因为python2.7对中文的支持不是很好所以如果出现中文错误
修改一下 python27\lib\site-packages\paramiko\py3compat.py

Python使用sftp实现传文件夹和文件

还有

Python使用sftp实现传文件夹和文件

最后上一下执行结果

Python使用sftp实现传文件夹和文件

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/qq_15682489/article/details/72400055

延伸 · 阅读

精彩推荐