/
ftp_client.py
1284 lines (1179 loc) · 42.6 KB
/
ftp_client.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
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#import necessary packages.
import os
import os.path
import errno
import traceback
import sys
from socket import *
import argparse
import subprocess
from configparser import ConfigParser
import logging
import threading
#Global constants
USAGE = "usage: Python ftp hostname [username] [password] -h [hostname] -u [username]\
-w [password] -fp [ftp server port] -P (passive) -A (active)-D (debug mode on/off) \
-d [on/off] (debug on/off) -V (verbose) -dpr [data port range (space separated)] \
-c [configuarion file] -t [test file] -T (run default test file) -L [log_file_name] \
-ALL (log all output to log file) -ONLY (log all output to log file without displaying)\
-version( prints version number of this client.) -info"
t_list=[]
CMD_FTP = "FTP"
CMD_OPEN = "OPEN"
CMD_QUIT = "QUIT"
CMD_BYE = "BYE"
CMD_CLOSE = "CLOSE"
CMD_EXIT = "EXIT"
CMD_DISC = "DISCONNECT"
CMD_HELP = "HELP"
CMD_QUESTION = "?"
CMD_LOGIN = "LOGIN"
CMD_LOGOUT = "LOGOUT"
CMD_LS = "LS"
CMD_LIST = "LIST"
CMD_DIR = "DIR"
CMD_PWD = "PWD"
CMD_MKD = "MKD"
CMD_MKDIR = "MKDIR"
CMD_RMD = "RMD"
CMD_RMDIR = "RMDIR"
CMD_CWD = "CWD"
CMD_CDUP = "CDUP"
CMD_PORT = "PORT"
CMD_DELETE = "DELETE"
CMD_PUT = "PUT"
CMD_SEND = "SEND"
CMD_GET = "GET"
CMD_USER = "USER"
CMD_PASS = "PASS"
CMD_RETR = "RETR"
CMD_NOOP ="NOOP"
CMD_DELE = "DELE"
CMD_STOR = "STOR"
CMD_STOU = "STOU"
CMD_RNFR = "RNFR"
CMD_RNTO = "RNTO"
CMD_APPE = "APPE"
CMD_APPEND = "APPEND"
CMD_TYPE = "TYPE"
CMD_IMAGE = "IMAGE"
CMD_BIN = "BINARY"
CMD_ASCII = "ASCII"
CMD_LPWD = "LPWD"
CMD_LCD = "LCD"
CMD_LLS = "LLS"
CMD_CD="CD"
CMD_USAGE = "USAGE"
CMD_VERBOSE = "VERBOSE"
CMD_SUNIQUE = "SUNIQUE"
CMD_DEBUG = "DEBUG"
CMD_RHELP = "RHELP"
CMD_RENAME = "RENAME"
unique_on = False
verbose_on = False
#global
global username
global password
username = ""
password = ""
hostname = ""
collection=""
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("supplied",nargs="*", help ="hostname, username, password")
parser.add_argument("-h", "--h", help="provide hostname",
type=str)
parser.add_argument("-u", "--u", help="provide username",
type=str)
parser.add_argument("-p", "--p", help="provide password",
type=str)
parser.add_argument("-w", "--w", help="provide password",
type=str)
parser.add_argument("-fp","--fp", help="provide ftp server port",
type=str)
parser.add_argument("-A","--A" ,help="Sets to active mode",
action="store_true")
parser.add_argument("-P", "--P",help="Sets to passive mode",
action="store_true")
parser.add_argument("-D", "--D",help="Sets to debug mode",
action="store_true")
parser.add_argument("-V", "--V",help="Sets to verbose mode",
action="store_true")
parser.add_argument("-dpr","--dpr",help="Changes data port range",
type=int,nargs="*")
parser.add_argument("-c","--c", help="Changes config file path", type=str)
parser.add_argument("-t", "--t",help="run test file", type=str)
parser.add_argument("-T", "--T", help="run default test file", action="store_true")
parser.add_argument("-L","--L", help="Changes files log name", type=str)
parser.add_argument("-ALL","--ALL", help="log all output to log file (and still display it) log_file_name", type=str)
parser.add_argument("-ONLY","--ONLY", help="log all output to log file", type=str)
parser.add_argument("-version", "--version",help="Prints version info", action="store_true")
parser.add_argument("-info", "--info",help="Prints student info", action="store_true")
debug_mode=0
logon_ready = False
args = parser.parse_args()
if args.h:
hostname = args.h
if args.u:
username = args.u
if args.p:
password = args.p
if args.w:
password = args.w
if args.u and args.w:
logon_ready = True
if args.fp:
FTP_PORT = int(args.fp)
if args.A:
FTP_MODE = "ACTIVE"
if args.P:
FTP_MODE = "PASSIVE"
if args.D:
debug_mode = 1
if args.V:
verbose_on = True
if args.dpr:
DATA_PORT_MIN, DATA_PORT_MAX = args.dpr
if args.c:
config_file_path = args.c
if args.t:
#RUN args.t
pass
if args.T:
#RUN DEFAULT
pass
if args.L:
log_file_name = args.L
if args.ALL:
log_file_name = args.ALL
log_all_output = True
print_and_log = True
if args.ONLY:
log_file_name = args.ONLY
log_all_output = True
print_and_log =False
if args.version:
print("FTP Client v2.0")
if args.info:
print("FTP Client v2.0 was created by Mark Fajet.")
#entry point main()
def main():
read_config()
global username
global password
global log_file_name
global hostname
global args
logged_on = False
global logon_ready
global debug_mode
if not debug_mode:
global default_debug_mode
if default_debug_mode == "on":
debug_mode = 1
else:
debug_mode = 0
global verbose_on
if not verbose_on:
global default_verbose_mode
if default_verbose_mode == "on":
verbose_on = True
logging.basicConfig(level=logging.DEBUG, filename=log_file_name,
format="%(asctime)-15s %(levelname)-8s %(message)s")
print("FTP Client v2.0")
if (len(args.supplied) < 1):
print(USAGE)
if (len(args.supplied) == 1):
hostname = args.supplied[0]
if (len(args.supplied) == 2):
username = args.supplied[0]
password = args.supplied[1]
logon_ready = True
if (len(args.supplied) == 3):
username = args.supplied[1]
password = args.supplied[2]
logon_ready = True
while not hostname:
rinput = input("FTP>")
if (rinput is None or rinput.strip() == ''):
continue
tokens = rinput.split()
cmd = tokens[0].upper()
if cmd == CMD_FTP or cmd ==CMD_OPEN:
if len(tokens) == 2:
hostname = tokens[1]
elif len(tokens) == 3:
hostname = tokens[1]
global FTP_PORT
FTP_PORT = int(tokens[2])
else:
print(cmd + " [hostname]")
elif cmd==CMD_HELP:
help_ftp()
else:
print("Not connected")
print("********************************************************************")
print("** ACTIVE MODE ONLY **")
print("********************************************************************")
print(("You will be connected to host:" + hostname))
print("Type HELP for more information")
print("Commands are NOT case sensitive\n")
ftp_socket = ftp_connecthost(hostname)
ftp_recv = ftp_socket.recv(RECV_BUFFER)
ftp_code = ftp_recv[:3]
#
#note that in the program there are many .strip('\n')
#this is to avoid an extra line from the message
#received from the ftp server.
#an alternative is to use sys.stdout.write
print(msg_str_decode(ftp_recv,True))
#
#this is the only time that login is called
#without relogin
#otherwise, relogin must be called, which included prompts
#for username
#
if(username and password):
logon_ready = True
if (logon_ready):
logged_on = login(username,password,ftp_socket)
keep_running = True
while keep_running:
try:
rinput = input("FTP>")
if (rinput is None or rinput.strip() == ''):
continue
tokens = rinput.split()
cmdmsg , logged_on, ftp_socket = run_cmds(tokens,logged_on,ftp_socket)
if (cmdmsg != ""):
if log_all_output:
logging.info(cmdmsg)
print(cmdmsg)
except OSError as e:
# A socket error
print("Socket error:",e)
strError = str(e)
#this exits but it is better to recover
if (strError.find("[Errno 32]") >= 0):
sys.exit()
#print ftp_recv
try:
ftp_socket.close()
print("Thank you for using FTP 1.0")
except OSError as e:
print("Socket error:",e)
sys.exit()
def run_cmds(tokens,logged_on,ftp_socket):
global username
global password
global hostname
global debug_mode
global t_list
cmd = tokens[0].upper()
if (cmd == CMD_QUIT or cmd==CMD_EXIT or cmd == CMD_DISC or cmd==CMD_BYE or cmd ==CMD_CLOSE):
quit_ftp(logged_on,ftp_socket)
return "",logged_on, ftp_socket
if (cmd == CMD_HELP or cmd == CMD_QUESTION):
help_ftp(tokens)
return "",logged_on, ftp_socket
if (cmd == CMD_PWD):
pwd_ftp(ftp_socket)
return "",logged_on, ftp_socket
if (cmd == CMD_STOU):
data_socket = ftp_new_dataport(ftp_socket)
if (data_socket is not None):
stou_ftp(tokens, ftp_socket,data_socket)
return "",logged_on, ftp_socket
else:
if log_all_output:
logging.info("[STOU] Failed to get data port. Try again.")
return "[STOU] Failed to get data port. Try again.",logged_on, ftp_socket
if (cmd == CMD_LS or cmd == CMD_LIST or cmd == CMD_DIR):
#FTP must create a channel to received data before
#executing ls.
#also makes sure that data_socket is valid
#in other words, not None
data_socket = ftp_new_dataport(ftp_socket)
if (data_socket is not None):
ls_ftp(tokens,ftp_socket,data_socket)
return "",logged_on, ftp_socket
else:
if log_all_output:
logging.info("[LS] Failed to get data port. Try again.")
return "[LS] Failed to get data port. Try again.",logged_on, ftp_socket
if (cmd == CMD_LOGIN):
username, password, logged_on, ftp_socket \
= relogin(username, password, logged_on, tokens, hostname, ftp_socket)
return "",logged_on, ftp_socket
if (cmd == CMD_LOGOUT):
logged_on,ftp_socket = logout(logged_on,ftp_socket)
return "",logged_on, ftp_socket
if (cmd == CMD_DELETE or cmd == CMD_DELE or cmd=="DEL"):
delete_ftp(tokens,ftp_socket)
return "",logged_on, ftp_socket
if (cmd == CMD_PUT or cmd==CMD_STOR or cmd==CMD_SEND):
# FTP must create a channel to received data before
# executing put.
# also makes sure that data_socket is valid
# in other words, not None
data_socket = ftp_new_dataport(ftp_socket)
if (data_socket is not None):
global unique_on
if unique_on:
stou_ftp(tokens,ftp_socket,data_socket)
else:
put_ftp(tokens,ftp_socket,data_socket)
return "",logged_on, ftp_socket
else:
if log_all_output:
logging.info("[PUT] Failed to get data port. Try again.")
return "[PUT] Failed to get data port. Try again.",logged_on, ftp_socket
if (cmd==CMD_STOR):
# FTP must create a channel to received data before
# executing put.
# also makes sure that data_socket is valid
# in other words, not None
data_socket = ftp_new_dataport(ftp_socket)
if (data_socket is not None):
put_ftp(tokens,ftp_socket,data_socket)
return "",logged_on, ftp_socket
else:
if log_all_output:
logging.info("[PUT] Failed to get data port. Try again.")
return "[PUT] Failed to get data port. Try again.",logged_on, ftp_socket
if (cmd == CMD_APPE or cmd == CMD_APPEND):
# FTP must create a channel to received data before
# executing put.
# also makes sure that data_socket is valid
# in other words, not None
data_socket = ftp_new_dataport(ftp_socket)
if (data_socket is not None):
appe_ftp(tokens,ftp_socket,data_socket)
return "",logged_on, ftp_socket
else:
if log_all_output:
logging.info("[APPE] Failed to get data port. Try again.")
return "[APPE] Failed to get data port. Try again.",logged_on, ftp_socket
if (cmd == CMD_GET or cmd ==CMD_RETR):
# FTP must create a channel to received data before
# executing get.
# also makes sure that data_socket is valid
# in other words, not None
data_socket = ftp_new_dataport(ftp_socket)
if (data_socket is not None):
get_ftp(tokens,ftp_socket,data_socket)
return "",logged_on, ftp_socket
else:
if log_all_output:
logging.info("[GET] Failed to get data port. Try again.")
return "[GET] Failed to get data port. Try again.",logged_on, ftp_socket
if (cmd==CMD_USER):
user_ftp(tokens,ftp_socket)
return "",logged_on, ftp_socket
if (cmd==CMD_PASS):
logged_on = pass_ftp(tokens,ftp_socket)
return "",logged_on, ftp_socket
if (cmd==CMD_NOOP):
noop_ftp(ftp_socket)
return "",logged_on, ftp_socket
if (cmd == CMD_CWD or cmd =="CD"):
cwd_ftp(tokens,ftp_socket)
return "",logged_on, ftp_socket
if (cmd == CMD_MKD or cmd == CMD_MKDIR):
mkd_ftp(tokens,ftp_socket)
return "",logged_on, ftp_socket
if (cmd == CMD_RMD or cmd == CMD_RMDIR):
rmd_ftp(tokens,ftp_socket)
return "",logged_on, ftp_socket
if (cmd == CMD_CDUP):
cdup_ftp(ftp_socket)
return "",logged_on, ftp_socket
if (cmd == CMD_RNFR):
rnfr_ftp(tokens, ftp_socket)
return "",logged_on, ftp_socket
if (cmd == CMD_RNTO):
rnto_ftp(tokens, ftp_socket)
return "",logged_on, ftp_socket
if (cmd == CMD_TYPE):
type_ftp(tokens, ftp_socket)
return "",logged_on, ftp_socket
if cmd == CMD_IMAGE or cmd == CMD_BIN:
image_ftp(tokens, ftp_socket)
return "",logged_on, ftp_socket
if cmd == CMD_ASCII:
ascii_ftp(tokens, ftp_socket)
return "",logged_on, ftp_socket
if (cmd == CMD_PORT):
port_ftp(tokens,ftp_socket)
return "",logged_on, ftp_socket
if (cmd==CMD_LPWD):
return os.getcwd(),logged_on, ftp_socket
if (cmd==CMD_LCD):
if len(tokens) > 1:
try:
os.chdir(tokens[1])
return os.getcwd(),logged_on, ftp_socket
except:
if log_all_output:
logging.info("LCD failed. Path does not exist")
return "Path does not exist", logged_on, ftp_socket
else:
if log_all_output:
logging.info("LCD failed. Path not specified")
return "Path not specified", logged_on, ftp_socket
if (cmd==CMD_LLS):
if len(tokens) > 1:
ls_output = subprocess.check_output(['ls', '-l', tokens[1]]).decode()
else:
ls_output = subprocess.check_output(['ls', '-l']).decode()
return ls_output, logged_on, ftp_socket
if (cmd==CMD_SUNIQUE):
unique_on = not unique_on
if unique_on:
return "Unique storing on", logged_on, ftp_socket
else:
return "Unique storing off", logged_on, ftp_socket
if (cmd == CMD_RENAME):
rename_ftp(tokens, ftp_socket)
return "",logged_on, ftp_socket
if (cmd ==CMD_DEBUG):
if len (tokens)>1:
if tokens[1]>=1:
debug_mode=tokens[1]
elif tokens[1] == 0:
debug_mode = 0
else:
return tokens[1] + ": bad debugging value.", logged_on, ftp_socket
else:
if debug_mode:
debug_mode = 0
else:
debug_mode = 1
if debug_mode:
return "Debugging on (debug=" + str(debug_mode) + ")", logged_on,ftp_socket
else:
return "Debugging off (debug=0).", logged_on,ftp_socket
if (cmd==CMD_VERBOSE):
global verbose_on
verbose_on = not verbose_on
if verbose_on:
return "Verbose mode on.", logged_on, ftp_socket
else:
return "Verbose mode on.", logged_on, ftp_socket
if cmd == CMD_USAGE:
global USAGE
return USAGE, logged_on,ftp_socket
if cmd == CMD_RHELP:
rhelp_ftp(tokens,ftp_socket)
return "",logged_on, ftp_socket
return "Unknown command", logged_on, ftp_socket
def str_msg_encode(strValue):
msg = strValue.encode()
return msg
def msg_str_decode(msg,pStrip=False):
#print("msg_str_decode:" + str(msg))
strValue = msg.decode()
if (pStrip):
strValue.strip('\n')
return strValue
def ftp_connecthost(hostname):
ftp_socket = socket(AF_INET, SOCK_STREAM)
#to reuse socket faster. It has very little consequence for ftp client.
ftp_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
ftp_socket.connect((hostname, FTP_PORT))
print (ftp_socket)
return ftp_socket
def ftp_new_dataport(ftp_socket):
global next_data_port
dport = next_data_port
host = gethostname()
host_address = gethostbyname(host)
next_data_port = next_data_port + 1 #for next next
dport = (DATA_PORT_MIN + dport) % DATA_PORT_MAX
if verbose_on:
print(("Preparing Data Port: " + host + " " + host_address + " " + str(dport)))
data_socket = socket(AF_INET, SOCK_STREAM)
# reuse port
data_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
data_socket.bind((host_address, dport))
data_socket.listen(DATA_PORT_BACKLOG)
#the port requires the following
#PORT IP PORT
#however, it must be transmitted like this.
#PORT 192,168,1,2,17,24
#where the first four octet are the ip and the last two form a port number.
host_address_split = host_address.split('.')
high_dport = str(dport // 256) #get high part
low_dport = str(dport % 256) #similar to dport << 8 (left shift)
port_argument_list = host_address_split + [high_dport,low_dport]
port_arguments = ','.join(port_argument_list)
cmd_port_send = CMD_PORT + ' ' + port_arguments + '\r\n'
if verbose_on:
print(cmd_port_send)
try:
ftp_socket.send(str_msg_encode(cmd_port_send))
except socket.timeout:
print("Socket timeout. Port may have been used recently. wait and try again!")
return None
except socket.error:
print("Socket error. Try again")
return None
msg = ftp_socket.recv(RECV_BUFFER)
if verbose_on:
print(msg_str_decode(msg,True))
if not msg.decode()[0:3] == "200":
return None
return data_socket
def pwd_ftp(ftp_socket):
message = str_msg_encode("PWD\r\n")
global debug_mode
if debug_mode:
print("(DEBUG) --> " + message.decode())
ftp_socket.send(message)
msg = ftp_socket.recv(RECV_BUFFER)
print(msg_str_decode(msg,True))
def rhelp_ftp(tokens, ftp_socket):
if len(tokens)>1:
message = str_msg_encode("HELP " + tokens[1] + "\r\n")
else:
message = str_msg_encode("HELP\r\n")
global debug_mode
if debug_mode:
print("(DEBUG) --> " + message.decode())
ftp_socket.send(message)
msg = ftp_socket.recv(RECV_BUFFER)
print(msg_str_decode(msg,True))
def port_ftp(tokens,ftp_socket):
if (len(tokens) < 2):
print("PORT [h1,h2,h3,h4,p1,p2]. Please specify address")
return
message = str_msg_encode("PORT " + tokens[1] + "\r\n")
global debug_mode
if debug_mode:
print("(DEBUG) --> " + message.decode())
ftp_socket.send(message)
msg = ftp_socket.recv(RECV_BUFFER)
if verbose_on:
print(msg_str_decode(msg,True))
def type_ftp(tokens,ftp_socket):
if (len(tokens) < 2):
print("TYPE [type-code]. Please specify type-code")
return
message=str_msg_encode("TYPE " + tokens[1] + "\r\n")
global debug_mode
if debug_mode:
print("(DEBUG) --> " + message.decode())
ftp_socket.send(message)
msg = ftp_socket.recv(RECV_BUFFER)
if verbose_on:
print(msg_str_decode(msg,True))
def image_ftp(tokens,ftp_socket):
message = str_msg_encode("TYPE I\r\n")
global debug_mode
if debug_mode:
print("(DEBUG) --> " + message.decode())
ftp_socket.send(message)
msg = ftp_socket.recv(RECV_BUFFER)
if verbose_on:
print(msg_str_decode(msg,True))
def ascii_ftp(tokens,ftp_socket):
message = str_msg_encode("TYPE A\r\n")
global debug_mode
if debug_mode:
print("(DEBUG) --> " + message.decode())
ftp_socket.send(message)
msg = ftp_socket.recv(RECV_BUFFER)
if verbose_on:
print(msg_str_decode(msg,True))
def rename_ftp(tokens,ftp_socket):
if (len(tokens) < 3):
print("RENAME [filename] [filename]. Please specify filename")
return
message = str_msg_encode("RNFR " + tokens[1] + "\r\n")
global debug_mode
if debug_mode:
print("(DEBUG) --> " + message.decode())
ftp_socket.send(message)
msg = ftp_socket.recv(RECV_BUFFER)
if verbose_on:
print(msg_str_decode(msg,True))
message = str_msg_encode("RNTO " + tokens[2] + "\r\n")
if debug_mode:
print("(DEBUG) --> " + message.decode())
ftp_socket.send(message)
msg = ftp_socket.recv(RECV_BUFFER)
if verbose_on:
print(msg_str_decode(msg,True))
def rnfr_ftp(tokens,ftp_socket):
if (len(tokens) < 2):
print("RNFR [filename]. Please specify filename")
return
message = str_msg_encode("RNFR " + tokens[1] + "\r\n")
global debug_mode
if debug_mode:
print("(DEBUG) --> " + message.decode())
ftp_socket.send(message)
msg = ftp_socket.recv(RECV_BUFFER)
if verbose_on:
print(msg_str_decode(msg,True))
def rnto_ftp(tokens, ftp_socket):
if (len(tokens) < 2):
print("RNTO [filename]. Please specify filename")
return
message = str_msg_encode("RNTO " + tokens[1] + "\r\n")
global debug_mode
if debug_mode:
print("(DEBUG) --> " + message.decode())
ftp_socket.send(message)
msg = ftp_socket.recv(RECV_BUFFER)
if verbose_on:
print(msg_str_decode(msg,True))
def stou_ftp(tokens, ftp_socket,data_socket):
if (len(tokens) < 2):
print("stou [filename]")
return
local_filename = tokens[1]
if (len(tokens) == 3):
filename = tokens[2]
else:
filename = local_filename
if (os.path.isfile(local_filename) == False):
print(("Filename does not exisit on this client. Filename: " + filename + " -- Check file name and path"))
return
filestat = os.stat(local_filename)
filesize = filestat.st_size
message = str_msg_encode("STOU " + filename + "\r\n")
global debug_mode
if debug_mode:
print("(DEBUG) --> " + message.decode())
ftp_socket.send(message)
msg = ftp_socket.recv(RECV_BUFFER)
if verbose_on:
print(msg_str_decode(msg,True))
print(("Attempting to send file. Local: " + local_filename + " - Remote:" + filename + " - Size:" + str(filesize)))
def data_func():
data_connection, data_host = data_socket.accept()
file_bin = open(filename,"rb") #read and binary modes
size_sent = 0
#use write so it doesn't produce a new line (like print)
while True:
data = file_bin.read(RECV_BUFFER)
if (not data or data == '' or len(data) <= 0):
file_bin.close()
break
else:
data_connection.send(data)
size_sent += len(data)
sys.stdout.write("\n")
data_connection.close()
global t_list
t = threading.Thread(target = data_func)
t.start()
t_list.append(t)
msg = ftp_socket.recv(RECV_BUFFER)
if verbose_on:
print(msg_str_decode(msg,True))
def user_ftp(tokens,ftp_socket):
if (len(tokens) < 2):
print("user [username]. Please specify username")
return
message = ("USER " + tokens[1] + "\n").encode()
global debug_mode
if debug_mode:
print("(DEBUG) --> " + message.decode())
ftp_socket.send(message)
msg = ftp_socket.recv(RECV_BUFFER).decode()
if verbose_on:
print(msg.strip('\n'))
def pass_ftp(tokens,ftp_socket):
if (len(tokens) < 2):
print("pass [password]. Please specify password")
return False
message = ("PASS " + tokens[1] + "\n").encode()
global debug_mode
if debug_mode:
print("(DEBUG) --> " + message.decode())
ftp_socket.send(message)
msg = ftp_socket.recv(RECV_BUFFER).decode()
if verbose_on:
print(msg.strip('\n'))
if msg.split()[0]=="230":
return True
else:
return False
def get_ftp(tokens, ftp_socket, data_socket):
if (len(tokens) < 2):
print("put [filename]. Please specify filename")
return
remote_filename = tokens[1]
if (len(tokens) == 3):
filename = tokens[2]
else:
filename = remote_filename
message = str_msg_encode("RETR " + remote_filename + "\r\n")
global debug_mode
if debug_mode:
print("(DEBUG) --> " + message.decode())
ftp_socket.send(message)
if verbose_on:
print(("Attempting to write file. Remote: " + remote_filename + " - Local:" + filename))
msg = ftp_socket.recv(RECV_BUFFER)
strValue = msg_str_decode(msg)
tokens = strValue.split()
if (tokens[0] != "150" ):
print("Unable to retrieve file. Check that file exists (ls) or that you have permissions")
return
if verbose_on:
print(msg_str_decode(msg,True))
def data_func():
data_connection, data_host = data_socket.accept()
file_bin = open(filename, "wb") # read and binary modes
print()
size_recv = 0
while True:
data = data_connection.recv(RECV_BUFFER)
if (not data or data == '' or len(data) <= 0):
file_bin.close()
break
else:
file_bin.write(data)
size_recv += len(data)
sys.stdout.write("\n")
data_connection.close()
global t_list
t = threading.Thread(target = data_func)
t.start()
t_list.append(t)
msg = ftp_socket.recv(RECV_BUFFER)
if verbose_on:
print(msg_str_decode(msg,True))
def appe_ftp(tokens, ftp_socket, data_socket):
if (len(tokens) < 2):
print("appe [filename]. Please specify filename")
return
local_filename = tokens[1]
if (len(tokens) == 3):
filename = tokens[2]
else:
filename = local_filename
if (os.path.isfile(local_filename) == False):
print(("Filename does not exisit on this client. Filename: " + filename + " -- Check file name and path"))
return
filestat = os.stat(local_filename)
filesize = filestat.st_size
message = str_msg_encode("APPE " + filename + "\r\n")
global debug_mode
if debug_mode:
print("(DEBUG) --> " + message.decode())
ftp_socket.send(message)
msg = ftp_socket.recv(RECV_BUFFER)
if verbose_on:
print(msg_str_decode(msg,True))
print(("Attempting to send file. Local: " + local_filename + " - Remote:" + filename + " - Size:" + str(filesize)))
def data_func():
data_connection, data_host = data_socket.accept()
file_bin = open(filename,"rb") #read and binary modes
size_sent = 0
#use write so it doesn't produce a new line (like print)
while True:
data = file_bin.read(RECV_BUFFER)
if (not data or data == '' or len(data) <= 0):
file_bin.close()
break
else:
data_connection.send(data)
size_sent += len(data)
sys.stdout.write("\n")
data_connection.close()
global t_list
t = threading.Thread(target = data_func)
t.start()
t_list.append(t)
msg = ftp_socket.recv(RECV_BUFFER)
if verbose_on:
print(msg_str_decode(msg,True))
### put_ftp
def put_ftp(tokens,ftp_socket,data_socket):
if (len(tokens) < 2):
print("put [filename]. Please specify filename")
return
local_filename = tokens[1]
if (len(tokens) == 3):
filename = tokens[2]
else:
filename = local_filename
if (os.path.isfile(local_filename) == False):
print(("Filename does not exisit on this client. Filename: " + filename + " -- Check file name and path"))
return
filestat = os.stat(local_filename)
filesize = filestat.st_size
message=str_msg_encode("STOR " + filename + "\r\n")
global debug_mode
if debug_mode:
print("(DEBUG) --> " + message.decode())
ftp_socket.send(message)
msg = ftp_socket.recv(RECV_BUFFER)
if verbose_on:
print(msg_str_decode(msg,True))
print(("Attempting to send file. Local: " + local_filename + " - Remote:" + filename + " - Size:" + str(filesize)))
def data_func():
data_connection, data_host = data_socket.accept()
file_bin = open(filename,"rb") #read and binary modes
size_sent = 0
#use write so it doesn't produce a new line (like print)
while True:
data = file_bin.read(RECV_BUFFER)
if (not data or data == '' or len(data) <= 0):
file_bin.close()
break
else:
data_connection.send(data)
size_sent += len(data)
sys.stdout.write("\n")
data_connection.close()
global t_list
t = threading.Thread(target = data_func)
t.start()
t_list.append(t)
msg = ftp_socket.recv(RECV_BUFFER)
if verbose_on:
print(msg_str_decode(msg,True))
#
def ls_ftp(tokens,ftp_socket,data_socket):
if (len(tokens) > 1):
message = str_msg_encode("LIST " + tokens[1] + "\r\n")
global debug_mode
if debug_mode:
print("(DEBUG) --> " + message.decode())
ftp_socket.send(message)
else:
message = str_msg_encode("LIST\r\n")
if debug_mode:
print("(DEBUG) --> " + message.decode())
ftp_socket.send(message)
msg = ftp_socket.recv(RECV_BUFFER)
if verbose_on:
print(msg_str_decode(msg,True))
strValue = msg_str_decode(msg)
tokens = strValue.split()
if (tokens[0] != "200" and tokens[0]!="150"):
print("Unable to list directory contents. Check that you have permissions")
return
def data_func():
data_connection, data_host = data_socket.accept()
print()
msg = data_connection.recv(RECV_BUFFER)
while (len(msg) > 0):
print(msg_str_decode(msg,True))
msg = data_connection.recv(RECV_BUFFER)
data_connection.close()
global t_list
t = threading.Thread(target = data_func)
t.start()
t_list.append(t)
msg = ftp_socket.recv(RECV_BUFFER)
if verbose_on:
print(msg_str_decode(msg,True))
#data_connection.close()
def delete_ftp(tokens, ftp_socket):
if (len(tokens) < 2):
print("You must specify a file to delete")
else:
message = str_msg_encode("DELE " + tokens[1] + "\r\n")
global debug_mode
if debug_mode:
print("(DEBUG) --> " + message.decode())
if verbose_on:
print(("Attempting to delete " + tokens[1]))
ftp_socket.send(message)
msg = ftp_socket.recv(RECV_BUFFER)
if verbose_on:
print(msg_str_decode(msg,True))
def logout(lin, ftp_socket):
if (ftp_socket is None):
print("Your connection was already terminated.")
return False, ftp_socket
global t_list
for t in t_list:
t.join()
if (lin == False):
print("You are not logged in. Logout command will be send anyways")
if verbose_on:
print("Attempting to logged out")
msg = ""
try:
ftp_socket.send(str_msg_encode("QUIT\r\n"))
msg = ftp_socket.recv(RECV_BUFFER)
except socket.error:
print ("Problems logging out. Try logout again. Do not login if you haven't logged out!")
return False
if verbose_on:
print(msg_str_decode(msg,True))
return False, ftp_socket #it should only be true if logged in and not able to logout
def quit_ftp(lin,ftp_socket):
print ("Quitting...")
logged_on, ftp_socket = logout(lin,ftp_socket)
print("Thank you for using FTP")