0 .背景
最近,需要做一個保存網絡攝像機上傳的圖片,并進行處理的程序,攝像機是通過移動偵測和遮擋偵測發(fā)送圖片到ftp服務器上. 為了實現上述目標,考慮編寫一套ftp server的代碼,這樣不僅可以保存圖片還可以處理不同用戶(攝像頭)上傳的圖片,物體檢測,人臉識別等可以同步執(zhí)行.
考慮到目前項目大都在python上,決定采用 pyftpdlib 開發(fā)ftp server.
1 .安裝
這個極為簡單:
(python3) pip3 install pyftpdlib
(python2) pip install pyftpdlib
2. Hello World
寫一個最簡單的ftp server代碼.
支持匿名登錄,一個用戶 'user' 密碼 '12345'),擁有全部權限.
匿名用戶只有只讀權限.
端口2121
import os
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
def main():
# Instantiate a dummy authorizer for managing 'virtual' users
authorizer = DummyAuthorizer()
# Define a new user having full r/w permissions and a read-only
# anonymous user
authorizer.add_user('user', '12345', '.', perm='elradfmwMT')
authorizer.add_anonymous(os.getcwd())
# Instantiate FTP handler class
handler = FTPHandler
handler.authorizer = authorizer
# Define a customized banner (string returned when client connects)
handler.banner = "pyftpdlib based ftpd ready."
# Specify a masquerade address and the range of ports to use for
# passive connections. Decomment in case you're behind a NAT.
#handler.masquerade_address = '151.25.42.11'
#handler.passive_ports = range(60000, 65535)
# Instantiate FTP server class and listen on 0.0.0.0:2121
address = ('', 2121)
server = FTPServer(address, handler)
# set a limit for connections
server.max_cons = 256
server.max_cons_per_ip = 5
# start ftp server
server.serve_forever()
if __name__ == '__main__':
main()
3. 更完善的代碼
具備事件功能,可以監(jiān)控到上傳文件的用戶和文件名,可以進一步處理.
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
from pyftpdlib.authorizers import DummyAuthorizer
class MyHandler(FTPHandler):
def on_connect(self):
print ("%s:%s connected" % (self.remote_ip, self.remote_port))
def on_disconnect(self):
# do something when client disconnects
pass
def on_login(self, username):
# do something when user login
pass
def on_logout(self, username):
# do something when user logs out
pass
def on_file_sent(self, file):
# do something when a file has been sent
print(self.username, file)
pass
def on_file_received(self, file):
# do something when a file has been received
print(self.username, file)
pass
def on_incomplete_file_sent(self, file):
# do something when a file is partially sent
print(self.username, file)
pass
def on_incomplete_file_received(self, file):
# remove partially uploaded files
import os
os.remove(file)
def main():
authorizer = DummyAuthorizer()
authorizer.add_user('user', '12345', homedir='.', perm='elradfmwMT')
authorizer.add_anonymous(homedir='.')
handler = MyHandler
handler.authorizer = authorizer
server = FTPServer(('', 2121), handler)
server.serve_forever()
if __name__ == "__main__":
main()
4. 性能對比
和主流的vsftp server性能對比
5.下一步...
下一步的思路是:
1 . ftp服務監(jiān)控攝像頭上傳的圖片
2 . 獲取用戶(那個攝像頭)和圖片,做物體識別
3 .獲取人員或車輛的Box,裁剪圖片
4 .根據裁剪圖片處理作人員識別或車輛檢測
5 .處理結果反饋給對應攝像機的處理設備