本文整理汇总了Python中ftplib.FTP_TLS.mkd方法的典型用法代码示例。如果您正苦于以下问题:Python FTP_TLS.mkd方法的具体用法?Python FTP_TLS.mkd怎么用?Python FTP_TLS.mkd使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ftplib.FTP_TLS
的用法示例。
在下文中一共展示了FTP_TLS.mkd方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: send_chunks
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import mkd [as 别名]
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
示例2: __init__
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import mkd [as 别名]
class FTPES:
def __init__(self, host, port=None, username=None, password=None, remote_path=None, absolute_zipfile_path=None):
"""
This is a helper class to manage the FTP commands from the ftplib.
@param host: The host for the connection.
@type host: String
@param port: The post for the connection.
@type port: Integer
@param username: The username for the connection. Leave blank to use "anonymous".
@type username: String
@param password: The password for the connection. Leave empty for none.
@type password: String
@param remote_path: The remote path of the server in which the zip file should be uploaded. If the path does not
exists, it will be created (recursive).
@type remote_path: String
@param absolute_zipfile_path: The absolute LOCAL filepath of the zip file.
@type absolute_zipfile_path: String
"""
self.ftps = None
self._host = host
self._port = port
self._username = username
self._password = password
self._remote_path = remote_path
self._absolute_zipfile_path = absolute_zipfile_path
self._bytesWritten = 0;
self._totalFileSize = os.path.getsize(self._absolute_zipfile_path)
self._uploadCallback = None
self._currentProgress = 0
# make the remote path relative if it isnt absolute or relative yet
if self._remote_path is not None and self._remote_path.startswith(
'.') is False and self._remote_path.startswith('/') is False:
self._remote_path = './' + self._remote_path
if self._username is None:
self._username = 'anonymous'
if self._port is None:
self._port = 22
def connect(self):
"""
Try to connect to the FTP server.
Raise an error if something went wrong.
"""
try:
self.ftps = FTP_TLS()
self.ftps.set_pasv(True)
self.ftps.connect(self._host, self._port)
except socket.gaierror:
raise
def login(self):
"""
Try to login in on the FTP server.
Raise an error if something went wrong.
"""
try:
self.ftps.login(self._username, self._password)
self.ftps.prot_p()
except ftplib.error_perm:
raise
def cwd(self):
"""
Try to switch the working directory on the FTP server (if set in the settings).
If the path does not exist, it will be created.
"""
if self._remote_path is not None:
try:
self.ftps.cwd(self._remote_path)
except ftplib.error_perm:
self.create_directory_tree(self._remote_path)
except IOError:
raise
def create_directory_tree(self, current_directory):
"""
Helper function to create the remote path.
@param current_directory: The current working directory.
@type current_directory: String
"""
if current_directory is not "":
try:
self.ftps.cwd(current_directory)
except ftplib.error_perm:
self.create_directory_tree("/".join(current_directory.split("/")[:-1]))
self.ftps.mkd(current_directory)
self.ftps.cwd(current_directory)
except IOError:
raise
def upload(self, callback=None):
"""
The upload function.
@param callback: The callback function for the upload progress.
#.........这里部分代码省略.........
示例3: FTPClient
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import mkd [as 别名]
#.........这里部分代码省略.........
if (not self._is_connected):
self._mh.demsg('htk_on_warning', self._mh._trn.msg(
'htk_ftp_not_connected'), self._mh.fromhere())
return False
ev = event.Event('ftp_before_delete_file', path)
if (self._mh.fire_event(ev) > 0):
path = ev.argv(0)
if (ev.will_run_default()):
self._client.delete(path)
self._mh.demsg('htk_on_debug_info', self._mh._trn.msg(
'htk_ftp_file_deleted'), self._mh.fromhere())
return True
except all_errors as ex:
self._mh.demsg(
'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere())
return False
def make_dir(self, path):
"""Method makes directory on server
Args:
path (str): remote path
Returns:
bool: result
Raises:
event: ftp_before_make_dir
"""
try:
self._mh.demsg('htk_on_debug_info', self._mh._trn.msg(
'htk_ftp_making_dir', path), self._mh.fromhere())
if (not self._is_connected):
self._mh.demsg('htk_on_warning', self._mh._trn.msg(
'htk_ftp_not_connected'), self._mh.fromhere())
return False
ev = event.Event('ftp_before_make_dir', path)
if (self._mh.fire_event(ev) > 0):
path = ev.argv(0)
if (ev.will_run_default()):
self._client.mkd(path)
self._mh.demsg('htk_on_debug_info', self._mh._trn.msg(
'htk_ftp_dir_made'), self._mh.fromhere())
return True
except all_errors as ex:
self._mh.demsg(
'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere())
return False
def remove_dir(self, path):
"""Method removes directory from server
Args:
path (str): remote path
Returns:
bool: result
Raises:
event: ftp_before_remove_dir
"""
try:
self._mh.demsg('htk_on_debug_info', self._mh._trn.msg(
'htk_ftp_removing_dir', path), self._mh.fromhere())
if (not self._is_connected):
self._mh.demsg('htk_on_warning', self._mh._trn.msg(
'htk_ftp_not_connected'), self._mh.fromhere())
return False
ev = event.Event('ftp_before_remove_dir', path)
if (self._mh.fire_event(ev) > 0):
path = ev.argv(0)
if (ev.will_run_default()):
self._client.rmd(path)
self._mh.demsg('htk_on_debug_info', self._mh._trn.msg(
'htk_ftp_dir_removed'), self._mh.fromhere())
return True
except all_errors as ex:
self._mh.demsg(
'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere())
return False
示例4: FTP_TLS
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import mkd [as 别名]
import sys,json
server = json.loads(sys.argv[1])
try:
if server['secure'] == True:
from ftplib import FTP_TLS
ftp = FTP_TLS()
else:
from ftplib import FTP
ftp = FTP()
ftp.connect(server['host'], server['port'])
ftp.login(server['user'], server['pass'])
try:
ftp.storbinary('STOR %s' % sys.argv[2], open(sys.argv[3], 'rb'))
except:
strsplt = sys.argv[2][1:].split('/')
strsplt = strsplt[:-1]
wdir = "/"+"/".join(strsplt)
ftp.mkd(wdir)
ftp.storbinary('STOR %s' % sys.argv[2], open(sys.argv[3], 'rb'))
ftp.quit()
except:
sys.exit(1)
示例5: len
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import mkd [as 别名]
images_to_upload = []
if image_list:
# Add first image
images_to_upload.append(image_list[0])
if len(image_list) > 1:
# Add last image (if more than 1 image)
images_to_upload.append(image_list[len(image_list)-1])
# Download oldest & newest image
for image in images_to_upload:
print 'Downloading %s...' % image
ftps.retrbinary('RETR %s' % image, open(image, 'wb').write)
# Check if directory for old images exists, if not create it
if 'old' not in directory_list:
print 'Creating dir "old"...'
ftps.mkd('old')
# Move checked images to old
for image in image_list:
#date_str = image.split('_')[1].split('.')[0]
#img_date = datetime.strptime(date_str, '%Y%m%d-%H%M%S')
print 'Moving %s to "old"...' % image
ftps.rename(image, 'old/%s' % image)
# Disconnect from FTP server
ftps.quit()
def upload_image(filename):
image_file = {'file': open(filename, 'rb')}
print 'Uploading %s to GroupMe image service...' % filename
r = requests.post('%s?access_token=%s' % (GROUPME_IMAGE_URL, TOKEN), files=image_file)
示例6: FTPSession
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import mkd [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
#.........这里部分代码省略.........
示例7: ServerWatcher
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import mkd [as 别名]
#.........这里部分代码省略.........
cmds = ['MFMT', 'MDTM']
for cmd in cmds:
try:
self.ftp.sendcmd(
'%s %s %s' % (cmd, newtime.strftime('%Y%m%d%H%M%S'), serverpath))
return
except (error_perm, error_reply) as e:
if cmd == cmds[len(cmds) - 1]:
# If is the last comand, re-raise the exception, else
# keep trying.
raise e
else:
continue
def mkpath(self, path):
"""
Creates the path `path` on the server by recursively
created folders, if needed.
:param path: Absolute path on the server to be created
"""
try:
self.ftp.cwd(path)
except error_perm:
# `cwd` call failed. Need to create some folders
make_dir = '/'
steps = path.split('/')
for step in steps:
if len(step) == 0:
continue
make_dir += '%s/' % step
try:
self.ftp.mkd(make_dir)
except error_perm:
# Probably already exists
continue
else:
# `cwd` call succeed. No need to create
# any folders
self.ftp.cwd('/')
return
@Slot(str, str)
def added(self, location, serverpath):
super(ServerWatcher, self).added(location, serverpath)
def actionFromPath(serverpath):
f = File()
fileExistsOnServer = True
try:
f.servermdate = self.lastModified(serverpath)
except error_perm:
fileExistsOnServer = False
f.servermdate = 0
f.localmdate = LocalWatcher.lastModified(self.localFromServer(serverpath))
diff = f.timeDiff()
action = None
if abs(diff) > Watcher.TOLERANCE:
if not fileExistsOnServer or diff > 0:
action = FileAction(serverpath, FileAction.UPLOAD, ServerWatcher.LOCATION)
else:
action = FileAction(serverpath, FileAction.DOWNLOAD, LocalWatcher.LOCATION)
return action