-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSFTP.py
More file actions
98 lines (76 loc) · 2.38 KB
/
Copy pathSFTP.py
File metadata and controls
98 lines (76 loc) · 2.38 KB
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
import paramiko
import os
def getConnect(host, port, username, password):
"""
:param host: SFTP ip
:param port: SFTP port
:param username: SFTP userName
:param password: SFTP password
:return: sftp
"""
print("SFTP connection...")
result = [1, ""]
sftp = None
try:
handle = paramiko.Transport((host, port))
handle.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(handle)
print("connection success")
except Exception as e:
sftp = None
print("connection fail, reason:{0}".format(e))
return sftp
def uploadFile(sftp, remoteDir, localPath):
"""
:param sftp:
:param remoteDir: server path
:param localPath: client path
:return:
"""
print("start upload file by use SFTP...")
result = [1, ""]
try:
try:
sftp.chdir(remoteDir)
except:
sftp.mkdir(remoteDir)
fileName = os.path.basename(localPath)
remotePath = '{0}{1}'.format(remoteDir, fileName)
sftp.put(localPath, remotePath)
result = [1, "upload " + fileName + " success"]
except Exception as e:
result = [-1, "upload fail, reason:{0}".format(e)]
print(result[1])
return result
def downloadFile(sftp, remotePath, localAbsDir):
"""
:param handle:
:param remotePath: server path
:param localAbsDir: client path
:return:
"""
print("start download file by use SFTP...")
result = [1, ""]
try:
fileName = os.path.basename(remotePath)
localAbsPath = '{0}{1}'.format(localAbsDir, fileName)
lad = os.path.split(localAbsPath)[0]
if not os.path.exists(lad):
os.makedirs(lad)
sftp.get(remotePath, localAbsPath)
result = [1, "download " + localAbsPath + " success"]
except Exception as e:
result = [-1, "download fa,il, reason:{0}".format(e)]
print(result[1])
return result
if __name__ == '__main__':
sftp = getConnect(
host="127.0.0.1",
port=22,
username='user',
password='123456'
)
print(sftp)
#uploadFile(sftp, path, path)
#downloadFile(sftp,path, path)
sftp.close()