本文整理汇总了Python中ftplib.FTP_TLS.close方法的典型用法代码示例。如果您正苦于以下问题:Python FTP_TLS.close方法的具体用法?Python FTP_TLS.close怎么用?Python FTP_TLS.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ftplib.FTP_TLS
的用法示例。
在下文中一共展示了FTP_TLS.close方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import close [as 别名]
def main():
global ftp_client
scan_arguments()
ftp_client = FTP(host)
try:
ftp_client.login(username, password)
except ftplib.all_errors as e:
print "ERROR: cannot login with username '{0}' and relative password.\nMessage returned from server:".format(username)
print e
return
try:
ftp_client.cwd(remote_dir)
except ftplib.all_errors as e:
print "ERROR: emote directory '{0}' not existing.\nMessage returned from server:".format(remote_dir)
print e
return
else:
files = ftp_client.nlst()
print_directory_content(files)
setup_folder()
download_files(remote_dir, files)
if compress:
create_zip(local_dir)
try:
ftp_client.close()
print "!!!!! OPERATION COMPLETED SUCCESSFULLY !!!!!"
except ftplib.all_errors as e:
print "ERROR: cannot close the connection properly.\nMessage from server:"
print e
示例2: write_file
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import close [as 别名]
def write_file(self):
output = open('chan_output.htm', 'w')
for channel in self.main.channels:
self.logger.log(LOG_DEBUG, "Writing output for %s, topic %s" % (channel, self.topics[channel]))
output.write("<b>Channel:</b> %s\n<br /><b>Topic:</b> %s\n<br /><b>Users:</b>\n<ul>\n" % (channel, self.topics[channel]))
for user in self.main.channels[channel]['users']:
output.write(" <li>%s</li>\n" %(user))
output.write("</ul>\n\n")
output.close
output = open('chan_output.htm', 'r')
self.update_all = 0
ftp_server = 'whub25.webhostinghub.com'
ftp_user = '[email protected]'
passfile = open('password.txt','r')
password = passfile.readline()
passfile.close()
password = password.rstrip('\n')
self.logger.log(LOG_INFO, "Connecting to FTP server %s, username %s" % (ftp_server, ftp_user))
ftp = FTP_TLS(ftp_server, ftp_user, password)
ftp.prot_p()
self.logger.log(LOG_INFO, "Successfully logged in, storing file")
ftp.storlines('STOR chan_output.htm', output)
ftp.close()
output.close()
self.update_all = 0
self.logger.log(LOG_INFO, "Done")
示例3: getfilelist
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import close [as 别名]
def getfilelist(server, port, user, password, db):
sqliteconnection = sqlite3.connect(db)
sqlitecursor = sqliteconnection.cursor()
sqlitecursor.execute('''CREATE TABLE IF NOT EXISTS files (date int, name text, CONSTRAINT 'id_UNIQUE' UNIQUE ('name'))''')
sqliteconnection.commit()
ftpsconnection = FTP_TLS()
ftpsconnection.connect(server, port)
ftpsconnection.auth()
ftpsconnection.prot_p()
ftpsconnection.login(user, password)
ftpsconnection.prot_p()
rootfiles = ftpsconnection.nlst()
for i in range(0,5):
episodes = ftpsconnection.nlst(rootfiles[i])
for episode in episodes:
sqlitecursor.execute('''INSERT OR IGNORE INTO files VALUES ("%(date)d", "%(folder)s")''' % {'date': time.time(), 'folder': ("/" + rootfiles[i] + "/" + episode) } )
sqliteconnection.commit()
sqliteconnection.close()
ftpsconnection.quit()
ftpsconnection.close()
示例4: get_file
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import close [as 别名]
def get_file(filename): # how do we 'stream' the file from Box to browser? using a callback!
class VMFile: # this will store the VM message as a
def __init__(self): # memory object instead of in a file (+ deleted after execution)
self.data = ""
def __call__(self,s):
self.data += s
v = VMFile()
session = FTP_TLS('ftp.box.com', box_username, box_password) # open Box
session.retrbinary('RETR recordings/' + filename, v) # add each chunk of data to memory from Box
session.close() # close Box
return v.data # return the data put back together again to be sent to browser
示例5: __init__
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import close [as 别名]
class FTPS:
def __init__(self):
self.ftps = FTP_TLS( )
def connect(self):
self.ftps.connect('192.168.0.102', 2121)
print(self.ftps.getwelcome())
def login(self):
self.ftps.login('anderson', 'nosredna89')
self.ftps.prot_p() #para fazer a conexação de dados segura
def close(self):
self.ftps.close()
示例6: getfiles
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import close [as 别名]
def getfiles(server, port, user, password, db):
sqliteconnection = sqlite3.connect(db)
sqlitecursor = sqliteconnection.cursor()
sqlitecursor.execute('''CREATE TABLE IF NOT EXISTS latest (date int, CONSTRAINT 'id_UNIQUE' UNIQUE ('date'))''')
sqliteconnection.commit()
sqlitecursor.execute('''SELECT date FROM files WHERE date = (SELECT MAX(date) FROM files) LIMIT 1''')
latestfile = sqlitecursor.fetchone()
sqlitecursor.execute('''SELECT date FROM latest WHERE date = (SELECT MAX(date) FROM latest) LIMIT 1''')
latestfetch = sqlitecursor.fetchone()
if latestfetch is None:
latestfetch = 0
if latestfetch < latestfile:
ftpsconnection = FTP_TLS()
ftpsconnection.connect(server, port)
ftpsconnection.auth()
ftpsconnection.prot_p()
ftpsconnection.login(user, password)
ftpsconnection.prot_p()
sqlitecursor.execute('''SELECT name FROM files WHERE date > %d''' % latestfetch)
filestofetch = sqlitecursor.fetchall()
for currfile in filestofetch:
ftpsconnection.cwd(currfile[0])
filenames = ftpsconnection.nlst()
for filename in filenames:
print 'Now saving /mnt/folder' + currfile[0] + '/' + filename
localfile = open('/mnt/folder' + currfile + '/' + filename, 'wb')
ftpsconnection.retrbinary('RETR ' + filename, localfile.write)
localfile.close()
sqliteconnection.execute('''INSERT OR IGNORE INTO latest VALUES (%d)''' % time.time())
sqliteconnection.commit()
sqliteconnection.close()
ftpsconnection.quit()
ftpsconnection.close()
示例7: startProtocol
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import close [as 别名]
def startProtocol(port, user, passwd, ip, regex, target_path, args):
global num_files, size, mirror, verbose, timeout
num_files = 0
size = 0
mirror = args.search
verbose = args.verbose
timeout = args.timeout
try:
print(70*'#')
print('Trying FTPS server: %s:%s' %(ip, port))
host = FTP_TLS(str(ip), timeout = timeout)
host.login(user, passwd)
host.prot_p()
print('Connected... Downloading files...\n')
files = downloadFTPFiles(target_path, host, regex)
print('%i files (%s) downloaded... Closing connection...' % (files, convert_bytes(size)))
host.close()
except ftplib.all_errors as err:
print (err)
示例8: connect
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import close [as 别名]
def connect(velkost_ftp,port):
ftp=FTP_TLS(server,meno2,ps,port)
ftp.prot_p()
ftp.cwd(my_list[2])
print "Posielam subor. Cakajte prosim."
obsah=open(file_to_send, 'rb')
obsah.close()
ftp.storbinary('STOR %s' % file_to_send, open(file_to_send, 'rb'))
obsah.close()
print "Subor odoslany [OK]"
print "Obsah adresara na serveri:"
ftp.retrlines("LIST")
size_ftp=ftp.nlst()
pocet=len(size_ftp)
velkost_ftp_subor=size_ftp[pocet-1] #berie posledne pridany subor zo zoznamu
ftp.sendcmd("TYPE i")
velkost_ftp=ftp.size(velkost_ftp_subor)
ftp.close()
return velkost_ftp
示例9: download
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import close [as 别名]
def download(downloaded, user, passwd, all_files=False, filename=None):
# Connect to the MAPS ftp server over FTPS
ftps = FTP_TLS('ftps.tsi.telecom-paristech.fr')
print 'Connected to MAPS FTP over TLS.'
try:
ftps.login(user=user, passwd=passwd)
ftps.cwd('maps')
except error_perm:
print "Incorrect username/password" ; quit
ftps.retrlines('LIST *.zip', get_file_list)
if filename is not None:
if not in_downloads(files, filename): print 'File not found' ; return
print 'Downloading', filename
res = ftps.retrbinary('RETR '+filename, open('./downloads/'+filename, 'wb').write)
ftps.close()
return [(filename, 0)]
if len(files) == len(downloaded):
print "All MAPS files downloaded. Continuing."
return
if all_files:
for f, s in files:
if not in_downloads(downloaded, f):
print "Downloading", f, "of size", s, "bytes"
res = ftps.retrbinary('RETR '+f, open('./downloads/'+f, 'wb').write)
elif filename is None:
f, s = random.choice(files)
while in_downloads(downloaded, f):
f, s = random.choice(files)
print "Downloading", f, "of size", s, "bytes"
res = ftps.retrbinary('RETR '+f, open('./downloads/'+f, 'wb').write)
ftps.close()
if all_files: return files
return [(f, s)]
示例10: FTP_TLS
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import close [as 别名]
import time
import requests
from ftplib import FTP_TLS
host = "quandl.brickftp.com"
ftps = FTP_TLS(host)
ftps.prot_p()
print (ftps.getwelcome())
try:
print ("Logging in...")
ftps.login("tricolor", "9v0$NkRUaM")
file_header = "=\nnotify: [email protected]\ntoken: 9kzPsYLWsnmrZ1xTENrX\n=\n"
headers = {"x-amz-acl": "bucket-owner-full-control"}
for input_file in glob.iglob("*.csv"):
with file(input_file, 'r') as original:
data = original.read()
if file_header not in data:
with file(input_file, 'w') as modified:
modified.write(file_header + data)
file_name = input_file
print "Opening file:" + file_name
fp = open (file_name,'rb')
ftps.storbinary('STOR ' + file_name, fp)
fp.close()
ftps.close()
except Exception, e: #you can specify type of Exception also
print str(e)
示例11: FTPSession
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import close [as 别名]
class FTPSession(object):
""" Attempt to create some robustness and performance to FTPing """
def __init__(self, server, username, password, tmpdir="/tmp", timeout=60):
"""Build a FTP session """
self.conn = None
self.server = server
self.username = username
self.password = password
self.tmpdir = tmpdir
self.timeout = timeout
def _connect(self):
"""Connect to FTP server """
if self.conn is not None:
return
logging.debug("Creating new connection to server %s", self.server)
not_connected = True
attempt = 1
while not_connected and attempt < 6:
try:
self.conn = FTP_TLS(self.server, timeout=self.timeout)
self.conn.login(self.username, self.password)
self.conn.prot_p()
not_connected = False
except Exception as exp:
logging.debug(exp)
time.sleep(5)
self.close()
attempt += 1
if not_connected is True:
raise Exception("Failed to make FTP connection after 5 tries!")
def _reconnect(self):
""" First attempt to shut down connection and then reconnect """
logging.debug("_reconnect() was called...")
try:
self.conn.quit()
self.conn.close()
except:
pass
finally:
self.conn = None
self._connect()
def _put(self, path, localfn, remotefn):
""" """
self.chdir(path)
sz = os.path.getsize(localfn)
if sz > 14000000000:
# Step 1 Split this big file into 14GB chunks, each file will have
# suffix .aa then .ab then .ac etc
basefn = os.path.basename(localfn)
cmd = "split --bytes=14000M %s %s/%s." % (localfn, self.tmpdir, basefn)
subprocess.call(cmd, shell=True, stderr=subprocess.PIPE)
files = glob.glob("%s/%s.??" % (self.tmpdir, basefn))
for filename in files:
suffix = filename.split(".")[-1]
self.conn.storbinary("STOR %s.%s" % (remotefn, suffix), open(filename))
os.unlink(filename)
else:
logging.debug("_put '%s' to '%s'", localfn, remotefn)
self.conn.storbinary("STOR %s" % (remotefn,), open(localfn))
return True
def close(self):
""" Good bye """
try:
self.conn.quit()
self.conn.close()
except:
pass
finally:
self.conn = None
def chdir(self, path):
if self.pwd() == path.rstrip("/"):
return
self.conn.cwd("/")
for dirname in path.split("/"):
if dirname == "":
continue
bah = []
self.conn.retrlines("NLST", bah.append)
if dirname not in bah:
logging.debug("Creating directory '%s'", dirname)
self.conn.mkd(dirname)
logging.debug("Changing to directory '%s'", dirname)
self.conn.cwd(dirname)
def pwd(self):
""" Low friction function to get connectivity """
self._connect()
pwd = exponential_backoff(self.conn.pwd)
if pwd is None:
self._reconnect()
pwd = exponential_backoff(self.conn.pwd)
logging.debug("pwd() is currently '%s'", pwd)
return pwd
#.........这里部分代码省略.........