Python ftplib.FTP_TLS Examples

The following are 30 code examples of ftplib.FTP_TLS(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ftplib , or try the search function .
Example #1
Source File: connection.py    From insightconnect-plugins with MIT License 7 votes vote down vote up
def connect(self, params={}):
        self.logger.info("Connect: Connecting..")
        host = params.get('host')
        username = params.get('credentials').get('username', 'anonymous')
        password = params.get('credentials').get('password', 'test@test.com')
        # Use secure mode?
        secure = params.get('secure', False)
        # Use passive mode?
        passive = params.get('passive', False)

        # Either ftplib.FTP or ftplib.FTP_TLS
        base_ftp_class = ftplib.FTP
        if secure:
            base_ftp_class = ftplib.FTP_TLS
        my_session_factory = ftputil.session.session_factory(
            base_class=base_ftp_class,
            use_passive_mode=passive)
        try:
            self.ftp_host = ftputil.FTPHost(host, username,
                                            password, session_factory=my_session_factory)
        except ftputil.error.PermanentError as e:
            raise e 
Example #2
Source File: networking_03.py    From Modern-Python-Standard-Library-Cookbook with MIT License 6 votes vote down vote up
def __init__(self, host, username='', password=''):
        self._client = ftplib.FTP_TLS(timeout=10)
        self._client.connect(host)

        # enable TLS
        try:
            self._client.auth()
        except ftplib.error_perm:
            # TLS authentication not supported
            # fallback to a plain FTP client
            self._client.close()
            self._client = ftplib.FTP(timeout=10)
            self._client.connect(host)
        
        self._client.login(username, password)

        if hasattr(self._client, 'prot_p'):
            self._client.prot_p() 
Example #3
Source File: test_ftplib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_context(self):
        self.client.quit()
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE,
                          context=ctx)
        self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
                          context=ctx)
        self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
                          keyfile=CERTFILE, context=ctx)

        self.client = ftplib.FTP_TLS(context=ctx, timeout=TIMEOUT)
        self.client.connect(self.server.host, self.server.port)
        self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
        self.client.auth()
        self.assertIs(self.client.sock.context, ctx)
        self.assertIsInstance(self.client.sock, ssl.SSLSocket)

        self.client.prot_p()
        with self.client.transfercmd('list') as sock:
            self.assertIs(sock.context, ctx)
            self.assertIsInstance(sock, ssl.SSLSocket) 
Example #4
Source File: test_ftplib.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_context(self):
        self.client.quit()
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE,
                          context=ctx)
        self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
                          context=ctx)
        self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
                          keyfile=CERTFILE, context=ctx)

        self.client = ftplib.FTP_TLS(context=ctx, timeout=TIMEOUT)
        self.client.connect(self.server.host, self.server.port)
        self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
        self.client.auth()
        self.assertIs(self.client.sock.context, ctx)
        self.assertIsInstance(self.client.sock, ssl.SSLSocket)

        self.client.prot_p()
        with self.client.transfercmd('list') as sock:
            self.assertIs(sock.context, ctx)
            self.assertIsInstance(sock, ssl.SSLSocket) 
Example #5
Source File: test_ftplib.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_context(self):
        self.client.quit()
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE,
                          context=ctx)
        self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
                          context=ctx)
        self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
                          keyfile=CERTFILE, context=ctx)

        self.client = ftplib.FTP_TLS(context=ctx, timeout=TIMEOUT)
        self.client.connect(self.server.host, self.server.port)
        self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
        self.client.auth()
        self.assertIs(self.client.sock.context, ctx)
        self.assertIsInstance(self.client.sock, ssl.SSLSocket)

        self.client.prot_p()
        with self.client.transfercmd('list') as sock:
            self.assertIs(sock.context, ctx)
            self.assertIsInstance(sock, ssl.SSLSocket) 
Example #6
Source File: ftp.py    From airflow with Apache License 2.0 6 votes vote down vote up
def get_conn(self):
        """
        Returns a FTPS connection object.
        """
        if self.conn is None:
            params = self.get_connection(self.ftp_conn_id)
            pasv = params.extra_dejson.get("passive", True)

            if params.port:
                ftplib.FTP_TLS.port = params.port

            self.conn = ftplib.FTP_TLS(
                params.host, params.login, params.password
            )
            self.conn.set_pasv(pasv)

        return self.conn 
Example #7
Source File: test_ftplib.py    From android_universal with MIT License 6 votes vote down vote up
def test_context(self):
        self.client.quit()
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE,
                          context=ctx)
        self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
                          context=ctx)
        self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
                          keyfile=CERTFILE, context=ctx)

        self.client = ftplib.FTP_TLS(context=ctx, timeout=TIMEOUT)
        self.client.connect(self.server.host, self.server.port)
        self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
        self.client.auth()
        self.assertIs(self.client.sock.context, ctx)
        self.assertIsInstance(self.client.sock, ssl.SSLSocket)

        self.client.prot_p()
        with self.client.transfercmd('list') as sock:
            self.assertIs(sock.context, ctx)
            self.assertIsInstance(sock, ssl.SSLSocket) 
Example #8
Source File: test_ftplib.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_context(self):
        self.client.quit()
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLS)
        self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE,
                          context=ctx)
        self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
                          context=ctx)
        self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
                          keyfile=CERTFILE, context=ctx)

        self.client = ftplib.FTP_TLS(context=ctx, timeout=TIMEOUT)
        self.client.connect(self.server.host, self.server.port)
        self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
        self.client.auth()
        self.assertIs(self.client.sock.context, ctx)
        self.assertIsInstance(self.client.sock, ssl.SSLSocket)

        self.client.prot_p()
        sock = self.client.transfercmd('list')
        try:
            self.assertIs(sock.context, ctx)
            self.assertIsInstance(sock, ssl.SSLSocket)
        finally:
            sock.close() 
Example #9
Source File: test_functional_ssl.py    From pyftpdlib with MIT License 5 votes vote down vote up
def login(self, *args, **kwargs):
            ftplib.FTP_TLS.login(self, *args, **kwargs)
            self.prot_p() 
Example #10
Source File: test_ftplib.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        self.server = DummyTLS_FTPServer((HOST, 0))
        self.server.start()
        self.client = ftplib.FTP_TLS(timeout=10)
        self.client.connect(self.server.host, self.server.port) 
Example #11
Source File: test_ftplib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.server = DummyTLS_FTPServer((HOST, 0))
        self.server.start()
        self.client = ftplib.FTP_TLS(timeout=TIMEOUT)
        self.client.connect(self.server.host, self.server.port)
        # enable TLS
        self.client.auth()
        self.client.prot_p() 
Example #12
Source File: test_ftplib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.server = DummyTLS_FTPServer((HOST, 0))
        self.server.start()
        self.client = ftplib.FTP_TLS(timeout=TIMEOUT)
        self.client.connect(self.server.host, self.server.port) 
Example #13
Source File: patcher.py    From ibllib with MIT License 5 votes vote down vote up
def __init__(self, one=None, globus_client=None):
        super().__init__(one=one)
        self.ftp = ftplib.FTP_TLS(host=FTP_HOST,
                                  user=one._par.FTP_DATA_SERVER_LOGIN,
                                  passwd=one._par.FTP_DATA_SERVER_PWD)
        # self.ftp.ssl_version = ssl.PROTOCOL_TLSv1
        # self.ftp.auth()
        self.ftp.prot_p()
        self.ftp.login(one._par.FTP_DATA_SERVER_LOGIN, one._par.FTP_DATA_SERVER_PWD) 
Example #14
Source File: test_ftplib.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.server = DummyTLS_FTPServer((HOST, 0))
        self.server.start()
        self.client = ftplib.FTP_TLS(timeout=10)
        self.client.connect(self.server.host, self.server.port) 
Example #15
Source File: test_ftplib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_check_hostname(self):
        self.client.quit()
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        ctx.verify_mode = ssl.CERT_REQUIRED
        ctx.check_hostname = True
        ctx.load_verify_locations(CAFILE)
        self.client = ftplib.FTP_TLS(context=ctx, timeout=TIMEOUT)

        # 127.0.0.1 doesn't match SAN
        self.client.connect(self.server.host, self.server.port)
        with self.assertRaises(ssl.CertificateError):
            self.client.auth()
        # exception quits connection

        self.client.connect(self.server.host, self.server.port)
        self.client.prot_p()
        with self.assertRaises(ssl.CertificateError):
            with self.client.transfercmd("list") as sock:
                pass
        self.client.quit()

        self.client.connect("localhost", self.server.port)
        self.client.auth()
        self.client.quit()

        self.client.connect("localhost", self.server.port)
        self.client.prot_p()
        with self.client.transfercmd("list") as sock:
            pass 
Example #16
Source File: ftp_exfil.py    From PyExfil with MIT License 5 votes vote down vote up
def send_chunks(self):
		if self.final_chunks is None:
			return ERR

		if self.tls_flag:
			if self.auth_flag:
				ftp_obj = FTP_TLS(host=self.server, user=self.creds[0], passwd=self.creds[1])
			else:
				ftp_obj = FTP_TLS(host=self.server)
		else:
			if self.auth_flag:
				ftp_obj = FTP(host=self.server, user=self.creds[0], passwd=self.creds[1])
			else:
				ftp_obj = FTP(host=self.server)

		try:
			ftp_obj.login()
			sys.stdout.write("\t[+]\tConnected to server %s.\n" % self.server)
		except:
			sys.stderr.write("\t[-]\tCould not login to the server.\n")
			return ERR

		for chunk in self.final_chunks:
			ftp_obj.mkd(chunk)
			time.sleep(SLEEP)

		ftp_obj.quit()
		sys.stdout.write("\t[+]\tWrote %s(+1) folders.\n" % (len(self.final_chunks)-1))
		return OKAY 
Example #17
Source File: test_ftplib.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.server = DummyTLS_FTPServer((HOST, 0))
        self.server.start()
        self.client = ftplib.FTP_TLS(timeout=10)
        self.client.connect(self.server.host, self.server.port)
        # enable TLS
        self.client.auth()
        self.client.prot_p() 
Example #18
Source File: test_ftplib.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.server = DummyTLS_FTPServer((HOST, 0))
        self.server.start()
        self.client = ftplib.FTP_TLS(timeout=10)
        self.client.connect(self.server.host, self.server.port)
        # enable TLS
        self.client.auth()
        self.client.prot_p() 
Example #19
Source File: test_ftplib.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.server = DummyTLS_FTPServer((HOST, 0))
        self.server.start()
        self.client = ftplib.FTP_TLS(timeout=10)
        self.client.connect(self.server.host, self.server.port) 
Example #20
Source File: files.py    From python-sploitkit with GNU Affero General Public License v3.0 5 votes vote down vote up
def _ftp(self, locator, *args, **kwargs):
        """ Simple FTP downloader. """
        scheme = locator.split("://", 1)[0]
        client = [FTP, FTP_TLS][scheme == "ftps"]()
        client.connect(kwargs.pop("host", ""), kwargs.pop("port", 21))
        if scheme == "ftps":
            client.auth()
        usr, pswd = kwargs.pop("user", ""), kwargs.pop("passwd", "")
        if usr != "" and pswd != "":
            client.login(usr, passwd)
        #client.retrbinary(kwargs.pop("cmd", None),
        #                  kwargs.pop("callback", None))
        #FIXME 
Example #21
Source File: test_functional_ssl.py    From pyftpdlib with MIT License 5 votes vote down vote up
def _setup(self,
               tls_control_required=False,
               tls_data_required=False,
               ssl_protocol=ssl.PROTOCOL_SSLv23,
               ):
        self.server = FTPSServer()
        self.server.handler.tls_control_required = tls_control_required
        self.server.handler.tls_data_required = tls_data_required
        self.server.handler.ssl_protocol = ssl_protocol
        self.server.start()
        self.client = ftplib.FTP_TLS(timeout=TIMEOUT)
        self.client.connect(self.server.host, self.server.port) 
Example #22
Source File: ftp.py    From cwl-tes with Apache License 2.0 5 votes vote down vote up
def _connect(self, url):  # type: (Text) -> Optional[ftplib.FTP]
        parse = urllib.parse.urlparse(url)
        if parse.scheme == 'ftp':
            host, user, passwd, _ = self._parse_url(url)
            if (host, user, passwd) in self.cache:
                if self.cache[(host, user, passwd)].pwd():
                    return self.cache[(host, user, passwd)]
            ftp = ftplib.FTP_TLS()
            ftp.set_debuglevel(1 if _logger.isEnabledFor(logging.DEBUG) else 0)
            ftp.connect(host)
            ftp.login(user, passwd, secure=not self.insecure)
            self.cache[(host, user, passwd)] = ftp
            return ftp
        return None 
Example #23
Source File: ftps.py    From habu with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def login(self):

        if self.service == 'ftp':
            ftp = FTP()
        else:
            #print('doing FTP SSL')
            ftp = FTP_TLS()

        try:
            ftp.connect(host=self.address, port=self.port, timeout=3)
        except socket.timeout:
            return ReturnCode.CONN_TIMEOUT

        if self.service == 'ftps':
            logging.info('Securing SSL/TLS connection...')
            print('Securing SSL/TLS connection...')
            try:
                print(ftp.auth())
                print(ftp.prot_p())
                #print(ftp.prot_p())
            except error_perm as e:
                logging.info(e) #'Error during SSL/TLS setup.')
                print(e)
                #if str(e).startswith('500'):
                    #logging.info('Maybe the server doesn\'t supports FTPS')
                return ReturnCode.TLS_ERROR

        try:
            #print(self.service)
            #ftp.connect(host=self.address, port=self.port, timeout=3)
            #if self.service == 'ftps':
            ftp.login(user=self.username, passwd=self.password)
            return ReturnCode.AUTH_OK
        except ConnectionRefusedError:
            return ReturnCode.CONN_REFUSED
        except error_perm as e:
            print(e)
            return ReturnCode.AUTH_FAILED
        except Exception:
            return ReturnCode.GENERIC_ERROR 
Example #24
Source File: auxdata.py    From pyroSAR with MIT License 5 votes vote down vote up
def __retrieve_ftp(url, filenames, outdir, username, password):
        files = list(set(filenames))
        if not os.path.isdir(outdir):
            os.makedirs(outdir)
        pattern = r'(ftp(?:es|))://([a-z0-9.\-]*)[/]*((?:[a-zA-Z0-9/_]*|))'
        protocol, url, path = re.search(pattern, url).groups()
        if protocol == 'ftpes':
            ftp = ftplib.FTP_TLS(url)
            try:
                ftp.login(username, password)  # login anonymously before securing control channel
            except ftplib.error_perm as e:
                raise RuntimeError(str(e))
            ftp.prot_p()  # switch to secure data connection.. IMPORTANT! Otherwise, only the user and password is encrypted and not all the file data.
        else:
            ftp = ftplib.FTP(url, timeout=100)
            ftp.login()
        if path != '':
            ftp.cwd(path)
        locals = []
        for product_remote in files:
            product_local = os.path.join(outdir, os.path.basename(product_remote))
            if not os.path.isfile(product_local):
                try:
                    targetlist = ftp.nlst(product_remote)
                except ftplib.error_temp:
                    continue
                address = '{}://{}/{}{}'.format(protocol, url, path + '/' if path != '' else '', product_remote)
                print('{} <<-- {}'.format(product_local, address))
                with open(product_local, 'wb') as myfile:
                    ftp.retrbinary('RETR {}'.format(product_remote), myfile.write)
            if os.path.isfile(product_local):
                locals.append(product_local)
        ftp.close()
        return sorted(locals) 
Example #25
Source File: test_ftplib.py    From android_universal with MIT License 5 votes vote down vote up
def setUp(self):
        self.server = DummyTLS_FTPServer((HOST, 0))
        self.server.start()
        self.client = ftplib.FTP_TLS(timeout=TIMEOUT)
        self.client.connect(self.server.host, self.server.port)
        # enable TLS
        self.client.auth()
        self.client.prot_p() 
Example #26
Source File: test_ftplib.py    From android_universal with MIT License 5 votes vote down vote up
def setUp(self):
        self.server = DummyTLS_FTPServer((HOST, 0))
        self.server.start()
        self.client = ftplib.FTP_TLS(timeout=TIMEOUT)
        self.client.connect(self.server.host, self.server.port) 
Example #27
Source File: files.py    From python-sploitkit with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, locator, *args, **kwargs):
        """ Get a resource. """
        if locator in self.keys() and not kwargs.pop("force", False):
            return self[locator]
        scheme, path = locator.split("://")
        if scheme in ["http", "https"]:
            r = requests.get(locator, *args, **kwargs)
            self[locator] = r.content
            if r.status_code == 403:
                raise ValueError("Forbidden")
        elif scheme in ["ftp", "ftps"]:
            client = [FTP, FTP_TLS][schem == "ftps"]()
            client.connect(kwargs.pop("host", ""), kwargs.pop("port", 21))
            if scheme == "ftps":
                client.auth()
            usr, pswd = kwargs.pop("user", ""), kwargs.pop("passwd", "")
            if usr != "" and pswd != "":
                client.login(usr, passwd)
            client.retrbinary(kwargs.pop("cmd", None),
                              kwargs.pop("callback", None))
            #FIXME
        elif scheme == "file":
            with open(path, 'rb') as f:
                self[locator] = f.read()
        else:
            raise ValueError("Unsupported scheme '{}'".format(scheme)) 
Example #28
Source File: test_ftplib.py    From android_universal with MIT License 5 votes vote down vote up
def test_check_hostname(self):
        self.client.quit()
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
        self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
        self.assertEqual(ctx.check_hostname, True)
        ctx.load_verify_locations(CAFILE)
        self.client = ftplib.FTP_TLS(context=ctx, timeout=TIMEOUT)

        # 127.0.0.1 doesn't match SAN
        self.client.connect(self.server.host, self.server.port)
        with self.assertRaises(ssl.CertificateError):
            self.client.auth()
        # exception quits connection

        self.client.connect(self.server.host, self.server.port)
        self.client.prot_p()
        with self.assertRaises(ssl.CertificateError):
            with self.client.transfercmd("list") as sock:
                pass
        self.client.quit()

        self.client.connect("localhost", self.server.port)
        self.client.auth()
        self.client.quit()

        self.client.connect("localhost", self.server.port)
        self.client.prot_p()
        with self.client.transfercmd("list") as sock:
            pass 
Example #29
Source File: ftpbench.py    From aioftp with Apache License 2.0 5 votes vote down vote up
def connect():
    """Connect to FTP server, login and return an ftplib.FTP instance."""
    ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS
    ftp = ftp_class(timeout=TIMEOUT)
    ftp.connect(HOST, PORT)
    ftp.login(USER, PASSWORD)
    if SSL:
        ftp.prot_p()  # secure data connection
    return ftp 
Example #30
Source File: ftp.py    From d6tpipe with MIT License 5 votes vote down vote up
def _ftp_connect(self):
        try:
            self.conn.voidcmd("NOOP")
            return True
        except:
            if self.tls:
                self.conn = ftplib.FTP_TLS()
            else:
                self.conn = ftplib.FTP()
            self.conn.connect(self.host, self.port, timeout=self.timeout)
            self.conn.login(self.username, self.password)
            if self.tls:
                self.conn.prot_p()