-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathftp-client.py
More file actions
285 lines (220 loc) · 7.03 KB
/
ftp-client.py
File metadata and controls
285 lines (220 loc) · 7.03 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
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import socket
import threading
import os
import sys
import pdb
from lib2to3.fixer_util import String
import cmd
ftp_client_default_port = 7712
class ftp_data_thread(threading.Thread):
def __init__(self, cmd, filename):
self.dataPort = 6548
self.sock = socket.socket()
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(("127.0.0.1", self.dataPort))
self.sock.listen(1)
self.sock.settimeout(1)
self.cmd = cmd
self.filename = filename
self.current_dir = os.path.abspath("./ftp-downloads/")
threading.Thread.__init__(self)
def run(self):
try:
self.dataConn, addr = self.sock.accept()
except:
return
if self.cmd == "list":
self.list()
elif self.cmd == "retr":
self.retr()
elif self.cmd == "stor":
self.stor()
else:
print('Unhandled data thread command')
def list(self):
print("\nReceiving file list\n")
total_payload = "" # Concatenate list of files
data = str(self.dataConn.recv(1024), "utf-8")
while data:
total_payload += data
data = str(self.dataConn.recv(1024), "utf-8")
# Print the entire list
print("\nFTP File List\n--------------\n" + total_payload + "\n")
self.dataConn.close()
def retr(self):
try:
# Establish full directory path
full_filename = os.path.join(self.current_dir, self.filename)
print ("Full Dir: " + full_filename)
f = open(full_filename, "wb+") # Opens/creates file to copy data over
print ("Retrieving file: " + self.filename)
try:
data = self.dataConn.recv(1024)
while data:
f.write(data)
data = self.dataConn.recv(1024)
except:
print("Problem receiving data")
f.close()
print("File received.")
except:
if not f.closed:
f.close()
print("Cannot open file.")
self.dataConn.close()
def stor(self):
# Establish full directory path
full_filename = os.path.join(self.current_dir, self.filename)
print("Full Dir " + full_filename)
try:
f = open(full_filename, "rb") # Opens file, if it exists
print("Storing to file: " + self.filename)
except:
print("File not found")
self.dataConn.close()
return
# Send all data in file
while True:
self.data = f.read(8)
if not self.data: break
self.dataConn.sendall(self.data)
f.close()
class response_thread(threading.Thread):
def __init__(self, conn):
self.conn = conn
threading.Thread.__init__(self)
def run(self):
while True:
self.empty()
def empty(self):
try:
response = str(self.conn.recv(1024), "utf-8")
print(response)
except:
return
class ftp_client:
def __init__(self):
self.ctrlSock = socket.socket()
self.ctrlSock.settimeout(2)
self.current_dir = os.path.abspath("./ftp-downloads/")
if not os.path.exists(self.current_dir):
os.makedirs(self.current_dir)
# MAIN LOOP
################
while True:
entry_array = input("\nPlease enter command: ").lower().split(" ")
if entry_array[0] == "connect":
self.connect(entry_array)
elif entry_array[0] == "list":
self.list(entry_array)
elif entry_array[0] == "retr":
self.retr(entry_array)
elif entry_array[0] == "stor":
self.stor(entry_array)
elif entry_array[0] == "quit":
self.quit(entry_array)
else:
print("Unknown command: '" + entry_array[0] + "'")
try:
self.response_thread.empty()
except:
continue
# CONNECT FUNCTION
def connect(self, entry_array):
# Make sure correct amount of parameters were passed
if len(entry_array) != 3:
print("Invalid command - CONNECT Parameters: <server name/IP address> <server port>")
print("USING DEFAULT TO MAKE OUR LIVES EASIER")
entry_array = ["connect", "127.0.0.1", 7711]
# Parse control port to integer value
try:
ctrlPort = int(entry_array[2])
except ValueError:
print("Invalid port number")
return
# Establish control connection
try:
self.ctrlSock.connect((entry_array[1], ctrlPort))
# after connection is established, we need to wait for the 220 response from the server "awaiting input"
self.response_thread = response_thread(self.ctrlSock)
self.response_thread.setDaemon(True)
self.response_thread.start()
except ConnectionRefusedError:
print("Connection refused - check port number")
return
except OSError:
print("Connect request was made on an already connected socket or the server is not listening on that port.")
return
print("Connection established on port {}.".format(ctrlPort))
# LIST FUNCTION
def list(self, entry_array):
# Make sure correct amount of parameters were passed
if len(entry_array) != 1:
print("Invalid command - LIST requires no additional parameters")
return
# Make sure ctrl connection is established
try:
self.send("LIST")
except:
print("You must connect to server before using this command")
return
# Open data port and receive list
self.openDataPort(cmd="list")
# RETRIEVE FUNCTION
def retr(self, entry_array):
# Make sure correct amount of parameters were passed
if len(entry_array) != 2:
print("Invalid command - RETR Parameters: <filename>")
return
filename = entry_array[1]
# Make sure ctrl connection is established
try:
self.send("RETR " + filename)
except:
print("You must connect to server before using this command")
return
#Open data port and retrieve file
self.openDataPort(cmd="retr", filename=filename)
# STORE FUNCTION
def stor(self, entry_array):
# Make sure correct amount of parameters were passed
if len(entry_array) != 2:
print("Invalid command - STOR Parameters: <filename>")
return
filename=entry_array[1]
# Make sure ctrl connection is established
try:
self.send("STOR " + filename)
except:
print("You must connect to server before using this command")
return
#Open data port and send file
self.openDataPort(cmd="stor", filename=filename)
# QUIT FUNCTION
def quit(self, entry_array):
# Make sure correct amount of parameters were passed
if len(entry_array) != 1:
print("Invalid command - QUIT requires no additional parameters")
return
else:
try:
self.send("QUIT")
except:
exit()
# self.ctrlSock().close()
self.response_thread.empty()
exit()
def send(self, message, encoding="utf-8"):
self.ctrlSock.sendall(bytearray(message + "\r\n", encoding))
def openDataPort(self, cmd, filename=""):
try:
fct = ftp_data_thread(cmd=cmd, filename=filename)
fct.start()
fct.join()
except:
print("Unexpected error: ", sys.exc_info()[0])
print("Unexpected error: ", sys.exc_info()[1])
print("Unexpected error: ", sys.exc_info()[2])
exit()
if __name__ == '__main__':
client = ftp_client()