|
| 1 | +import socket |
| 2 | +from os.path import getsize |
| 3 | +import sys |
| 4 | + |
| 5 | +class ftp_client(): |
| 6 | + def __init__(self,ip_port): |
| 7 | + self.ip_port = ip_port |
| 8 | + self.client = socket.socket() |
| 9 | + self.client.connect(self.ip_port) |
| 10 | + def run(self): |
| 11 | + while True: |
| 12 | + try: |
| 13 | + msg = input('ftp_client:>>') |
| 14 | + if not msg: |
| 15 | + continue |
| 16 | + elif msg == 'dir': |
| 17 | + self.client.send(msg.encode('utf-8')) |
| 18 | + data = self.client.recv(1024) |
| 19 | + print('{}'.format(data.decode())) |
| 20 | + elif msg.split()[0] == 'get': |
| 21 | + self.client.send(msg.encode('utf-8')) |
| 22 | + file_size = self.client.recv(1024).decode() |
| 23 | + print('remote file size : {}'.format(file_size)) |
| 24 | + filename = input('Plz input you prepare to save filename and path: ') |
| 25 | + self.client.send('ack'.encode('utf-8')) |
| 26 | + recv_size = 0 |
| 27 | + with open('{}'.format(filename),'wb') as write_f: |
| 28 | + while recv_size < int(file_size): |
| 29 | + res = self.client.recv(1024) |
| 30 | + write_f.write(res) |
| 31 | + recv_size += len(res) |
| 32 | + print(type(recv_size),type(file_size),recv_size == int(file_size)) |
| 33 | + if recv_size == int(file_size): |
| 34 | + print('get done !!! plz find file to {}'.format(filename)) |
| 35 | + else: |
| 36 | + print('lost some data during trasfer...') |
| 37 | + |
| 38 | + elif msg.split()[0] == 'put': |
| 39 | + self.client.send(msg.encode('utf-8')) |
| 40 | + filename = msg.split()[1] |
| 41 | + filesize = getsize(filename) |
| 42 | + print(filesize) |
| 43 | + if self.client.recv(1024).decode() == 'ack': |
| 44 | + self.client.send(str(filesize).encode('utf-8')) |
| 45 | + if self.client.recv(1024).decode() == 'ack': |
| 46 | + remoete_filename = input('Plz input filename and path you prepare to put on the remote server: ') |
| 47 | + self.client.send(remoete_filename.encode('utf-8')) |
| 48 | + if self.client.recv(1024).decode() == 'ack': |
| 49 | + with open('{}'.format(filename),'rb') as read_f: |
| 50 | + for line in read_f: |
| 51 | + self.client.send(line) |
| 52 | + print(self.client.recv(1024).decode()) |
| 53 | + |
| 54 | + elif msg == 'quit' or msg == 'exit': |
| 55 | + sys.exit(0) |
| 56 | + |
| 57 | + else: |
| 58 | + print('Wrong command,plz input agian...') |
| 59 | + except KeyboardInterrupt: |
| 60 | + self.client.close() |
| 61 | + |
| 62 | + |
| 63 | + |
| 64 | +if __name__ == '__main__': |
| 65 | + ip_port = ('localhost',8888) |
| 66 | + f_c = ftp_client(ip_port) |
| 67 | + f_c.run() |
0 commit comments