예제 #1
0
def server_start(is_verbose=False, port=None):
    if not os.path.isfile('conf.json'):
        print 'Conf file not found, please run setup.'
        sys.exit(1)
    with open('conf.json') as jd:
        template = json.load(jd)
    container.set_acc_db(str(template['user_db']), str(template['user_table']))
    container.set_shares_db(str(template['user_logs']))
    container.set_root_dir(str(template['root']))
    container.set_log_file(str(template['root']) + '/pyftpd.log')
    auth = authorizer()
    handle = handler
    handle.user_sendfile = True
    handle.timeout = None
    handle.authorizer = auth
    handle.banner = 'this is the banner'
    if port:  # untested
        address = ('', 1024)
    else:
        address = ('', 21)
    server = FTPServer(address, handle)
    server.max_cons = 256
    server.maxcons_per_ip = 1000000
    if not is_verbose:
        logging.basicConfig(filename=container.get_log_file(), level=logging.INFO)
    server.serve_forever()
예제 #2
0
class FTPListener(threading.Thread):
    """
    Simple thread to run the FTP Server
    """

    def __init__(self, user=DEFAULT_USER, pwd=DEFAULT_PWD, port=DEFAULT_FTP_PORT, addr=DEFAULT_FTP_ADDR):
        """
        Constructor
        """
        self.user = user
        self.pwd = pwd
        self.port = port
        self.addr = addr
        threading.Thread.__init__(self)

    def run(self):
        """
        Starts the FTP server
        """
        authorizer = DummyAuthorizer()
        authorizer.add_user(self.user, self.pwd, ".", perm="elradfmw")
        handler = OneTimeFTPHandler
        handler.authorizer = authorizer
        self.server = FTPServer((self.addr, self.port), handler)
        self.server.serve_forever()

    def stop(self):
        """
        Stops the FTP server
        """
        if self.server is not None:
            self.server.close()
    def run(self):
        """Start the FTP Server for pulsar search."""
        self._log.info('Starting Pulsar Search Interface')
        # 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._config['login']['user'],
                            self._config['login']['psswd'], '.',
                            perm=self._config['login']['perm'])
        authorizer.add_anonymous(os.getcwd())

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

        # Define a customized banner (string returned when client connects)
        handler.banner = "SKA SDP pulsar search interface."

        # Instantiate FTP server class and listen on 0.0.0.0:7878
        address = (self._config['address']['listen'],
                   self._config['address']['port'])
        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()
예제 #4
0
파일: ftp.py 프로젝트: drunkard/lazycat
 def custom_server(self, start=1):
     # TODO: finish me
     from pyftpdlib.authorizers import DummyAuthorizer
     from pyftpdlib.handlers import FTPHandler
     from pyftpdlib.servers import FTPServer
     # Generate random username and password for ftp session
     logging.debug('generating arguments')
     if not os.path.isdir(self.path):
         logging.info('%s create directory: %s' %
                      ('device.name', self.path))
         os.makedirs(self.path)
     # Add ftp user
     authorizer = DummyAuthorizer()
     logging.debug('generated args: user=%s password=%s path=%s perm=%s' %
                   (self.user, self.password, self.path, self.password))
     authorizer.add_user(self.user, self.password, self.path,
                         perm=self.perm)
     handler = FTPHandler
     handler.authorizer = authorizer
     # Instantiate FTP server class and listen
     logging.debug('%s ftp server listen on: %s %s' %
                   ('device.name', self.address, self.port))
     addr = (self.address, self.port)
     server = FTPServer(addr, handler)
     # Set a limit for connections
     server.max_cons = 32
     server.max_cons_per_ip = 5
     # Start ftp server
     logging.debug('starting disposable ftp server')
     server.serve_forever(timeout=600, blocking=False)
예제 #5
0
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()
예제 #6
0
 def handle(self, *args, **options):
     handler = TLS_FTPHandler
     handler.certfile = Config.objects.get(key='certfile').value
     handler.authorizer = DjangoFtpAuthorizer()
     handler.abstracted_fs = CloudFS
     server = FTPServer(("0.0.0.0", 21), handler)
     server.serve_forever()
예제 #7
0
def main(profiles):
    authorizer = DummyAuthorizer()
    # 将每个profile映射为一个用户
    uploadTmpRoot = tempfile.gettempdir()
    for p, c in profiles.items():
        # perm权限定义说明:
        # Read permissions:
        # "e" = change directory (CWD, CDUP commands)
        # "l" = list files (LIST, NLST, STAT, MLSD, MLST, SIZE commands)
        # "r" = retrieve file from the server (RETR command)
        # Write permissions:

        # "a" = append data to an existing file (APPE command)
        # "d" = delete file or directory (DELE, RMD commands)
        # "f" = rename file or directory (RNFR, RNTO commands)
        # "m" = create directory (MKD command)
        # "w" = store a file to the server (STOR, STOU commands)
        # "M" = change mode/permission (SITE CHMOD command) New in 0.7.0
        # 注意:投产时权限似乎应限制为只写,即:'w'
        uploadTmp = path.join(uploadTmpRoot, p)
        print uploadTmp
        if not path.isdir(uploadTmp):
            mkdir(uploadTmp)

        authorizer.add_user(p, c["upload"].get("password", ""), uploadTmp, perm="ledw")

    handler = UploadHandler
    handler.authorizer = authorizer
    handler.banner = "OSO fileserv"
    address = ("", int(getenv("FTP_PORT", "2121")))
    logging.basicConfig(filename="logs/ftp.log", level=logging.INFO)
    server = FTPServer(address, handler)
    server.max_cons = 256
    server.max_cons_per_ip = 5
    server.serve_forever()
예제 #8
0
def main():
    """
    Main ftp server code
    """
    with open("ABSOLUTE_PATH_OF_config.yaml", 'r') as stream:
        config = yaml.load(stream)
        authorizer = DummyAuthorizer()
        if config.get('user'):
            for each_user in config['user']:
                if not os.path.exists(each_user['details']['home_directory']):
                    os.makedirs(each_user['details']['home_directory'])
                authorizer.add_user(
                    each_user['details']['username'],
                    each_user['details']['password'],
                    each_user['details']['home_directory'],
                    perm=each_user['details']['permission']
                )
        authorizer.add_anonymous('.')
        handler = MyHandler
        handler.certfile = config['certfile']
        handler.authorizer = authorizer
        handler.masquerade_address = config['masquerade_address']
        # requires SSL for both control and data channel
        handler.tls_control_required = True
        handler.tls_data_required = True
        handler.passive_ports = range(60000, 60099)
        server = FTPServer(('', 21), handler)
        server.serve_forever()
예제 #9
0
파일: ftpserver.py 프로젝트: BBOOXX/stash
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()
예제 #10
0
def main():
    # Instantiate a dummy authorizer for managing 'virtual' users
    authorizer = DummyAuthorizer()
    # Define a new user having full r/w permissions
    authorizer.add_user("user_name", "pass_word", "./", perm="elradfmwM", msg_login="******", msg_quit="bye")
    # Define a read-only anonymous user
    authorizer.add_anonymous("./")

    # Instantiate FTP handler class
    handler = FTPHandler
    handler.authorizer = authorizer
    handler.max_login_attempts = 3
    handler.permit_foreign_addresses = True
    handler.tcp_no_delay = True

    # Define a customized banner (string returned when client connects)
    handler.banner = "Welcome to my FTP."

    # Instantiate FTP server class and listen on 127.0.0.1:21
    address = ("0.0.0.0", 2121)
    server = FTPServer(address, handler)

    # set a limit for connections
    server.max_cons = 128
    server.max_cons_per_ip = 2

    absfs = AbstractedFS(u"./", handler)
    absfs.cwd = u"/bbb/ss/"
    # start ftp server
    server.serve_forever()
예제 #11
0
def start_ftp_server():
    cs.CSClient().log(APP_NAME, 'start_ftp_server()...')
    try:
        authorizer = DummyAuthorizer()
        # Define a new user having full r/w permissions and a read-only
        # anonymous user
        authorizer.add_user('user', '12345', FTP_DIR, perm='elradfmwM')
        authorizer.add_anonymous(FTP_DIR)

        # 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.
        # Application can only use ports higher that 1024 and the port
        # will need to be allowed in the router firewall
        address = ('', 2121)
        server = FTPServer(address, handler)

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

        # start ftp server
        cs.CSClient().log(APP_NAME, 'Starting FTP server...')
        server.serve_forever()
        # This will run the server in another thread
        # t = Thread(target=server.serve_forever())
        # t.start()

    except Exception as e:
        cs.CSClient().log(APP_NAME, 'Exception occurred! exception: {}'.format(e))
예제 #12
0
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', os.getcwd(), perm='elradfmwM')
    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()
예제 #13
0
파일: test.py 프로젝트: magne4000/ftpvista
def start_ftp_server():
    authorizer = DummyAuthorizer()
    authorizer.add_anonymous("ftpvista/test")
    handler = FTPHandler
    handler.authorizer = authorizer
    server = FTPServer(("127.0.0.1", 2121), handler)
    server.serve_forever()
예제 #14
0
def main():
    authorizer = UnixAuthorizer(rejected_users=["root"], require_valid_shell=True)
    handler = FTPHandler
    handler.authorizer = authorizer
    handler.abstracted_fs = UnixFilesystem
    server = FTPServer(('', 21), handler)
    server.serve_forever()
예제 #15
0
def ftp_server(command_line_object):
    # current directory
    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(
            command_line_object.username, command_line_object.password,
            loot_path, perm="lrw")

        handler = FTPHandler
        handler.authorizer = authorizer

        # Define a customized banner (string returned when client connects)
        handler.banner = "Connecting to Egress-Assess's FTP server!"

        server = FTPServer(('', 21), handler)
        server.serve_forever()
    except ValueError:
        print "[*] Error: The directory you provided may not exist!"
        print "[*] Error: Please re-run with a valid FTP directory."
        sys.exit()
예제 #16
0
파일: ftpd.py 프로젝트: Schnobb/ftpd
def main(args):
    user = DEFAULT_USER
    password = DEFAULT_PASSWORD
    ip = DEFAULT_IP
    port = DEFAULT_PORT
    directory = args.directory
    permissions = DEFAULT_PERM
    
    if args.user:
        user = args.user
    
    if args.password:
        password = args.password
        
    if args.ip:
        ip = args.ip
        
    if args.port:
        port = args.port
        
    authorizer = DummyAuthorizer()
    authorizer.add_user(user, password, directory, perm=permissions)
    
    #handler = TLS_FTPHandler
    #handler.certfile = 'server.crt'
    handler = FTPHandler
    handler.authorizer = authorizer
    
    server = FTPServer((ip, port), handler)
    server.serve_forever()
예제 #17
0
def main():
    # Instantiate a dummy authorizer for managing 'virtual' users
    authorizer = DummyAuthorizer()
    # Define a new user having full r/w permissions
    authorizer.add_user('test', 'test','./', perm='elradfmwM')
    # Define a read-only anonymous user
    authorizer.add_anonymous('./')
 
    # Instantiate TLS FTP handler class
    handler = TLS_FTPHandler
    handler.authorizer = authorizer
    handler.certfile = './server.crt'
    handler.keyfile = './server.key'
 
    # Define a customized banner (string returned when client connects)
    handler.banner = "Welcome to test's FTPS."
 
    # Instantiate FTP server class and listen on 127.0.0.1:21
    address = ('127.0.0.1', 21)
    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()
예제 #18
0
파일: server.py 프로젝트: jpf/ftp-to-s3
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(konf.ftp_username,
                        konf.ftp_password,
                        'ftp/',
                        perm='elradfmwM')
    # 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."

    # 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()
예제 #19
0
def main():
    port = 3334
    user = ''
    password = ''
    l = sys.argv

    if (len(l) > 1 and l[1]):
        user = l[1]

    if (len(l) > 2 and l[2]):
        password = l[2]

    if (len(l) > 3 and l[3]):
        port = int(l[3])


    authorizer = DummyAuthorizer()
    authorizer.add_user(user, password, os.getcwd(), perm='elradfmwM')
    authorizer.add_anonymous('.')

    handler = TLS_FTPHandler
    handler.certfile = CERTFILE
    handler.authorizer = authorizer

    server = FTPServer(("127.0.0.1", port), handler)
    server.serve_forever()
예제 #20
0
def main():
    port = 3334
    user = ''
    password = ''
    l = sys.argv

    if (len(l) > 1 and l[1]):
        user = l[1]

    if (len(l) > 2 and l[2]):
        password = l[2]

    if (len(l) > 3 and l[3]):
        port = int(l[3])


    authorizer = DummyAuthorizer()
    authorizer.add_user(user, password, os.getcwd(), perm='elradfmwM')
    #authorizer.add_anonymous("/home/nobody")

    handler = FTPHandler
    handler.authorizer = authorizer

    logging.basicConfig(level=logging.DEBUG)

    server = FTPServer(("127.0.0.1", port), handler)
    server.serve_forever()
예제 #21
0
    def serve(self):
        # current directory
        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!"

            try:
                server = FTPServer(('', self.port), handler)
                server.serve_forever()
            except socket.error:
                print "[*][*] Error: Port %d is currently in use!" % self.port
                print "[*][*] Error: Please restart when port is free!\n"
                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
예제 #22
0
파일: qftpd.py 프로젝트: Qumulo/qftpd
def main():
    authorizer = QSFSAuthorizer()
    handler = QFTPHandler
    handler.authorizer = authorizer
    handler.abstracted_fs = AbstractedQSFS
    server = FTPServer(('127.0.0.1', 21), handler)
    pyftpdlib.log.LEVEL = logging.DEBUG
    server.serve_forever()
예제 #23
0
def main():
    authorizer = DummyAuthorizer()
    authorizer.add_user("user", "12345", ".", perm="elradfmw")
    authorizer.add_anonymous(".")
    handler = AntiFloodHandler
    handler.authorizer = authorizer
    server = FTPServer(("", 2121), handler)
    server.serve_forever(timeout=1)
예제 #24
0
def main():
    authorizer = UsernameIsPathAuthorizer()
    authorizer.add_anonymous("/")

    handler = FTPHandler
    handler.authorizer = authorizer
    server = FTPServer(('*', 21), handler)
    server.serve_forever()
예제 #25
0
def main():
    authorizer = DummyAuthorizer()
    authorizer.add_anonymous("/opt/anonymous/", perm="lr")

    handler = FTPSchemeDetectionHandler
    handler.authorizer = authorizer
    server = FTPServer(('', 2121), handler)
    server.serve_forever()
예제 #26
0
 def handle(self, *args, **options):
     authorizer = DummyAuthorizer()
     authorizer.add_user('user', '12345', '.', perm='elradfmw')
     ftp_handler = FTPHandler
     ftp_handler.authorizer = authorizer
     ftp_handler.abstracted_fs = YourFS
     ftpd = FTPServer(('', 21), ftp_handler)
     ftpd.serve_forever()
예제 #27
0
파일: app.py 프로젝트: RealGeeks/pys3ftpd
def run_server():
    tempdir = tempfile.mkdtemp()
    authorizer = DummyAuthorizer()
    authorizer.add_user(FTP_USERNAME, FTP_PASSWORD, tempdir, perm="elradfmw")
    handler = S3FtpUploadHandler
    handler.authorizer = authorizer
    server = FTPServer((BIND_ADDRESS, PORT), handler)
    server.serve_forever()
예제 #28
0
def ftpstop():
    authorizer = DummyAuthorizer()
    handler = FTPHandler
    handler.authorizer = authorizer
    address = ('', 2121)
    server = FTPServer(address, handler)
    #server.serve_forever()
    server.close_all()
예제 #29
0
def run_ftpd(host, port, alert_bot, username, password, homedir):
    authorizer = FTPAuthorizer()
    authorizer.set_credentials(username, password, homedir)
    handler = MyFTPHandler
    handler.bot_queue = alert_bot
    handler.authorizer = authorizer
    server = FTPServer((host, port), handler)
    server.serve_forever()
예제 #30
0
def main():
    authorizer = DummyAuthorizer()
    authorizer.add_user('user', '12345', '.', perm='elradfmw')
    authorizer.add_anonymous('.')
    handler = AntiFloodHandler
    handler.authorizer = authorizer
    server = FTPServer(('', 2121), handler)
    server.serve_forever(timeout=1)
예제 #31
0
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

#实例化虚拟用户,这是FTP验证首要条件
authorizer = DummyAuthorizer()

#添加用户权限和路径,括号内的参数是(用户名, 密码, 用户目录, 权限)
authorizer.add_user('user',
                    '123456',
                    '/home/changshuai/Temp/changshuai',
                    perm='elradfmw')

# 添加匿名用户 只需要路径
# authorizer.add_anonymous('/home/changshuai/Temp/changshuai')

#初始化ftp句柄
handler = FTPHandler
handler.authorizer = authorizer

#监听ip 和 端口,因为linux里非root用户无法使用21端口,所以我使用了2121端口
server = FTPServer(('127.0.0.1', 2121), handler)

#开始服务
server.serve_forever()
예제 #32
0
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.servers import FTPServer
from pyftpdlib.handlers import FTPHandler
import os
from threading import Thread

NAME = 'mik'
PASS = '******'

auth = DummyAuthorizer()
# auth.add_anonymous(os.getcwd())

handler = FTPHandler
handler.authorizer = auth

serv = FTPServer(('localhost', 9091), handler)

thread = Thread()
thread.run = lambda: serv.serve_forever()

thread.start()

auth.add_user(NAME, PASS, os.path.join(os.getcwd(), '..\\ftp_storage'), 'wr')
예제 #33
0
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer


if __name__ == '__main__':

    parser = argparse.ArgumentParser(
        description='Starts a simple FTP server',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument('-un', '--username', help='Expected username', default='user')
    parser.add_argument('-up', '--password', help='Expected password', default='pass')
    parser.add_argument('-lh', '--addr', help='Listening address', default='')
    parser.add_argument('-lp', '--port', help='Listening port', type=int, default=21)
    parser.add_argument('-p', '--path', help='Exposed local path', default='./')
    parser.add_argument('-b', '--banner', help='Exposed FTP banner', default='FTPd 1.99')
    args = parser.parse_args()

    authorizer = DummyAuthorizer()
    authorizer.add_user(args.username, args.password, args.path, perm='elradfmw')
    handler = FTPHandler
    handler.authorizer = authorizer
    handler.banner = args.banner
    handler.passive_ports = range(60000, 65535)
    address = (args.addr, args.port)
    server = FTPServer(address, handler)
    server.max_cons = 256
    server.max_cons_per_ip = 5
    server.serve_forever()
예제 #34
0
import os
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
import socket  

hostname = socket.gethostname()    
IPAddr = socket.gethostbyname(hostname)     
print("\n\n\t\t========= WELCOME! ==========")
print("\t\tFTP Server starting....")
print("\t\tHost: " + IPAddr+ " ; Port: 21") 
print("\t\tBrowser URL: ftp://"+IPAddr+"/")
print("\t\t============================\n\n")

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

handler = FTPHandler
handler.authorizer = authorizer

server = FTPServer((IPAddr, 21), handler)
server.serve_forever()
예제 #35
0
        self.fs.close()

    def check(self, p):
        check_path = self.temp_dir.rstrip(os.sep) + os.sep + p
        return os.path.exists(check_path.encode('utf-8'))


if __name__ == "__main__":

    # Run an ftp server that exposes a given directory
    import sys
    authorizer = DummyAuthorizer()
    authorizer.add_user("user", "12345", sys.argv[1], perm="elradfmw")
    authorizer.add_anonymous(sys.argv[1])

    #def nolog(*args):
    #    pass
    #ftpserver.log = nolog
    #ftpserver.logline = nolog

    handler = FTPHandler
    handler.authorizer = authorizer
    address = ("127.0.0.1", int(sys.argv[2]))
    #print address

    ftpd = FTPServer(address, handler)

    sys.stdout.write('serving\n')
    sys.stdout.flush()
    ftpd.serve_forever()
예제 #36
0
"""
Run like
    $ python -m test.ftp_server
"""
import os

from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

from .fixture_tools import PYFTPSYNC_TEST_FOLDER

directory = os.path.join(PYFTPSYNC_TEST_FOLDER, "remote")

authorizer = DummyAuthorizer()
authorizer.add_user("tester", "secret", directory, perm="elradfmwMT")
authorizer.add_anonymous(directory, perm="elradfmwMT")

handler = FTPHandler
handler.authorizer = authorizer

server = FTPServer(("127.0.0.1", 8021), handler)
server.serve_forever()
 def __init__(self):
     super().__init__()
     self.authorizer = DummyAuthorizer()
     handler = FTPHandler
     handler.authorizer = self.authorizer
     self.server = FTPServer(("127.0.0.1", 0), handler)
예제 #38
0
    def connect(self, **kwargs):
        if self.username == "" and self.password == "":
            raise ValueError("Input username password server")

        self.server = FTPServer(self.address, self.handler)
        self.server.serve_forever()
예제 #39
0
                        default='password',
                        help='Set a password')
    args = parser.parse_args()

    class Handler(FTPHandler):
        queue = collections.defaultdict(queue.SimpleQueue)

        def ftp_RETR(self, file):
            fd = io.BytesIO(self.queue[file].get(True).encode())
            setattr(fd, 'name', file)
            producer = FileProducer(fd, self._current_type)
            self.push_dtp_data(producer, isproducer=True, file=fd, cmd="RETR")
            return file

        def on_file_received(self, file):
            with self.fs.open(file, 'r') as beacon_file:
                beacon = beacon_file.read().strip()
                res = requests.post(args.operator, data=beacon)
                res.encoding = 'utf-8'
                self.queue[file].put(res.text)

    # start server
    authorizer = DummyAuthorizer()
    authorizer.add_user(args.user, args.password, os.getcwd(), perm='rw')
    handler = Handler
    handler.authorizer = authorizer
    handler.masquerade_address = requests.get(
        'http://checkip.amazonaws.com').text.strip()
    server = FTPServer((args.address, 21), handler)
    server.serve_forever()
예제 #40
0
HOST_IP = socket.gethostbyname(USERNAME)
if HOST_IP == "127.0.0.1":
    print(">> Please Connect to Network Before Start FTP...")
    sleep(2)
    sys.exit()
PORT = 8000
HOST = (HOST_IP, PORT)

print(">> Starting FTP...")
sleep(1)

HOME = askdirectory(title='Selct Hosting Folder...')
if HOME == "":
    print(">> FTP Server Terminating...(No Folder Choosed!)")
    sleep(3)
    sys.exit()
Authorizer.add_anonymous(HOME, perm="elr")

print(f">> Server Address             : ftp://{HOST_IP}:{PORT}")
print(
    "                              $ For Download and Upload Data Use Windows Explorer"
)
print(f">> Server Hosted Location     : [ {HOME} ]")
print("\n>> Server Started...")
Handler = FTPHandler
Handler.authorizer = Authorizer
Server = FTPServer(HOST, Handler)
Server.serve_forever()

root.mainloop()
예제 #41
0
def main():
    """Start a stand alone anonymous FTP server."""
    import optparse
    import sys
    import os

    from pyftpdlib.authorizers import DummyAuthorizer
    from pyftpdlib.handlers import FTPHandler
    from pyftpdlib.servers import FTPServer
    from pyftpdlib._compat import getcwdu

    class CustomizedOptionFormatter(optparse.IndentedHelpFormatter):
        """Formats options shown in help in a prettier way."""
        def format_option(self, option):
            result = []
            opts = self.option_strings[option]
            result.append('  %s\n' % opts)
            if option.help:
                help_text = '     %s\n\n' % self.expand_default(option)
                result.append(help_text)
            return ''.join(result)

    usage = "python -m pyftpdlib.ftpserver [options]"
    parser = optparse.OptionParser(usage=usage,
                                   description=main.__doc__,
                                   formatter=CustomizedOptionFormatter())
    parser.add_option('-i',
                      '--interface',
                      default='',
                      metavar="ADDRESS",
                      help="specify the interface to run on (default all "
                      "interfaces)")
    parser.add_option('-p',
                      '--port',
                      type="int",
                      default=21,
                      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)
    ftpd.serve_forever()
예제 #42
0
파일: ftp.py 프로젝트: Rockira/Python
'''

if __name__ == '__main__':
    authorizer = DummyAuthorizer()
    '''
        权限说明:
        Read permissions:
         - "e" = change directory (CWD command)
         - "l" = list files (LIST, NLST, STAT, MLSD, MLST, SIZE, MDTM commands)
         - "r" = retrieve file from the server (RETR command)

        Write permissions:
         - "a" = append data to an existing file (APPE command)
         - "d" = delete file or directory (DELE, RMD commands)
         - "f" = rename file or directory (RNFR, RNTO commands)
         - "m" = create directory (MKD command)
         - "w" = store a file to the server (STOR, STOU commands)
         - "M" = change file mode (SITE CHMOD command)
         - "T" = update file last modified time (MFMT command)
    '''
    '''
     这里我们创建一个管理员,拥有所有权限,创建一个普通用户,只拥有浏览权限
    '''
    authorizer.add_user('admin', 'admin', 'F:\\file', perm='elradfmwM')
    authorizer.add_user('user', 'user', 'F:\\file')
    handler = FTPHandler
    handler.authorizer = authorizer
    server = FTPServer(('0.0.0.0', 8888), handler)
    server.serve_forever()
예제 #43
0
import socket
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

print("Por favor ingrese la dirección ip del servidor")
# Dirección ip del servidor
HOST = input()
# Creacion de un autorizador, el cual manejara las autenticaciones y permitira es uso de usuarios anonimos
autorizaciones = DummyAuthorizer()
autorizaciones.add_anonymous("/users")
# El FTPHandler se encarga de implementar el protocolo FTP, en este caso especificando que el autorizador previamente
# creado sera el encargado de las autorizaciones del mismo
handler = FTPHandler
handler.authorizer = autorizaciones
# Se crea el servidor con el manejador indicado, en el puerto predeterminado y la ip escogida
server = FTPServer((HOST, 21), handler)
server.serve_forever()

예제 #44
0
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

authorizer = DummyAuthorizer()

authorizer.add_user('user', '12345', 'ftpdfiles', perm='elradfmw')

handler = FTPHandler
handler.authorizer = authorizer

server = FTPServer(('0.0.0.0', 2121), handler)

server.serve_forever()
예제 #45
0
from pyftpdlib.authorizers import DummyAuthorizer  #Python FTP server library
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

authorizer = DummyAuthorizer()  #dummy authorizer

authorizer.add_anonymous(
    "/home/sree/Desktop/", perm="elradfmw"
)  #adding a user(userid,password) here as anonymous to the server with 										read , write etc permission

handler = FTPHandler
handler.authorizer = authorizer

connection = ('192.168.1.5', 21)  #host address and port number

server = FTPServer(connection, handler)

server.serve_forever()
예제 #46
0
 def run(self):
     handler = FTPHandler
     handler.authorizer = self.__authorizer
     self.__server = FTP((get_ip(), 1036), handler)
     self.__server.serve_forever()
예제 #47
0
파일: ftp_server2.py 프로젝트: pheeque/EHCP
    def get_msg_quit(self, username):
        if not self.user_table.has_key(username):
            return ""  # because of https://github.com/giampaolo/pyftpdlib/issues/400
        else:
            return super(Ehcp_Authorizer, self).get_msg_quit(username)


def initdb():
    try:
        app.conn.execute("select now()")
    except:
        print prefix, "reconnecting..."
        app.connecttodb()


app = Application()

handler = My_Handler
handler.banner = "Welcome to python based EHCP Ftp Server, managed by EHCP (Easy Hosting Control Panel, www.ehcp.net) (Beta)"
handler.authorizer = None
logging.basicConfig(filename='/var/log/ehcp_ftpd.log', level=logging.INFO)

print prefix, "server starting in 2 sec.. "
time.sleep(2)
server = FTPServer(("0.0.0.0", 2121), handler)
server.max_cons = 256
server.max_cons_per_ip = 5
rebuild_users()

server.serve_forever()
예제 #48
0
    {
        'name': 'test',
        'passwd': 'test',
        'homedir': '/home/test',
        'perm': 'elradfmwMT'
    },
]

authorizer = DummyAuthorizer()
for user in user_list:
    authorizer.add_user(user['name'],
                        user['passwd'],
                        user['homedir'],
                        perm=user['perm'])

dtp_handler = ThrottledDTPHandler
dtp_handler.read_limit = read_limit
dtp_handler.write_limit = write_limit

handler = FTPHandler
# handler.passive_ports = range(2000, 2300)  # 被动模式
handler.authorizer = authorizer
handler.dtp_handler = dtp_handler

logging.basicConfig(filename=log_file, level=log_level)

server = FTPServer((bind_addr, port), handler)
server.max_cons = max_connects
server.max_cons_per_ip = max_connects_pre_ip
server.serve_forever()
예제 #49
0
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
import yaml
import os

config_file = "server.yml"


def get_config(index):
    with open(config_file) as f:
        return yaml.load(f, Loader=yaml.FullLoader)[index]


if __name__ == "__main__":
    authorizer = DummyAuthorizer()

    authorizer.add_user(get_config("user_name"),
                        get_config("password"),
                        get_config("storage_path"),
                        perm='elradfmwMT')
    authorizer.add_anonymous(os.getcwd())

    handler = FTPHandler
    handler.authorizer = authorizer

    handler.banner = "File Synchronizer FTP Server Powered by pyftpdlib."

    address = ("", get_config("port"))
    server = FTPServer(address, handler)
    server.serve_forever()
예제 #50
0
    def get_perms(self, username):
        return self.user[username].permissions

    def get_msg_login(self, username):
        return "Welcome {!s}".format(username)

    def get_msg_quit(self, username):
        return "Bye"

    def impersonate_user(self, username, password):
        pass

    def terminate_impersonation(self, username):
        pass


if __name__ == "__main__":
    if AUTH_ADDR is None or AUTH_PORT is None or SECRET is None:
        raise ValueError("AUTH_ADDR, AUTH_PORT, and SECRET must be set")

    local, remote = (FTP_ADDR, FTP_PORT), (AUTH_ADDR, AUTH_PORT)

    auth = RemoteAuthorizer(remote, SECRET)

    class handler(FTPHandler):
        authorizer = auth

    server = FTPServer(local, handler)
    server.serve_forever()
예제 #51
0
#! /usr/bin/Python
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

authorizer = DummyAuthorizer()
authorizer.add_user("1", "1", "/home/bartek/python/project/JPO", perm="elradfmw")
#authorizer.add_anonymous("/home/bartek/python/project/JPO/nobody")

handler = FTPHandler
handler.authorizer = authorizer

server = FTPServer(("10.22.114.17", 2121), handler)
server.max_cons = 50
server.serve_forever()
예제 #52
0
# DummyAuthorizer gerencia as permissões de autorização no servidor FTP
from pyftpdlib.handlers import FTPHandler
# FTPHandler verificação acesso e permissões
from pyftpdlib.servers import FTPServer
# criar io diretório

autoridade = DummyAuthorizer()
autoridade.add_user('admin',
                    'admin',
                    '/home/jdso/servidorFTP',
                    perm='elradfmw')
#autoridade.add_anonymous('/home/jdso/servidorFTP', perm='elradfmw')

gerenteFTP = FTPHandler
gerenteFTP.authorizer = autoridade

servidor = FTPServer(('10.25.201.147', 1026), gerenteFTP)
servidor.serve_forever()

#
#"e" = mudar diretório (CWD, CDUP )
#"l" = listar arquivos (LIST, NLST, STAT, MLSD, MLST, SIZE )
#"r" = baixar arquivos (RETR)
#"a" = adicionar dados a um arquivo existente (APPE )
#"d" = remover um arquivo ou diretório (DELE, RMD)
#"f" = renomear um arquivo ou diretório (RNFR, RNTO )
#"m" = criar um diretório (MKD )
#"w" = armazenar um arquivo no servidor (STOR, STOU )
#"M" = mudar as permiçeõs de um arquivo (SITE CHMOD )
#"T" = mudar o tempo do arquivo (SITE MFMT )
예제 #53
0
from pyftpdlib.authorizers import DummyAuthorizer  #bibliotēka
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

authorizer = DummyAuthorizer()  #lietotāju klase
authorizer.add_user("elvish", "12345", "/home/elvish/ftp",
                    perm="elradfmw")  #definē lietotāju
authorizer.add_anonymous("/home/elvish",
                         perm="elradfmw")  #nedefinēts lietotājs

handler = FTPHandler  #autorizācijas veids
handler.authorizer = authorizer

server = FTPServer(("127.0.0.1", 1026), handler)  #definē serveri
server.serve_forever()
예제 #54
0
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

#实例化虚拟用户,这是FTP验证首要条件
authorizer = DummyAuthorizer()

#添加用户权限和路径,括号内的参数是(用户名, 密码, 用户目录, 权限)
authorizer.add_user('user', '12345', 'C:\\Users\\于祥\\Desktop\\', perm='elradfmw')

#添加匿名用户 只需要路径
authorizer.add_anonymous('C:/')

#初始化ftp句柄
handler = FTPHandler
handler.authorizer = authorizer

#监听ip 和 端口,因为linux里非root用户无法使用21端口,所以我使用了2121端口
server = FTPServer(('192.168.1.194', 21), handler)

#开始服务
server.serve_forever()
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

authorizer = DummyAuthorizer()

authorizer.add_user("user",
                    "12345",
                    "C:\\Users\\th\\Down loads\\FTPserver",
                    perm="elradfmw")
authorizer.add_anonymous("C:\\Users\\th\\Downloads\\FTP server",
                         perm="elradfmw")

handler = FTPHandler
handler.authorizer = authorizer

server = FTPServer(("127.0.0.1", 1026), handler)
server.serve_forever()
예제 #56
0
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")
    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:
        import logging
        import pyftpdlib.log
        pyftpdlib.log.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_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()
예제 #57
0
파일: util.py 프로젝트: goddess5321/utils
# python3.5+合并字典
a = {"a":1 ,"b": 2}
b = {"c":3 ,"d": 4}
c = {**a, **b}

# 多条件或
any(a, b, c)

# python开启ftp服务
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
# 实例化虚拟用户,这是FTP验证首要条件
authorizer = DummyAuthorizer()
# 添加用户权限和路径,括号内的参数是(用户名, 密码, 用户目录, 权限)
authorizer.add_user('user', '12345', '/home/homework/user', perm='elradfmw')
# 初始化ftp句柄
handler = FTPHandler
handler.authorizer = authorizer
# 监听ip 和 端口,因为linux里非root用户无法使用21端口,所以我使用了2121端口
server = FTPServer(('192.168.240.13', 2121), handler)
# 开始服务
server.serve_forever()

# pandas排序
df.sort_values("name")

# 获得文件所在路径
os.path.split(os.path.realpath(__file__))[0]
예제 #58
0
##########################################

from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

authorizer = DummyAuthorizer()

########### USERS ####################
#first parameter is the username, second one is the password and the third one is the directory to which that particular user has access to

authorizer.add_user("Swapneel", "Swapneel", "D:\Demo", perm="elradfmwMT")
authorizer.add_user("Swarna", "Swarna", "D:\Demo", perm="elradfmwMT")
authorizer.add_user("Sumukh", "Sumukh", "D:\Demo", perm="elradfmwMT")
authorizer.add_user("Suhaas", "Suhaas", "D:\Demo", perm="elradfmwMT")
authorizer.add_user("Param", "Param", "D:\Demo", perm="elradfmwMT")
authorizer.add_user("Akash", "Akash", "D:\Demo", perm="elradfmwMT")
authorizer.add_user("Sumanth", "Sumanth", "D:\Demo", perm="elradfmwMT")

######################################

authorizer.add_anonymous(
    "D:\Demo")  #path of the directory you want to the clients to access
handler = FTPHandler
handler.authorizer = authorizer
server = FTPServer(
    ("192.168.43.115", 21),
    handler)  #the IP address of your system, the one which is the server
server.serve_forever()
예제 #59
0
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

authorizer = DummyAuthorizer()
authorizer.add_user("lftpd", "lftpd", ".", perm="elradfmw")
handler = FTPHandler
handler.authorizer = authorizer
server = FTPServer(("0.0.0.0", 21), handler)
server.serve_forever()
예제 #60
0
#!/usr/bin/python3

from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

authorizer = DummyAuthorizer()
authorizer.add_user("test", "test", "/Users/username", perm="elradfmw")

handler = FTPHandler
handler.authorizer = authorizer
handler.passive_ports = range(60000, 61000)

server = FTPServer(("172.20.10.3", 2000), handler)
server.serve_forever()