def startServerAtFolderSettedFTP(self): if (self.ipAddress == None): raise Exception("Could not get system IP Address") if (self.folderToShare == None): raise Exception("path to folder to share is not setted") # 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', '225588', self.folderToShare, perm='elradfmwMT') authorizer.add_anonymous(homedir=self.folderToShare) # Instantiate FTP handler class handler = FTPHandler handler.authorizer = authorizer if (not (self.logToConsole)): config_logging(level=logging.ERROR) # Define a customized banner (string returned when client connects) handler.banner = "pyftpdlib based ftpd ready." address = (self.ipAddress, self.port ) # listen on every IP on my machine on port 21 server = servers.FTPServer(address, handler) server.serve_forever()
def startftp(self,server_ip): ''' this function is a tiny ftp server, that will start if local machine has no ftp client running. ''' try: authorizer = DummyAuthorizer() authorizer.add_user('user', '12345', self._path, perm='elradfmwM') handler = FTPHandler handler.authorizer = authorizer handler.banner = "pyftpdlib based ftpd ready." address = (server_ip, 21) server = FTPServer(address, handler) server.max_cons = 256 server.max_cons_per_ip = 5 config_logging(level=logging.ERROR) server.serve_forever() print "[+] ftp Server Started Succesfully." except ValueError: print "[-] Unable to start the ftp server. \n exiting."
def __init__(self, host: str, username: str, password: str, block_size: Optional[int] = None, timeout: Optional[int] = None, port: int = 21, ftplib_log_level: int = 0, pyftpdlib_log_level: int = logging.WARNING): """ :param host: dns name or ip address :param port: ftp port, usually 21 :param username: ftp account username :param password: ftp account password :param block_size: size of each block requested from ftp server :param timeout: idle timeout of ftp server :param ftplib_log_level: log level for ftplib library :param pyftpdlib_log_level: log level for pyftpdlib """ self.host: str = host self.port: int = port self.user: str = username self.passwd: str = password self.timeout: int = timeout or 60 self.blocksize: Optional[int] = block_size self.md5: Optional[str] = None self.ftp = ftplib.FTP(user=self.user, passwd=self.passwd) self.ftp.set_debuglevel(ftplib_log_level) pyftpdlib_log.config_logging(level=pyftpdlib_log_level)
def thread_ftpd_daemon(bind='0.0.0.0', port=21, loglevel=logging.DEBUG): authorizer = DummyAuthorizer() authorizer.add_anonymous(homedir=u'.') handler = XXE_FTPHandler handler.authorizer = authorizer handler.banner = 'ftp daemon' server = FTPServer((bind, port), handler=handler) config_logging(level=loglevel) server.serve_forever()
def __init__(self, hub): self.hub = hub self.args = hub.args hs = [] if self.args.ftp: hs.append([FtpHandler, self.args.ftp]) if self.args.ftps: try: h = SftpHandler except: m = "\nftps requires pyopenssl;\nplease run the following:\n\n {} -m pip install --user pyopenssl\n" print(m.format(sys.executable)) sys.exit(1) h.certfile = os.path.join(E.cfg, "cert.pem") h.tls_control_required = True h.tls_data_required = True hs.append([h, self.args.ftps]) for h in hs: h, lp = h h.hub = hub h.args = hub.args h.authorizer = FtpAuth() h.authorizer.hub = hub if self.args.ftp_pr: p1, p2 = [int(x) for x in self.args.ftp_pr.split("-")] if self.args.ftp and self.args.ftps: # divide port range in half d = int((p2 - p1) / 2) if lp == self.args.ftp: p2 = p1 + d else: p1 += d + 1 h.passive_ports = list(range(p1, p2 + 1)) if self.args.ftp_nat: h.masquerade_address = self.args.ftp_nat if self.args.ftp_dbg: config_logging(level=logging.DEBUG) ioloop = IOLoop() for ip in self.args.i: for h, lp in hs: FTPServer((ip, int(lp)), h, ioloop) t = threading.Thread(target=ioloop.loop) t.daemon = True t.start()
def _log_start(self): def get_fqname(obj): return obj.__module__ + "." + obj.__class__.__name__ if (not logging.getLogger('pyftpdlib').handlers and not logging.root.handlers): # If we get to this point it means the user hasn't # configured any logger. We want logging to be on # by default (stderr). from pyftpdlib.log import config_logging config_logging() if self.handler.passive_ports: pasv_ports = "%s->%s" % (self.handler.passive_ports[0], self.handler.passive_ports[-1]) else: pasv_ports = None addr = self.address if hasattr(self.handler, 'ssl_protocol'): proto = "FTP+SSL" else: proto = "FTP" logger.info(">>> starting %s server on %s:%s, pid=%i <<<" % (proto, addr[0], addr[1], os.getpid())) if ('ThreadedFTPServer' in __all__ and issubclass(self.__class__, ThreadedFTPServer)): logger.info("concurrency model: multi-thread") elif ('MultiprocessFTPServer' in __all__ and issubclass(self.__class__, MultiprocessFTPServer)): logger.info("concurrency model: multi-process") elif issubclass(self.__class__, FTPServer): logger.info("concurrency model: async") logger.info("masquerade (NAT) address: %s", self.handler.masquerade_address) logger.info("passive ports: %s", pasv_ports) logger.debug("poller: %r", get_fqname(self.ioloop)) logger.debug("authorizer: %r", get_fqname(self.handler.authorizer)) if os.name == 'posix': logger.debug("use sendfile(2): %s", self.handler.use_sendfile) logger.debug("handler: %r", get_fqname(self.handler)) logger.debug("max connections: %s", self.max_cons or "unlimited") logger.debug("max connections per ip: %s", self.max_cons_per_ip or "unlimited") logger.debug("timeout: %s", self.handler.timeout or "unlimited") logger.debug("banner: %r", self.handler.banner) logger.debug("max login attempts: %r", self.handler.max_login_attempts) if getattr(self.handler, 'certfile'): logger.debug("SSL certfile: %r", self.handler.certfile) if getattr(self.handler, 'keyfile'): logger.debug("SSL keyfile: %r", self.handler.keyfile)
def negotiatedServe(self): # current directory config_logging(level=logging.ERROR) exfil_directory = os.path.join(os.getcwd(), "data") loot_path = exfil_directory + "/" # Check to make sure the agent directory exists, and a loot # directory for the agent. If not, make them if not os.path.isdir(loot_path): os.makedirs(loot_path) try: authorizer = DummyAuthorizer() authorizer.add_user(self.username, self.password, loot_path, perm="elradfmwM") handler = FTPHandler handler.authorizer = authorizer # Define a customized banner (string returned when client connects) handler.banner = "Connecting to Egress-Assess's FTP server!" # Define public address and passive ports making NAT configurations more predictable handler.masquerade_address = self.ip handler.passive_ports = range(60000, 60100) try: server = FTPServer(('', self.port), handler) server.serve_forever() except socket.error: requests.get( "http://localhost:5000/send-status?error=True&protocol=%s" % self.protocol) sys.exit() except ValueError: print "[*] Error: The directory you provided may not exist!" print "[*] Error: Please re-run with a valid FTP directory." sys.exit() return
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")
from pyftpdlib.servers import FTPServer from pyftpdlib.log import config_logging from biostar.ftpserver.handler import BiostarFTPHandler, BiostarAuthorizer, BiostarFileSystem from biostar.accounts import models from biostar import settings import logging config_logging(level=logging.DEBUG) logger = logging.getLogger("engine") logger.setLevel(logging.INFO) def start(): # Engine authorization comes from the accounts. authorizer = BiostarAuthorizer() user = models.User.objects.filter(email="*****@*****.**").first() authorizer.add_user("*****@*****.**",settings.DEFAULT_ADMIN_PASSWORD , user=user, perm='elradfmwMT') # When parameter user is not specified; we use AnonymousUser authorizer.add_user('user', '12345', perm='elradfmwMT') authorizer.add_user('user2', '12345', perm='elradfmwMT') # Instantiate FTP handler class. handler = BiostarFTPHandler handler.authorizer = authorizer handler.abstracted_fs = BiostarFileSystem
def main(): usage = "python -m pyftpdlib [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 2121)") 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") parser.add_option('-V', '--verbose', action='store_true', help="activate a more verbose logging") options, args = parser.parse_args() if options.version: sys.exit("pyftpdlib %s" % __ver__) if options.verbose: config_logging(level=logging.DEBUG) 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_user("test", "test", ".", perm=perm) 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()
import os from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.handlers import FTPHandler from pyftpdlib.servers import FTPServer import logging from pyftpdlib.log import config_logging from threading import Thread import threading import ufP2Phss config_logging(level=logging.ERROR) class Server(Thread): def __init__(self): Thread.__init__(self) self._stop = threading.Event() def run(self): """Code à exécuter pendant l'exécution du thread.""" # 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', 'password', './shared', perm='elradfmwMT') authorizer.add_anonymous(os.getcwd())