Exemple #1
0
def ftpServer(dirPath, account, password):
    # 实例化用户授权管理
    authorizer = DummyAuthorizer()
    authorizer.add_user(account, password, dirPath, perm='elradfmwMT')  # 添加用户 参数:username,password,允许的路径,权限
    authorizer.add_anonymous(os.getcwd())  # 这里是允许匿名用户,如果不允许删掉此行即可

    # 实例化FTPHandler
    handler = FTPHandler
    handler.authorizer = authorizer

    # 设定一个客户端链接时的标语
    handler.banner = "pyftpdlib based ftpd ready."

    # handler.masquerade_address = '151.25.42.11'#指定伪装ip地址
    # handler.passive_ports = range(60000, 65535)#指定允许的端口范围

    address = ('0.0.0.0', 21)  # FTP一般使用21,20端口
    server = ThreadedFTPServer(address, handler)  # FTP服务器实例

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

    # 开启服务器
    server.serve_forever()
def main():
    authorizer = DummyAuthorizer()
    authorizer.add_user('user', '12345', '.')
    handler = FTPHandler
    handler.authorizer = authorizer
    server = ThreadedFTPServer(('', 2121), handler)
    server.serve_forever()
Exemple #3
0
class FTPServer:

    server = None

    def __init__(self, user):

        authorizer = DummyAuthorizer()

        authorizer.add_user(user.username,
                            user.password,
                            user.dir_,
                            perm=user.permissions)

        handler = FTPHandler
        handler.authorizer = authorizer

        address = (str(ip_retriever.get_ip_address()), 2121)
        self.server = ThreadedFTPServer(address, handler)

        self.server.max_cons = 10
        self.server.max_cons_per_ip = 5

        print('\nServer Address: ftp://{}:{}\n'.format(address[0], address[1]))

    def start_server(self):

        self.server.serve_forever()
Exemple #4
0
def start_ftp(masquerade_address, listen_address, port, log_level, internal,
              passive_ports):

    LogLevel = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
    if log_level in LogLevel:
        for lev in LogLevel:
            if log_level == lev:
                level = lev
    else:
        print "wrong loglevel parameter: %s" % log_level
        exit(1)

    authorizer = ObsAuthorizer()
    authorizer.internal = internal
    handler = FTPHandler
    handler.passive_ports = passive_ports
    handler.permit_foreign_addresses = True
    if handler.masquerade_address != "":
        handler.masquerade_address = masquerade_address
    handler.authorizer = authorizer
    handler.abstracted_fs = AbstrFileToObs
    handler.banner = 'obs ftpd ready.'
    address = (listen_address, port)
    set_logger(level)
    server_muti = ThreadedFTPServer(address, handler)
    server_muti.serve_forever()
Exemple #5
0
class ftp_server(object):
    # Create Random Username and Password
    def __init__(self, Dir='/tmp', Port=2121):
        self.Dir = Dir
        self.Port = Port
        # Get Local Server Address
        self.Addr = _get_local_ip()

    def _run_server(self):
        # Create Dummy Authorizer, with the random user/pass
        self.authorizer = DummyAuthorizer()
        self.authorizer.add_user(self.User,
                                 self.Pass,
                                 self.Dir,
                                 perm='elradfmw')
        self.handler = FTPHandler
        self.handler.authorizer = self.authorizer
        # Instantiate the FTP Server
        self.SRV = ThreadedFTPServer(('0.0.0.0', self.Port), self.handler)
        self.SRV.serve_forever()

    def start(self):
        # Random user/pass
        self.User = _random_string()
        self.Pass = _random_string()
        # Start separate process calling Run Server function
        self.srv = multiprocessing.Process(target=self._run_server)
        self.srv.start()

    def stop(self):
        # Close all connections immediately
        self.srv.kill()
Exemple #6
0
def main():
    authorizer = DummyAuthorizer()
    authorizer.add_user("user", "12345", ".")
    handler = FTPHandler
    handler.authorizer = authorizer
    server = ThreadedFTPServer(("", 2121), handler)
    server.serve_forever()
Exemple #7
0
def main():
    # 新建一个用户组
    authorizer = DummyAuthorizer()
    # 将用户名,密码,指定目录,权限 添加到里面
    authorizer.add_user("root", "123456", ".", perm="elradfmwMT")  # adfmw
    # 这个是添加匿名用户,任何人都可以访问,如果去掉的话,需要输入用户名和密码,可以自己尝试
    authorizer.add_anonymous(".")

    # 带宽限制
    dtp_handler = ThrottledDTPHandler
    dtp_handler.read_limit = 1024 * 1024  # 1M/sec (1024 * 1024)
    dtp_handler.write_limit = 1024 * 1024  # 1M/sec (1024 * 1024)

    # FTP初始参数设置
    handler = MyHandler
    handler.timeout = 300
    handler.authorizer = authorizer
    handler.banner = "Ftp Ready......"  # 进入欢迎语
    handler.dtp_handler = dtp_handler

    # 日志
    logging.basicConfig(filename='Ftp.log', level=logging.INFO)

    # 开启服务器
    server = ThreadedFTPServer(("0.0.0.0", 21), handler)
    server.max_cons = 500
    server.max_cons_per_ip = 10
    server.serve_forever()
def main():
    authorizer = DummyAuthorizer()
    authorizer.add_user('user', '12345', '.')
    handler = FTPHandler
    handler.authorizer = authorizer
    server = ThreadedFTPServer(('', 2121), handler)
    server.serve_forever()
Exemple #9
0
def ftpStart(anoDir="",
             anoPerm="elr",
             ip="127.0.0.1",
             port=21,
             pasvPortBegin=60000,
             pasvPortEnd=65535,
             users=[],
             maxCons=512,
             maxConsPerIp=0):
    try:
        # step1:实例化用户授权管理
        authorizer = DummyAuthorizer()
        # step2:添加匿名用户,任何人都可以访问
        if len(anoDir) > 0:
            authorizer.add_anonymous(anoDir, perm=anoPerm)
        # step3:添加非匿名用户名,密码,指定目录,权限
        for user in users:
            authorizer.add_user(user["name"],
                                user["pwd"],
                                user["dir"],
                                perm=user["perm"])
        # step4:实例化FTPHandler
        handler = FTPHandler
        handler.authorizer = authorizer
        handler.passive_ports = range(pasvPortBegin, pasvPortEnd)
        # step5:配置服务器
        server = ThreadedFTPServer((ip, port), handler)
        server.max_cons = maxCons
        server.max_cons_per_ip = maxConsPerIp
        # step6:开启服务器
        server.serve_forever()
    except:
        print("Exception: ftp_server.ftpStart =>\n           " +
              str(sys.exc_info()))
Exemple #10
0
class Server(threading.Thread):
	def __init__(self, ip, path, users, port, password):
		super(Server, self).__init__()
		self.ip = ip
		self.path = path
		self.users = users
		self.port = port
		self.auth = DummyAuthorizer()
		self.handler = CustomFTP(self.auth, self.port, path, password)
		# self.handler.authorizer = self.auth
		print 'starting server on port %d' % (self.port)
		[self.add_user(self.path, u, password) for u in self.users]

	def start_thread(self):
		self.start()
		return self

	def add_user(self, path, user, password):
		pathn = os.path.join(path, str(self.port))
		if not os.path.exists(pathn): os.mkdir(pathn)
		self.auth.add_user(user, password, pathn, perm="elr") # elradfmw

	def run(self):
		self.server = ThreadedFTPServer((self.ip, self.port), self.handler)
		self.server.serve_forever()
Exemple #11
0
def main():
    authorizer = DummyAuthorizer()
    authorizer.add_user(USER, PWD, ftp_root, perm='elradfmw')
    handler = FTPHandler
    handler.authorizer = authorizer
    server = ThreadedFTPServer((ftp_address, ftp_port), handler)
    server.serve_forever()
Exemple #12
0
class ftp_server:
    def __init__(self):
        authorizer = DummyAuthorizer()
        authorizer.add_user('user', '12345', 'collected/', perm='elradfmwMT')
        authorizer.add_anonymous("collected/", perm='elradfmwMT')
        self.handler = MyHandler
        self.handler.authorizer = authorizer
        self.obj = ThreadedFTPServer(("0.0.0.0", 21), self.handler)
        self.filename = ""
        # set a limit for connections
        #self.max_cons = 256
        #self.max_cons_per_ip = 5

    def get_filename(self):
        global filename
        return filename

    def _run_server(self):
        self.obj.serve_forever()

    def start(self):
        srv = threading.Thread(target=self._run_server)
        srv.deamon = True
        srv.start()

    def stop(self):
        self.obj.close_all()
Exemple #13
0
def main():
    authorizer = DummyAuthorizer()
#    authorizer.add_user('user', '12345', '.')
    authorizer.add_anonymous(os.getcwd(),perm='elradfmw')
    handler = FTPHandler
    handler.authorizer = authorizer
    server = ThreadedFTPServer(('0.0.0.0', 21), handler)
    server.serve_forever()
Exemple #14
0
def main():
    authorizer = DummyAuthorizer()
    authorizer.add_user('1', '1', '/')
    handler = EncodedHandler

    handler.authorizer = authorizer
    server = ThreadedFTPServer(('', 21), handler)
    server.serve_forever()
Exemple #15
0
def runFTP():
    try:
        handler = FTPHandler
        handler.authorizer = listusersftp
        serverFTP = ThreadedFTPServer((IP_ADDRESS, PORT_FTP), handler)
        serverFTP.serve_forever()
    except:
        print("FTP cannot Run")
        return
Exemple #16
0
class ServeurFTP(Thread):
    port = "12345"
    server = None
    handler = None
    authorizer = None
    repertory = "./fichiers"

    # daemon = False
    # threadftp = None

    def __init__(self, port):
        Thread.__init__(self)
        self.daemon = True

        self.port = port

    def isin(self, file):
        retour = False

        Rfile = file.split('/')
        if len(Rfile) > 0:
            file = Rfile[-1]

        files = os.listdir(self.repertory)
        if file in files:
            retour = True

        return retour

    def run(self=object):
        print("# FTPD Forever: demarrage")

        # Thread.run(self)
        config_logging(0)
        self.authorizer = DummyAuthorizer()
        self.authorizer.add_anonymous(self.repertory, perm='elradfmwM')

        # handler = CustomFtpHandler
        self.handler = FTPHandler
        self.handler.authorizer = self.authorizer

        address = ('0.0.0.0', self.port)
        # self.server = FTPServer(address, self.handler)
        self.server = ThreadedFTPServer(address, self.handler)

        self.server.serve_forever(timeout=1, blocking=True, handle_exit=False)
        # self.server.serve_forever(timeout=1, blocking=True, handle_exit=False)
        # self.server.serve_forever(timeout=None, blocking=True, handle_exit=False)

        print("# FTPD Forever: sortie fonction run")

    @classmethod
    def stop(self):
        print("# Fermeture du service FTP")
        self.handler.close()
        self.server = None
def main():
    authorizer = DummyAuthorizer()
    authorizer.add_anonymous('.', perm='elradfmwM')

    handler = FTPHandler
    handler.authorizer = authorizer
    handler.banner = "Connected"

    server = ThreadedFTPServer(('127.0.0.1', 3001), handler)
    server.serve_forever()
Exemple #18
0
class FTPServerThread(threading.Thread):
    def __init__(self, addr, homedir, *args, **kwargs):
        super(FTPServerThread, self).__init__(*args, **kwargs)
        authorizer = DummyAuthorizer()
        authorizer.add_anonymous(homedir, perm='elradfmwM')
        handler = FTPHandler
        handler.authorizer = authorizer
        self.ftpserver = ThreadedFTPServer(addr, handler)
                
    def run(self):
        self.ftpserver.serve_forever()
Exemple #19
0
def main():
    authorizer = DummyAuthorizer()
    authorizer.add_user("usr", "pw", "./dummyAWG", perm="elradfmw")
    authorizer.add_anonymous("./dummyAWG")
    #logging.basicConfig(filename='./logs/pyftpd.log', level=logging.INFO)

    handler = MyHandler
    handler.authorizer = authorizer

    server = ThreadedFTPServer((HOST, PORT), handler)
    server.serve_forever()
Exemple #20
0
def ftpServer(user, psw, port=2121, write=True):
    authorizer = DummyAuthorizer()
    if write == True:
    	authorizer.add_user(user, psw , '.', perm='elradfmwM')
    else:
    	authorizer.add_user(user, psw , '.')
    # authorizer.add_anonymous(os.getcwd())
    handler = FTPHandler
    handler.authorizer = authorizer
    server = ThreadedFTPServer(('0.0.0.0', port), handler)
    server.serve_forever()
def main():
    authorizer = DummyAuthorizer()
    authorizer.add_user(
        'ftpuser', 'pass', homedir=r'C:\Temp\TMP\DFS\Dnode2',
        perm='elradfmw')  # set username, password & homedirectory for the user
    handler = FTPHandler
    handler.authorizer = authorizer
    server = ThreadedFTPServer((host, port),
                               handler)  # Bind the host:port for FTP services
    print("Starting FTP Server on port:", port)
    server.serve_forever()  # Start FTP server
Exemple #22
0
def main():
  authorizer = DummyAuthorizer()
  authorizer.add_anonymous(os.getcwd())
  for user, password, path, permission in USER_PASS_PATH_PERM:
    authorizer.add_user(user, password, path, perm=permission)

  handler = FTPHandler
  handler.authorizer = authorizer
  handler.passive_ports = range(8000, 9000)

  server = ThreadedFTPServer(('', PORT), handler)
  server.serve_forever()
Exemple #23
0
def main():
    authorizer = DummyAuthorizer()
    authorizer.add_anonymous(os.getcwd())
    for user, password, path, permission in USER_PASS_PATH_PERM:
        authorizer.add_user(user, password, path, perm=permission)

    handler = FTPHandler
    handler.authorizer = authorizer
    handler.passive_ports = range(8000, 9000)

    server = ThreadedFTPServer(('', PORT), handler)
    server.serve_forever()
Exemple #24
0
def main():
    # Creates authorization for anonymous users
    # and gives them Read/Write access to the server
    authorizer = DummyAuthorizer()
    authorizer.add_anonymous('.', perm='elradfmwM')

    # Using the default pyftpdlib handler to handle
    # requests sent to the server
    handler = FTPHandler
    handler.authorizer = authorizer
    server = ThreadedFTPServer(('127.0.0.1', 1026), handler)
    server.serve_forever()
Exemple #25
0
def serve_fs(fs, addr, port):
    """
    Creates a basic anonymous FTP server serving the given FS on the given address/port
    combo.
    """
    ftp_handler = FTPFSHandler
    ftp_handler.authorizer = DummyAuthorizer()
    ftp_handler.use_sendfile = False
    ftp_handler.authorizer.add_anonymous('/', perm='elrdmw')
    ftp_handler.abstracted_fs = FTPFSFactory(fs)
    s = ThreadedFTPServer((addr, port), ftp_handler)
    s.serve_forever()
Exemple #26
0
class FTP_SERVER:
    def __init__(self):
        path = os.getcwd()
        if path.startswith('C'):
            os.chdir('\\')
        else:
            os.chdir('C:')
        self.hose_name = socket.gethostname()
        self.ip = socket.gethostbyname(self.hose_name)
        self.port = '21'
        self.root_dir = 'C:'
        self.server_address = '\EWTSS'
        self.log_address = 'EWTSS\log\change_log_name.txt'
        self.log_time = 'EWTSS\log\change_log_time.txt'
        self.log_folder = 'EWTSS\log'
        self.server = ThreadedFTPServer
        self.changes_cheker = Checker(self.server_address, self.log_address,
                                      self.log_time)

    def log_generator(self):
        if os.path.exists(self.log_folder):
            server_logger = Server_Logger(self.server_address,
                                          self.log_address, self.log_time)
        else:
            try:
                os.makedirs(self.log_folder)
                server_logger = Server_Logger(self.server_address,
                                              self.log_address)
            except Exception as e:
                print(e)

    def start(self):
        try:
            answer = pyautogui.confirm('Server will start on :: ' + self.ip,
                                       "FTP Server", ("Start", "Stop"))
            if answer == "Start":
                self.log_generator()
                try:
                    self.changes_cheker.start()
                except Exception as e:
                    print(e, ":: Starting Thread")
                authorizer = DummyAuthorizer()
                authorizer.add_user('EWTSS_FTP_USER', 'EWTSS', '.')
                handler = FTPHandler
                handler.authorizer = authorizer
                self.server = ThreadedFTPServer((self.ip, self.port), handler)
                self.server.serve_forever()

        except Exception as e:
            pyautogui.alert(text=str(e),
                            title=str(type(e).__name__),
                            button='Exit')
def start_server(home_dir, port):
    host = '127.0.0.1'
    authorizer = DummyAuthorizer()
    with open('./db.json') as f:
        auth_info = json.loads(f.read())
    for user in auth_info:
        if user.startswith('ds'):
            authorizer.add_user(user, auth_info[user], homedir=home_dir, perm='elradfmw')
    handler = FTPHandler
    handler.authorizer = authorizer
    server = ThreadedFTPServer((host, port), handler)
    print("Starting FTP Server on port:", port)
    server.serve_forever()
Exemple #28
0
def start_ftp(ftp_folder):
    """Start FTP server."""

    authorizer = DummyAuthorizer()
    authorizer.add_anonymous(str(ftp_folder), perm='elradfmw')

    handler = FTPHandler
    handler.authorizer = authorizer

    server = ThreadedFTPServer(('0.0.0.0', 21), handler)
    server.max_cons = 100
    server.max_cons_per_ip = 2

    server.serve_forever()
Exemple #29
0
def main():
    authorizer = DummyAuthorizer()
    global authorizer
    authorizer.add_user('client', 'vina2cluster', '.', perm='elradfmwM')
    authorizer.add_anonymous(os.getcwd())
    handler = MyHandler
    handler.authorizer = authorizer
    handler.banner = "Vina2Cluster FTP Server."
    handler.timeout = 30
    address = ('', port)
    server = ThreadedFTPServer(address, handler)
    server.max_cons = 10000
    server.max_cons_per_ip = 10000
    server.serve_forever()
Exemple #30
0
class PyFtpServer(Thread):
    def __init__(self, path, user, pwd, port):
        super(PyFtpServer, self).__init__(name="PyFtpServer")
        self._stop_event = threading.Event()

        self._path = path
        self._user = user
        self._pwd = pwd
        self._port = port

        self._server = None

        self._lock = Lock()

    def run(self):
        with self._lock:
            # 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(self._user, self._pwd, self._path, perm='elradfmwMT')

            # Instantiate FTP handler class
            handler = FTPHandler
            handler.authorizer = authorizer

            # Define a customized banner (string returned when client connects)
            handler.banner = "pyftpdlib based ftpd ready."

            # Instantiate FTP server class and listen on 0.0.0.0:self._port
            address = ('0.0.0.0', int(self._port))
            try:
                self._server = ThreadedFTPServer(address, handler)
            except Exception as e:
                logging.error(f"Exception while start PyFtpServer: {e}")

        if self._server is not None:
            # set a limit for connections
            self._server.max_cons = 256
            self._server.max_cons_per_ip = 5

            # start ftp server
            self._server.serve_forever()

    def terminate(self):
        self._server.close_all()

    def success(self):
        with self._lock:
            return self._server is not None
Exemple #31
0
def main():
    # Creates an authorizer for login verification
    authorizer = DummyAuthorizer()
    # Adds one set of login credentials to handle one user
    authorizer.add_user("user", "pass", ".", perm="elradfmwMT")

    handler = FTPHandler
    handler.authorizer = authorizer
    handler.banner = "Connected"

    # Sets server to listen on address 127.0.0.1 while binding to port 3000
    address = ("127.0.0.1", 3000)
    server = ThreadedFTPServer(address, handler)
    server.serve_forever()
Exemple #32
0
def start_service(conf):
    """Main server"""
    daemon_conf = configuration.daemon_conf
    authorizer = MiGUserAuthorizer()
    if daemon_conf['nossl'] or not configuration.user_ftps_key:
        logger.warning('Not wrapping connections in SSL - only for testing!')
        handler = FTPHandler
    elif OpenSSL is None:
        logger.error("Can't run FTPS server without PyOpenSSL!")
        return False
    else:
        logger.info("Using fully encrypted mode")
        handler = MiGTLSFTPHandler
        # requires SSL for both control and data channel
        handler.tls_control_required = True
        handler.tls_data_required = True
        keyfile = certfile = conf.user_ftps_key
        handler.certfile = certfile
        # Harden TLS/SSL if possible, requires recent pyftpdlib
        if hasattr(handler, 'ssl_context'):
            dhparamsfile = configuration.user_shared_dhparams
            legacy_tls = configuration.site_enable_ftps_legacy_tls
            ssl_ctx = hardened_openssl_context(conf,
                                               OpenSSL,
                                               keyfile,
                                               certfile,
                                               dhparamsfile=dhparamsfile,
                                               allow_pre_tlsv12=legacy_tls)
            handler.ssl_context = ssl_ctx
        else:
            logger.warning("Unable to enforce explicit strong TLS connections")
            logger.warning(
                "Upgrade to a recent pyftpdlib for maximum security")

    # NOTE: We use the threaded FTP server to prevent slow requests from
    # blocking the flow of all other clients. Auth still takes place in main
    # process thread so we don't need locking on user creds refresh.
    handler.authorizer = authorizer
    handler.abstracted_fs = MiGRestrictedFilesystem
    # TODO: masqueraded ftps fails from fireftp - maybe this would help?
    # if configuration.user_ftps_show_address != configuration.user_ftps_address:
    #    handler.masquerade_address = socket.gethostbyname(
    #        configuration.user_ftps_show_address)
    handler.passive_ports = conf.user_ftps_pasv_ports
    server = ThreadedFTPServer(
        (conf.user_ftps_address, conf.user_ftps_ctrl_port), handler)
    server.serve_forever()
Exemple #33
0
def main():
    '''Execution method
	
	Creates a Threaded server on the localhost with on the port 1515.
	Runs infinitely and accepts all client connections.
	'''

    # Authorize the incoming client connection requests
    authorizer = DummyAuthorizer()
    authorizer.add_user("user", "12345", ".", perm="elradfmw")
    authorizer.add_anonymous('/Users/user/Desktop/')

    # Create and define the client handler
    handler = FTPHandler
    handler.authorizer = authorizer
    server = ThreadedFTPServer(('', 1515), handler)
    server.serve_forever()
Exemple #34
0
def main():
    authorizer = DummyAuthorizer()
    authorizer.add_user(username, password, root_path, perm='elradfmwM')
    authorizer.add_anonymous(os.getcwd())

    handler = FTPHandler
    handler.authorizer = authorizer

    handler.banner = "welcom to ftp"

    address = (host, port)
    server = ThreadedFTPServer(address, handler)

    server.max_cons = 256
    server.max_cons_per_ip = 5

    server.serve_forever()
Exemple #35
0
class Example(QtWidgets.QMainWindow):
    def __init__(self):
        super(Example, self).__init__()
        uic.loadUi('gui.ui', self)
        self.pushButtonStart.clicked.connect(self.onClick)
        self.pushButtonStop.clicked.connect(self.onStop)

        self.authorizer = DummyAuthorizer()
        self.authorizer.add_anonymous(os.getcwd())

        self.handler = FTPHandler
        self.handler.authorizer = self.authorizer
        self.handler.banner = "pyftpdlib based ftpd ready."

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

    def onClick(self):
        print('start')

        user = self.lineEditUser.text()
        passw = self.lineEditPassword.text()

        self.authorizer.add_user(user, passw, '.', perm='elrw')
        self.address = ('127.0.0.1', 2100)
        self.server = ThreadedFTPServer(self.address, self.handler)

        QMessageBox.information(self, "FTP Server started",
                                "FTP Server started")
        self.start()

    def _run_server(self):
        self.server.serve_forever()

    def start(self):
        srv = threading.Thread(target=self._run_server)
        srv.deamon = True
        srv.start()

    def onStop(self):
        print('stop')
        self.server.close_all()
        QMessageBox.information(self, "FTP Server stopped",
                                "FTP Server stopped")
Exemple #36
0
def main():
    """Execution method

    Creates a Threaded server on the localhost with on the port 1515.
    Runs infinitely and accepts all client connections.
    """

    # print(os.getcwd())
    # Authorize the incoming client connection requests
    authorizer = DummyAuthorizer()
    # authorizer.add_user("user", "12345", ".", perm="rw")
    authorizer.add_anonymous('./server', perm="elrafmw")

    # Create and define the client handler
    handler = ServerHandler
    handler.authorizer = authorizer
    server = ThreadedFTPServer((""'', 1515), handler)
    server.serve_forever()
def main(username, password, base_dir):
    # Instantiate a dummy authorizer for managing 'virtual' users
    authorizer = DummyAuthorizer()
    # Define a new user having full r/w permissions
    authorizer.add_user(username, password, base_dir, perm='elradfmwM')

    # Instantiate FTP handler class
    handler = FTPHandler
    handler.authorizer = authorizer

    # Define a customized banner (string returned when client connects)
    handler.banner = "pyftpdlib based ftpd ready."

    # Instantiate FTP server class and listen on 0.0.0.0:2121
    address = ('0.0.0.0', 2121)
    server = ThreadedFTPServer(address, handler)

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

    # start ftp server
    server.serve_forever()
Exemple #38
0
def main(user,password,ftppath=".",port=21):
    #新建一个用户组
    authorizer = DummyAuthorizer()
    
    #将用户名,密码,用户访问指定目录,权限 添加到里面,当目录用"."表示.py文件当前所在的目录
    authorizer.add_user(user, password, ftppath, perm="elr") #elr只读,perm="elradfmw",windows 路径用 /
    # authorizer.add_user(user, password, ftppath, perm="elradfmw") #全部权限elradfmw
    
    #这个是添加匿名用户,任何人都可以访问,如果去掉的话,需要输入用户名和密码,可以自己尝试
    authorizer.add_anonymous(ftppath) #windows 路径用 /
    
    #下载速度限制
    # dtp_handler = ThrottledDTPHandler
    # dtp_handler.read_limit = 30720  # 30 Kb/sec (30 * 1024)
    # dtp_handler.write_limit = 30720  # 30 Kb/sec (30 * 1024)
       
    #头部
    handler = FTPHandler
    handler.authorizer = authorizer
    handler.banner = "pyftpdlib based ftpd ready."
    
    #ssl 认证
    handler.tls_control_required = True
    handler.tls_data_required = True
    
    #开启服务器
    ip = socket.gethostbyname(socket.gethostname()) # 获取本机ip地址
    # server = FTPServer((ip, 21), handler) #ip、端口、协议
    
    server = ThreadedFTPServer((ip, port), handler) # 多线程
    # server = MultiprocessFTPServer((ip, 21), handler) #多进程,多进程,3.x貌似去掉了
    
    #连接数
    server.max_cons = 48 #ip连接总数
    server.max_cons_per_ip = 3 #每个ip连接总数  
    
    server.serve_forever() #一直打开
Exemple #39
0
class DeployAgent(object):
    def __init__(self, ftpaddr, ftpport, ftphome, rpcaddr, rpcport):
        self.ftpaddr        = ftpaddr
        self.ftpport        = ftpport
        self.ftphome        = ftphome
        
        self.rpcaddr        = rpcaddr
        self.rpcport        = rpcport
        
        logger.info("--- xagent startup ---")

        XOR.File.mkpath(self.ftphome)
        authorizer = DummyAuthorizer()
        authorizer.add_anonymous(self.ftphome, perm='elradfmwM')
        handler = FTPHandler
        handler.authorizer = authorizer
        handler.banner = "xagent ftp server ready"
        self.ftpserver = ThreadedFTPServer((self.ftpaddr, self.ftpport), handler)

        self.rpcserver = XOR.Net.XMLRPCServer(addr=(self.rpcaddr, self.rpcport), logRequests=True, allow_none=True, encoding="UTF-8")
        self.rpcserver.reg_function(XOR.OS.runex, "os.")
        self.rpcserver.reg_function(XOR.OS.type, "os.")
        self.rpcserver.reg_function(XOR.Zip.extract, "zip.")
        self.rpcserver.reg_function(XOR.File.remove, "file.")
        self.rpcserver.reg_function(self.reg_package)
        self.rpcserver.reg_function(self.shutdown)
        self.rpcserver.reg_function(self.set_logger)
        self.rpcserver.reg_function(self.del_logger)
        self.rpcserver.reg_function(self.get_ftphomedir)
        self.rpcserver.register_introspection_functions()
        self.rpcserver.register_multicall_functions()


    def startup(self):
        self.ftpthread = threading.Thread(target=lambda:self.ftpserver.serve_forever())
        self.ftpthread.daemon = True
        self.ftpthread.start()
        
        self.rpcthread = threading.Thread(target=lambda:self.rpcserver.serve_forever())
        self.rpcthread.daemon = True
        self.rpcthread.start()


    def shutdown(self):
        self.ftpserver.close_all()
        self.rpcserver.shutdown()


    def join(self):
        self.ftpthread.join()
        self.rpcthread.join()


    def set_logger(self, logurl):
        logger.info("set httphandler: %s", logurl)
        if hasattr(self, "httphandler"):
            self.del_logger()
        
        match = re.match("http://(.*:\d{1,5})/(.*)", logurl)
        host = match.group(1)
        path = "/%s" % match.group(2)
        logger.info("log host: %s", host)
        logger.info("log path: %s", path)
        self.httphandler = logging.handlers.HTTPHandler(host, path, "POST")
        self.httphandler.setLevel(logging.DEBUG)
        logger.info("set httphandler: %s", logurl)
        rootlogger.addHandler(self.httphandler)
    
    
    def del_logger(self):
        logger.info("delete logging httphandler: %s" % self.httphandler)
        rootlogger.removeHandler(self.httphandler)
    
    
    def reg_package(self, name, path=[], clss=[]):
        found = imp.find_module( name, path )
        imp.load_module(name, *found)
        self.rpcserver.reg_module(sys.modules[name], clss, "%s." % name)

    
    def get_ftphomedir(self):
        return self.ftphome
    
    @staticmethod
    def parse_args():
        parser = argparse.ArgumentParser(add_help=True)
        parser.add_argument('--host', action='store', default="0.0.0.0")
        parser.add_argument('--rpcport', action='store', type=int, default=3333)
        parser.add_argument('--ftpport', action='store', type=int, default=6121)
        parser.add_argument('--ftpusername', action='store', default="xor")
        parser.add_argument('--ftppassword', action='store', default="xor")
        parser.add_argument('--ftphomedir', action='store', default= os.path.join( os.path.dirname(bindir), "dist" ))
        args = parser.parse_known_args()
        return vars(args[0])