当前位置: 首页>>代码示例>>Python>>正文


Python FTPServer.close_all方法代码示例

本文整理汇总了Python中pyftpdlib.servers.FTPServer.close_all方法的典型用法代码示例。如果您正苦于以下问题:Python FTPServer.close_all方法的具体用法?Python FTPServer.close_all怎么用?Python FTPServer.close_all使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pyftpdlib.servers.FTPServer的用法示例。


在下文中一共展示了FTPServer.close_all方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: FTPd

# 需要导入模块: from pyftpdlib.servers import FTPServer [as 别名]
# 或者: from pyftpdlib.servers.FTPServer import close_all [as 别名]
class FTPd(threading.Thread):
    def __init__(self, root_dir, address=None, timeout=0.001, dtp_handler=None):
        threading.Thread.__init__(self)
        self.__flag = threading.Event()
        self.__timeout = timeout
        authorizer = DummyAuthorizer()
        authorizer.add_anonymous(root_dir)
        handler = FTPHandler
        handler.authorizer = authorizer
        if dtp_handler is not None:
            handler.dtp_handler = dtp_handler
        self.server = FTPServer(address, handler)

    def start(self):
        self.__flag.clear()
        threading.Thread.start(self)
        self.__flag.wait()

    def run(self):
        self.__flag.set()
        while self.__flag.is_set():
            self.server.serve_forever(timeout=self.__timeout, blocking=False)
        self.server.close_all()
        self.server.close()

    def stop(self):
        self.__flag.clear()
        self.join()
开发者ID:jvivian,项目名称:s3am,代码行数:30,代码来源:FTPd.py

示例2: run

# 需要导入模块: from pyftpdlib.servers import FTPServer [as 别名]
# 或者: from pyftpdlib.servers.FTPServer import close_all [as 别名]
def run(ns):
	"""starts the server."""
	auth = DummyAuthorizer()
	if ns.user is not None:
		auth.add_user(ns.user, ns.pswd, ns.path, perm=ns.perm)
	else:
		auth.add_anonymous(ns.path, perm=ns.perm)
	handler = FTPHandler
	handler.authorizer = auth
	handler.banner = "StaSh v{v} FTP-Server".format(v=_stash.__version__)
	address = ("0.0.0.0", ns.port)
	server = FTPServer(address, handler)
	server.max_cons = 128
	server.max_cons_per_ip = 128
	# setup logging
	logger = logging.getLogger("pyftpdlib")
	logger.setLevel(logging.CRITICAL)
	logger.propagate = False
	# server needs to run in a thread to be killable
	thr = threading.Thread(
		name="FTP-Server Thread", target=server.serve_forever
		)
	thr.daemon = True
	thr.start()
	print("FTP-Server started on {h}:{p}".format(h=address[0], p=str(address[1])))
	try:
		while True:
			time.sleep(0.2)
	except KeyboardInterrupt:
		print("Stopping Server...")
		server.close_all()
开发者ID:BBOOXX,项目名称:stash,代码行数:33,代码来源:ftpserver.py

示例3: __init__

# 需要导入模块: from pyftpdlib.servers import FTPServer [as 别名]
# 或者: from pyftpdlib.servers.FTPServer import close_all [as 别名]
class MyServerFtp:
	
	def __init__(self):
		self.error = False
		self.port = 2121
	def __exit__(self, *err	):
        	self.close()
	def serverStart(self,port,location):
		try:
			self.error = False
			self.authorizer = DummyAuthorizer()
			self.authorizer.add_user('user', 'sk', location , perm='elradfmwM')

			self.handler = FTPHandler
			self.handler.authorizer = self.authorizer

			self.handler.banner = "ftp Server ready"
			self.address = ('', port)
			self.server = FTPServer(self.address, self.handler)
	
			self.server.max_cons = 256
			self.server.max_cons_per_ip = 5
			
			self.thread = threading.Thread(target = self.server.serve_forever)
			self.thread.deamon = True
			self.thread.start()
		except socket.error:
			self.error = True
			pass

	def errorOccured(self):
		return self.error

	def serverStop(self):
		self.server.close_all()
开发者ID:Shivakishore14,项目名称:FShare,代码行数:37,代码来源:fsharev1.py

示例4: ftpstop

# 需要导入模块: from pyftpdlib.servers import FTPServer [as 别名]
# 或者: from pyftpdlib.servers.FTPServer import close_all [as 别名]
def ftpstop():
    authorizer = DummyAuthorizer()
    handler = FTPHandler
    handler.authorizer = authorizer
    address = ('', 2121)
    server = FTPServer(address, handler)
    #server.serve_forever()
    server.close_all()
开发者ID:070499,项目名称:service.lan.ftp,代码行数:10,代码来源:FTPtest.py

示例5: main

# 需要导入模块: from pyftpdlib.servers import FTPServer [as 别名]
# 或者: from pyftpdlib.servers.FTPServer import close_all [as 别名]
def main():
    """Start a stand alone anonymous FTP server."""
    usage = "python -m pyftpdlib.ftpserver [options]"
    parser = optparse.OptionParser(usage=usage, description=main.__doc__,
                                   formatter=CustomizedOptionFormatter())
    parser.add_option('-i', '--interface', default=None, metavar="ADDRESS",
                      help="specify the interface to run on (default all "
                           "interfaces)")
    parser.add_option('-p', '--port', type="int", default=2121, metavar="PORT",
                      help="specify port number to run on (default 21)")
    parser.add_option('-w', '--write', action="store_true", default=False,
                      help="grants write access for the anonymous user "
                           "(default read-only)")
    parser.add_option('-d', '--directory', default=getcwdu(), metavar="FOLDER",
                      help="specify the directory to share (default current "
                           "directory)")
    parser.add_option('-n', '--nat-address', default=None, metavar="ADDRESS",
                      help="the NAT address to use for passive connections")
    parser.add_option('-r', '--range', default=None, metavar="FROM-TO",
                      help="the range of TCP ports to use for passive "
                           "connections (e.g. -r 8000-9000)")
    parser.add_option('-v', '--version', action='store_true',
                      help="print pyftpdlib version and exit")

    options, args = parser.parse_args()
    if options.version:
        sys.exit("pyftpdlib %s" % __ver__)
    passive_ports = None
    if options.range:
        try:
            start, stop = options.range.split('-')
            start = int(start)
            stop = int(stop)
        except ValueError:
            parser.error('invalid argument passed to -r option')
        else:
            passive_ports = list(range(start, stop + 1))
    # On recent Windows versions, if address is not specified and IPv6
    # is installed the socket will listen on IPv6 by default; in this
    # case we force IPv4 instead.
    if os.name in ('nt', 'ce') and not options.interface:
        options.interface = '0.0.0.0'

    authorizer = DummyAuthorizer()
    perm = options.write and "elradfmwM" or "elr"
    authorizer.add_anonymous(options.directory, perm=perm)
    handler = FTPHandler
    handler.authorizer = authorizer
    handler.masquerade_address = options.nat_address
    handler.passive_ports = passive_ports
    ftpd = FTPServer((options.interface, options.port), FTPHandler)
    try:
        ftpd.serve_forever()
    finally:
        ftpd.close_all()
开发者ID:MagicGroup,项目名称:magicinstaller2,代码行数:57,代码来源:__main__.py

示例6: FtpThread

# 需要导入模块: from pyftpdlib.servers import FTPServer [as 别名]
# 或者: from pyftpdlib.servers.FTPServer import close_all [as 别名]
class FtpThread(threading.Thread):
    def __init__(self, source_path, ip='0.0.0.0', port=2121, username='root', password='root'):
        self.ip = ip
        self.port = port
        self.username = username
        self.password = password
        if not os.path.exists(source_path):
            raise ValueError('Path doesnt exist - ({})'.format(source_path))
        self.source_path = source_path
        threading.Thread.__init__(self)

    def run(self, *args, **kwargs):
        authorizer = DummyAuthorizer()
        authorizer.add_user(self.username, self.password, self.source_path, perm='elradfmwM')
        handler = FTPHandler
        handler.authorizer = authorizer

        # logging.basicConfig(filename='/var/log/verteiler_ftp.log', level=logging.INFO)
        handler.banner = "pyftpdlib based ftpd ready."
        address = (self.ip, self.port)
        self.server = FTPServer(address, handler)
        self.server.max_cons = 256
        self.server.max_cons_per_ip = 5
        self.server.serve_forever()

    def stop(self):
        self.server.close_all()

    @staticmethod
    def startup_server_thread_with_fixed_lifetime(source_path, seconds=FTP_SERVER_LIFETIME):
        '''
            Ftp server launch SYNCH for infinity (seconds=None) or  for fixed no of seconds
        '''
        server = FtpThread(source_path=source_path)
        server.start()
        if seconds:
            time.sleep(seconds)
            server.stop()

    @staticmethod
    def launch_ftp_server_with_fixed_lifetime(source_path, seconds=FTP_SERVER_LIFETIME):
        '''
            Ftp server launch ASYNCH for infinity (seconds=None) or for fixed no of seconds
        '''

        def worker():
            FtpThread.startup_server_thread_with_fixed_lifetime(seconds=seconds, source_path=source_path)

        thread = threading.Thread(target=worker)
        thread.start()
开发者ID:rwrzosu,项目名称:pq_mocker,代码行数:52,代码来源:ftp_server.py

示例7: main

# 需要导入模块: from pyftpdlib.servers import FTPServer [as 别名]
# 或者: from pyftpdlib.servers.FTPServer import close_all [as 别名]
def main():
	authorizer = DummyAuthorizer()
	authorizer.add_anonymous(os.path.expanduser('~/Documents'), perm='elradfmwM')
	handler = FTPHandler
	handler.authorizer = authorizer
	server = FTPServer(('0.0.0.0', 2121), handler)
	t = threading.Thread(target=server.serve_forever)
	t.start()
	print 'Server started.'
	print '\nConnect as guest/anonymous user to ftp://localhost:2121 (from this device) or "ftp://%s.local:2121" (from other devices in your network)' % (gethostname(),)
	try:
		while True: pass
	except KeyboardInterrupt:
		server.close_all()
		print 'Server stopped'
开发者ID:c0ns0le,项目名称:Pythonista,代码行数:17,代码来源:PythonistaFTP.py

示例8: main

# 需要导入模块: from pyftpdlib.servers import FTPServer [as 别名]
# 或者: from pyftpdlib.servers.FTPServer import close_all [as 别名]
def main():
	authorizer = DummyAuthorizer()
	authorizer.add_anonymous(os.path.expanduser('~/Documents'), perm='elradfmwM')
	handler = FTPHandler
	handler.authorizer = authorizer
	server = FTPServer(('0.0.0.0', 2121), handler)
	t = threading.Thread(target=server.serve_forever)
	t.start()
	print 'Server started.'
	print '\nConnect as guest/anonymous user to ftp://localhost:2121 (from this device) or "ftp://(YOUR_IP_ADDRESS):2121" (from other devices in your network -- you can find the IP address of your device in the WiFi settings)'
	try:
		while True: pass
	except KeyboardInterrupt:
		server.close_all()
		print 'Server stopped'
开发者ID:miwagner1,项目名称:Pythonista,代码行数:17,代码来源:FTPserver.py

示例9: FTPServerBase

# 需要导入模块: from pyftpdlib.servers import FTPServer [as 别名]
# 或者: from pyftpdlib.servers.FTPServer import close_all [as 别名]
class FTPServerBase(unittest.TestCase):
    def _run_ftp_server(self):
        self.server.serve_forever()

    def _setup_home(self):
        """ Initialize the temporary homedir of the test user
        """
        self.home = tempfile.mkdtemp()
        self.storage = tempfile.mkdtemp()
        tempfile.NamedTemporaryFile(dir=self.home)

    def _teardown_home(self):
        pass

    def setUp(self):
        self.ftp = None
        self.host = 'localhost'
        self.port = 9001
        self._setup_home()
        authorizer = DummyAuthorizer()
        authorizer.add_user('vagrant', 'vagrant', self.home, perm='elrdfmw')
        authorizer.add_anonymous(self.home)
        handler = FTPHandler
        handler.authorizer = authorizer
        self.server = FTPServer((self.host, self.port), handler)
        # run ftp server in a separate thread so as to not block tests from running
        self.thread = threading.Thread(target=self._run_ftp_server)
        self.thread.daemon = True
        self.thread.start()
        self.ftp = lftp.LFTP(self.host, self.port, 'vagrant', 'vagrant')

    def tearDown(self):
        if self.ftp:
            self.ftp.disconnect()
        self.server.close_all()
        self._teardown_home()

    def test_empty_homedir(self):
        ftp = self.ftp
        # listing of an empty directory
        ls = ftp.list()
        self.assertEqual(ls, "")

    def test_dir(self):
        ftp = self.ftp
        tempdir = tempfile.mkdtemp(dir=self.home)
        ls = ftp.list()
        ls.should.contain(os.path.basename(tempdir))
开发者ID:minadyn,项目名称:lftppy,代码行数:50,代码来源:testlftp.py

示例10: TestFTPServer

# 需要导入模块: from pyftpdlib.servers import FTPServer [as 别名]
# 或者: from pyftpdlib.servers.FTPServer import close_all [as 别名]
class TestFTPServer(object):
    class FTPThread(threading.Thread):
        def __init__(self, server, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.server = server

        def run(self):
            try:
                self.server.serve_forever()
            except OSError:
                pass

    def __init__(self):
        self.temp_dir = tempfile.mkdtemp()
        os.mkdir(os.path.join(self.temp_dir, "dir1"))
        with open(os.path.join(self.temp_dir, "file1.txt"), 'w') as f:
            f.write("Test")
        with open(os.path.join(self.temp_dir, "file2.txt"), 'w') as f:
            f.write("Test")

        authorizer = DummyAuthorizer()
        authorizer.add_user("username1", "password1", self.temp_dir, perm='elradfmwMT')
        handler = FTPHandler
        handler.authorizer = authorizer
        self.server = FTPServer(("127.0.0.1", 2121), handler)
        self.server_thread = TestFTPServer.FTPThread(server = self.server)

    def clean_temp_dir(self):
        os.remove(os.path.join(self.temp_dir, "file1.txt"))
        os.remove(os.path.join(self.temp_dir, "file2.txt"))
        if os.path.exists(os.path.join(self.temp_dir, "file3.txt")):
            os.remove(os.path.join(self.temp_dir, "file3.txt"))
        os.rmdir(os.path.join(self.temp_dir, "dir1"))
        os.rmdir(self.temp_dir)

    def start(self):
        self.server_thread.start()

    def stop(self):
        self.server.close_all()
        self.server_thread.join()
        self.clean_temp_dir()
开发者ID:dripfeeder,项目名称:teleftp,代码行数:44,代码来源:__init__.py

示例11: FTPtest

# 需要导入模块: from pyftpdlib.servers import FTPServer [as 别名]
# 或者: from pyftpdlib.servers.FTPServer import close_all [as 别名]

#.........这里部分代码省略.........
        # handler.passive_ports = range(60000, 65535)

        # Instantiate FTP server class and listen on every IP address of the machine on port 2121
        # If you use this port, please use the iptables command provided in the installation documentation
        # If you configured your system so users can listen on ports below 1024, you can set this to 21 and fotget the command
        self.address = ("", 2121)
        self.server = FTPServer(self.address, self.handler)

        # set a limit for connections
        self.server.max_cons = 256
        self.server.max_cons_per_ip = 5

    # Define a new user having full r/w permissions and a read-only
    def addUser(self, username, password):
        directory = os.getcwd() + "/testdata"
        print "adding user " + username + " and pw " + password
        self.authorizer.add_user(username, password, directory, perm="elradfmw")

    # Removes an user from the server
    def delUser(self, username):
        self.authorizer.remove_user(username)
        print "deletd user", username

    # Get some random directories to create within the server
    def getRandomDirs(self):
        htdocDirs = ["htdocs", "www", "www-data", "htdoc", "web"]
        htdocDir = random.choice(htdocDirs)
        dirs = [
            "isos",
            "wareZ",
            "pron",
            "files",
            "logs",
            "conficential",
            "misc",
            "funny",
            "photos",
            "gf",
            "share",
            "saves",
        ]
        dirs.append(htdocDir)
        numOfPossibleDirs = len(dirs)
        numOfDirs = random.randrange(0, numOfPossibleDirs)
        return random.sample(set(dirs), numOfDirs)

    # Get some random timestamps between the set start timestamp and now, so the timestamps on the server aren't weird
    def getRandomTimestamp(self):
        endTimestamp = time.time()
        startTimestamp = 1353073006.547738
        return startTimestamp + random.random() * (endTimestamp - startTimestamp)

    # Copy a random subset of data from the possibledata directory to the FTP server directory - then create some random directorys
    def populateFiles(self):
        # The path to the bait and safe data
        source = os.getcwd() + "/possibledata/"
        # The path to the FTP server directory
        destination = os.getcwd() + "/testdata/"
        # The uid and gid of the current user
        currentUser = os.getuid()
        currentGroup = os.getegid()

        # Whipe the whole directory the server had before and create a new one
        shutil.rmtree(destination, ignore_errors=True)
        os.mkdir(destination)

        filesToCleanUp = os.listdir(destination)
        for fileToRemove in filesToCleanUp:
            os.remove(destination + fileToRemove)

        # Get the random subset of files from the bait and safe data and copy them into the FTP directory
        allPossibleFiles = os.listdir(source)
        print allPossibleFiles
        numOfPossibleFiles = len(allPossibleFiles)
        numOfFilesToCopy = random.randrange(1, numOfPossibleFiles)

        filesToCopy = random.sample(set(allPossibleFiles), numOfFilesToCopy)

        for fileToCopy in filesToCopy:
            dstFile = destination + fileToCopy
            shutil.copy2(source + fileToCopy, dstFile)
            os.chown(dstFile, currentUser, currentGroup)
            fileTimestamp = self.getRandomTimestamp()
            os.utime(dstFile, (fileTimestamp, fileTimestamp))

        # Create the random directories
        dirsToCreate = self.getRandomDirs()
        for dirToCreate in dirsToCreate:
            dstPath = destination + dirToCreate
            os.mkdir(dstPath)
            dirTimestamp = self.getRandomTimestamp()
            os.utime(dstPath, (dirTimestamp, dirTimestamp))

    # start the FTP server
    def run(self):
        self.server.serve_forever()

    # stop the FTP server
    def stop(self):
        self.server.close_all()
开发者ID:rkoewer,项目名称:HoneyConnector,代码行数:104,代码来源:FTPtest.py

示例12: notification

# 需要导入模块: from pyftpdlib.servers import FTPServer [as 别名]
# 或者: from pyftpdlib.servers.FTPServer import close_all [as 别名]
		for tn in ['01','02','03','04','05','06','07','08','09','10']:
			if (tfalse(addst(tn+"-enable","false"))==True):
				tt={}; tt['path']=xbmc.validatePath(xbmc.translatePath(addst(tn+"-path","special://logpath"))) #.replace(pFindWhat,"|tag|").replace("|tag|",pReplaceWith)
				tt['user']=addst(tn+"-user",""); tt['pass']=addst(tn+"-pass","xbmchub"); tt['perm']=addst(tn+"-perm","elradfmwM")
				if (len(tt['user']) > 0) and (len(tt['path']) > 0):
					print "user : "+str(tt['user'])+" : path :"+str(tt['path'])+" :"
					try: authorizer.add_user(tt['user'],tt['pass'],tt['path'],perm=tt['perm'])
					except: print"Error adding user: "+str(tt['user']); pass
		handler=FTPHandler; handler.authorizer=authorizer; handler.banner="pyftpdlib based ftpd ready."
		try: LiP=addst("address","")
		except: LiP=""
		try: Lport=int(addst("port","2121"))
		except: Lport=2121
		address=(LiP,Lport); server=FTPServer(address,handler); server.max_cons=int(addst("max-connections","5")); server.max_cons_per_ip=int(addst("max-connections-per-ip","5")); 
		print "Starting Server... Port: "+str(Lport); notification("FTP Server","Starting Server... Port: "+str(Lport))
		#server.serve_forever()
		try: server.serve_forever(timeout=int(addst("timeout","10")),blocking=False)
		except: pass
	elif (STARTUP==False) and (ENABLED==True):
		try: server.serve_forever(timeout=int(addst("timeout","10")),blocking=False)
		except: pass
print "Service While Loop has been exited."; print "isEnabled="+str(ENABLED); print "Attempting to Close Server...."; notification("FTP Server","Attempting to Close Server....")
addstv("is-serivce-running","false")
try: server.ip_map=[]
except: print "failed: server.ip_map=[]"; pass
try: server.socket.close()
except: print "failed: server.socket.close()"; pass
try: server.close_all()
except: pass
sys.exit()
开发者ID:070499,项目名称:service.lan.ftp,代码行数:32,代码来源:service.py

示例13: run_server

# 需要导入模块: from pyftpdlib.servers import FTPServer [as 别名]
# 或者: from pyftpdlib.servers.FTPServer import close_all [as 别名]

#.........这里部分代码省略.........
    #     # Don't check project or execution of the workflow will not be allowed because input resource is missing
    #     workflow = pp.parse_project()
    #     print workflow._processes
    #     print [res.url for res in workflow._processes[0].inputs]
    #     workflow.prepare_execution()
    #     workflow.run()
    #     assert isfile("tuttle.html")

    @isolate
    def test_pre_check_before_running(self):
        """ Pre check should happen for each process before run the whole workflow """
        project = """file://A <-
        obvious failure
file://google.html <- file://A ! download
        """
        rcode, output = run_tuttle_file(project)
        assert rcode == 2
        assert output.find("Download processor") >= 0, output

    @isolate
    def test_no_error_with_download_process(self):
        """ Download process does not create code in reserved_path for the process... Thus it cant be moved when """
        """ retreiving logs and reserved path from previous execution(from bug) """
        project = """file://g <-  http://localhost:8043/a_resource ! download

file://h <- file://g
    ERROR
        """
        rcode, output = run_tuttle_file(project)
        assert rcode == 2, output
        rcode, output = tuttle_invalidate()
        assert rcode == 0, output
        rcode, output = run_tuttle_file()
        assert rcode == 2, output

    @isolate
    def test_pre_check_before_invalidation(self):
        """Pre check should happen before invalidation"""
        project1 = """file://A <-
        echo A > A
        """
        rcode, output = run_tuttle_file(project1)
        assert isfile('A')
        project2 = """file://A <-
        echo different > A
file://google.html <- file://A ! download
        """
        rcode, output = run_tuttle_file(project2)
        assert rcode == 2
        assert output.find("* file://B") == -1
        assert output.find("Download processor") >= 0, output

    @isolate
    def test_download_https(self):
        """ https download should work """
        if not online:
            raise SkipTest("Offline")
        project = "file://google.html <- https://www.google.com/ ! download"
        rcode, output = run_tuttle_file(project)

        if output.find("SSL certificate problem: unable to get local issuer certificate") >= 0:
            raise SkipTest("Skip test because of a certificate bug from appveyor")

        assert rcode == 0, output
        assert isfile("google.html")
        content = open("google.html").read()
        assert content.find("<title>Google</title>") >= 0
        logs = open(join(".tuttle", "processes", "logs", "tuttlefile_1_stdout.txt"), "r").read()
        assert re.search("\n\.+\n", logs) is not None, logs
        assert isfile(join(".tuttle", "processes", "logs", "tuttlefile_1_err.txt"))

    def run_ftp_server(self):
        authorizer = DummyAuthorizer()
        ftp_dir = join(dirname(__file__), 'ftp')
        authorizer.add_user("user", "password", ftp_dir, perm="elrd")
        handler = FTPHandler
        handler.authorizer = authorizer
        self._ftpd = FTPServer(("0.0.0.0", 8021), handler)
        self._ftpd.serve_forever(timeout=0.2, handle_exit=True)

    @isolate
    def test_download_ftp_resource(self):
        """Download processor should be able to download an ftp resource with authentification """
        from threading import Thread
        p = Thread(target=self.run_ftp_server)
        p.start()
        try:
            sleep(0.1)  # The server needs time to start

            project = """file://downloaded_resource <- ftp://localhost:8021/ftp_resource ! download
            """
            passfile = join(dirname(__file__), '.tuttlepass')
            with EnvVar('TUTTLEPASSFILE', passfile):
                rcode, output = run_tuttle_file(project)
            assert rcode == 0, output
            assert isfile('downloaded_resource')
        finally:
            self._ftpd.close_all()
            self._ftpd.ioloop.close()
            p.join()
开发者ID:lexman,项目名称:tuttle,代码行数:104,代码来源:test_net_addon.py

示例14: SimpleFtpWindow

# 需要导入模块: from pyftpdlib.servers import FTPServer [as 别名]
# 或者: from pyftpdlib.servers.FTPServer import close_all [as 别名]
class SimpleFtpWindow(QtGui.QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        
    def initUI(self):
        self.setFixedSize(415, 185)
        self.setWindowTitle('Simple FTP Server')
        
        self.Directory = QtGui.QLineEdit(self)
        self.Directory.setGeometry(10, 50, 270, 25)
        self.SetDirectory = QtGui.QPushButton(self)
        self.SetDirectory.setGeometry(285, 50, 120, 25)
        self.groupBox = QtGui.QGroupBox(self)
        self.groupBox.setGeometry(10, 90, 395, 50)
        self.OnButton = QtGui.QRadioButton(self.groupBox)
        self.OnButton.setGeometry(90, 20, 90, 15)
        self.OffButton = QtGui.QRadioButton(self.groupBox)
        self.OffButton.setGeometry(220, 20, 90, 15)
        self.Subject = QtGui.QLabel(self)
        self.Subject.setGeometry(10, 10, 395, 30)
        self.Result = QtGui.QLabel(self)
        self.Result.setGeometry(10, 150, 395, 30)
        
        self.SetDirectory.setText("Choose Directoy")
        self.groupBox.setTitle("Power")
        self.Result.setText("")
        self.OnButton.setText("On")
        self.OffButton.setText("Off")
        self.OffButton.setChecked(1)
        self.Subject.setText("Simple FTP Server")
        
        self.action()
        self.show()
        
    def action(self):
        self.SetDirectory.clicked.connect(self.openDirectoryDialog)
        self.OnButton.clicked.connect(self.on_clicked)
        self.OffButton.clicked.connect(self.off_clicked)
    
    def openDirectoryDialog(self):
        #path, _ = QtGui.QFileDialog.getOpenFileName(self, "Open File", os.getcwd())
        self.flags = QtGui.QFileDialog.DontResolveSymlinks | QtGui.QFileDialog.ShowDirsOnly
        self.path = directory = QtGui.QFileDialog.getExistingDirectory(self, "Open Directory", os.getcwd(), self.flags)
        self.Directory.setText(self.path)
        
    def on_clicked(self):
        #global server
        authorizer = DummyAuthorizer()
        try:
            authorizer.add_anonymous(self.Directory.text())
        except:
            authorizer.add_anonymous(os.getcwd())
        logging.basicConfig(filename='ftpd.log', level=logging.INFO)
        handler = FTPHandler
        handler.authorizer = authorizer
        self.server = FTPServer(('0.0.0.0', 21), handler)
        self.th = threading.Thread(target=self.server.serve_forever)
        self.th.start()
        self.Result.setText('on, 127.0.0.1:21, anonymous')
        
    def off_clicked(self):
        self.server.close_all()
        self.th.join()
        self.Result.setText('off')
        
    def closeEvent(self, event):
        reply = QtGui.QMessageBox.question(self, 'Message',
            "Are you sure to quit?", QtGui.QMessageBox.Yes | 
            QtGui.QMessageBox.No, QtGui.QMessageBox.No)
        
        if reply == QtGui.QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()
开发者ID:silmang,项目名称:Simple-Ftp-Server,代码行数:77,代码来源:ftpserver.py


注:本文中的pyftpdlib.servers.FTPServer.close_all方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。