-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathftp_server.py
executable file
·119 lines (106 loc) · 3.16 KB
/
ftp_server.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
'''
ftp 文件服务器
'''
from socket import *
import os
import sys
import time
import signal
#文件库路径
FILE_PATH = "/home/tarena/code/"
HOST = '0.0.0.0'
PORT = 8000
ADDR = (HOST,PORT)
#将文件服务器功能写在类中
class FtpServer(object):
def __init__(self,connfd):
self.connfd = connfd
def do_list(self):
#获取文件列表
file_list = os.listdir(FILE_PATH)
if not file_list:
self.connfd.send("文件库为空".encode())
return
else:
self.connfd.send(b'OK')
time.sleep(0.1)
files = ''
for file in file_list:
if file[0] != '.' and \
os.path.isfile(FILE_PATH + file):
files = files + file + '#'
self.connfd.sendall(files.encode())
def do_get(self,filename):
try:
fd = open(FILE_PATH + filename,'rb')
except:
self.connfd.send('文件不存在'.encode())
return
self.connfd.send(b'OK')
time.sleep(0.1)
#发送文件
while True:
data = fd.read(1024)
if not data:
time.sleep(0.1)
self.connfd.send(b'##')
break
self.connfd.send(data)
print("文件发送完毕")
def do_set(self,filenname):
try:
fd = open(FILE_PATH + filenname,'wb')
except:
self.connfd.send('文件已存在'.encode())
return
self.connfd.send(b'OK')
while True:
data = self.connfd.recv(1024).decode()
if data == '##':
break
fd.write(data.encode())
fd.close()
print("%s 接收完毕\n"%filenname)
#创建套接字,接收客户端连接,创建新的进程
def main():
sockfd = socket()
sockfd.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
sockfd.bind(ADDR)
sockfd.listen(5)
#处理子进程退出
signal.signal(signal.SIGCHLD,signal.SIG_IGN)
print("Listen the port 8000...")
while True:
try:
connfd,addr = sockfd.accept()
except KeyboardInterrupt:
sockfd.close()
sys.exit("服务器退出")
except Exception as e:
print("服务器异常:",e)
continue
print("已连接客户端:",addr)
#创建子进程
pid = os.fork()
if pid == 0:
sockfd.close()
ftp = FtpServer(connfd)
#判断客户端请求
while True:
data = connfd.recv(1024).decode()
if not data or data[0] == 'Q':
connfd.close()
sys.exit("客户端退出")
elif data[0] == 'L':
ftp.do_list()
elif data[0] == 'G':
filename = data.split(' ')[-1]
ftp.do_get(filename)
elif data[0] == 'S':
filenname = data.split(' ')[-1]
ftp.do_set(filenname)
else:
connfd.close()
continue
if __name__ == "__main__":
main()