-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.py
93 lines (73 loc) · 2.97 KB
/
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
import socket
import os
import codes
class Client:
def __init__(self, host, port):
self.user_pi = self.connect_server(host, port)
self.data_connection = False
self.buffers_size = 1024
def __enter__(self):
return self
def __exit__(self, *args, **kwargs):
if self.data_connection:
self.data_connection.close()
self.user_pi.close()
def create_data_connection(self, host, port):
self.data_connection = self.connect_server(host, port)
def parse_data_connection_path(self, path):
host_port = path.split(',')
host = '.'.join(host_port[:4])
port = (int(host_port[4])<<8) + int(host_port[5])
return host, port
def user_pi_command(self, msg):
self.user_pi.send(msg)
return self.user_pi.recv(self.buffers_size).decode('utf-8')
def dtf_command(self, msg):
self.user_pi.send(msg)
return self.data_connection.recv(self.buffers_size).decode('utf-8')
def retrieve(self, from_file, to_file):
if self.data_connection:
self.user_pi.send(b'RETR ' + from_file)
with open(to_file, 'wb') as f:
while True:
data = self.data_connection.recv(self.buffers_size)
stop_success = codes.REQUESTED_ACTION_COMPLETED
stop_fail = codes.REQUESTED_ACTION_NOT_TAKEN
if data in (stop_success, stop_fail) or not data:
break
f.write(data)
else:
raise ValueError('Отсутствует соединения с сервером данных.')
def connect_server(self, host, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
return s
if __name__ == '__main__':
HOST = '127.0.0.1'
PORT = 8080
with Client(HOST, PORT) as client:
user = client.user_pi_command(b'USER ash')
print(user)
data_address = client.user_pi_command(b'PASV')
print(data_address)
data_host, data_port = client.parse_data_connection_path(data_address)
print(data_host, data_port)
client.create_data_connection(data_host, data_port)
pwd = client.dtf_command(b'PWD')
print(pwd)
l = client.dtf_command(b'LIST ' + bytes(pwd, encoding='utf-8'))
print(l)
directory = client.dtf_command(b'MKD hz')
print(directory)
drop_directory = client.dtf_command(b'RMD hz')
print(drop_directory)
with open('random_server_file.txt', 'wb') as f:
f.write(os.urandom(2048))
client.retrieve(b'random_server_file.txt', b'new_file.txt')
with open('new_file.txt', 'rb') as f:
second = f.read()
with open('random_server_file.txt', 'rb') as f:
first = f.read()
print(second == first)
client.dtf_command(b'DELE random_server_file.txt')
client.dtf_command(b'DELE new_file.txt')