I need to use TFTP server on Python and I try to use TFTPy module for it. Server works perfect, but I can't stop it in moment as I wish.
Python v3.7, TFTPy v 0.8.0, Windows 10x64. I tried to write simple code and using threads but nothing changed.
import tftpy
import time
server = tftpy.TftpServer('C:/Users/MyUSER/Downloads/FTPS/')
server.listen('127.0.0.1', 69)
time.sleep(5)
server.stop(True)
and more complex using threads:
import tftpy
import threading
import time
from datetime import datetime
tftp_ip_addr = '127.0.0.1'
tftp_folder = 'C:/Users/MyUSER/Downloads/FTPS/'
class PyTFTPServer(object):
def __init__(self, tftp_ip_addr, tftp_folder):
self.tftp_ip_addr = tftp_ip_addr
self.tftp_folder = tftp_folder
self.server = tftpy.TftpServer(tftp_folder)
self.server.shutdown_gracefully = False
def start_tftp_server(self):
thr = threading.Thread(name="TFTP-Server Thread", target=self.server.listen(tftp_ip_addr, 69))
thr.daemon = True
thr.start()
now_time = datetime.now()
print(now_time.strftime("%d.%m.%Y %H:%M:%S") + ' TFTP Server: TFTP Server started')
def stop_tftp_server(self):
self.server.stop(True)
tftp_server = PyTFTPServer(tftp_ip_addr, tftp_folder)
tftp_server.start_tftp_server()
time.sleep(8)
tftp_server.stop_tftp_server()
Server don't stop as I wish. It start and continue working without any limits, also I tried use 'server timeout' (for example self.server.listen(tftp_ip_addr, 69,1)) but it is also don't work.
This code make all what I need: import threading import tftpy from datetime import datetime
def get_current_time():
now_time = datetime.now()
return now_time.strftime("%d.%m.%Y %H:%M:%S")
class PYTFTPServer(object):
def __init__(self, tftp_ip_addr, tftp_folder, tftp_log_level):
self.tftp_ip_addr = tftp_ip_addr
self.tftp_folder = tftp_folder
self.tftp_server = tftpy.TftpServer(self.tftp_folder)
self.tftp_log_level = tftp_log_level
def start_tftp_server(self):
try:
print(get_current_time() + ' TFTP Server: TFTP Server starting')
self.tftp_server.listen(self.tftp_ip_addr, 69)
except KeyboardInterrupt:
pass
def stop_tftp_server(self):
self.tftp_server.stop() # Do not take any new transfers, but complete the existing ones.
print(get_current_time() + ' TFTP Server: TFTP Server stoped')
# self.server.stop(True) # Drop all connections and stop the server. Can be used if needed.
def start_tftp_process(tftp_ip_addr, tftp_folder, tftp_log_level):
global tftpsrv, TFTP_srv_thread
tftpsrv = PYTFTPServer(tftp_ip_addr, tftp_folder, tftp_log_level)
TFTP_srv_thread = threading.Thread(name="TFTP Server thread", target=tftpsrv.start_tftp_server)
TFTP_srv_thread.start()
def stop_tftp_process():
tftpsrv.stop_tftp_server()
TFTP_srv_thread.join()