-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsftp.py
57 lines (45 loc) · 1.8 KB
/
sftp.py
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
#!/usr/bin/python
# coding=utf-8
import os
uploads = {}
downloads = {}
def uploadCallback(uploaded, total, key):
print key
progress = float(uploaded) / float(total) * 100.0
str = "已上传 %.2f" % progress + "%"
print str
def sftp_upload(host,port,username,password,local,remote):
sf = paramiko.Transport((host,port))
sf.connect(username = username,password = password)
sftp = paramiko.SFTPClient.from_transport(sf)
try:
if os.path.isdir(local):#判断本地参数是目录还是文件
for f in os.listdir(local):#遍历本地目录
a = lambda upload, total: uploadCallback(upload, total, local)
sftp.put(os.path.join(local+f),os.path.join(remote+f), callback=a)#上传目录中的文件
else:
sftp.put(local,remote)#上传文件
except Exception,e:
print('upload exception:',e)
sf.close()
def sftp_download(host,port,username,password,local,remote):
sf = paramiko.Transport((host,port))
sf.connect(username = username,password = password)
sftp = paramiko.SFTPClient.from_transport(sf)
try:
if os.path.isdir(local):#判断本地参数是目录还是文件
for f in sftp.listdir(remote):#遍历远程目录
sftp.get(os.path.join(remote+f),os.path.join(local+f))#下载目录中文件
else:
sftp.get(remote,local)#下载文件
except Exception,e:
print('download exception:',e)
sf.close()
host = 'localhost'#主机
port = 22 #端口
username = 'isan' #用户名
password = 'smart_isan' #密码
local = '/Users/isan/sftptest/local/'#本地文件或目录
remote = '/Users/isan/sftptest/remote/'
sftp_upload(host,port,username,password,local,remote)#上传
#sftp_download(host,port,username,password,local,remote)#下载