本文整理汇总了Python中ftplib.FTP_TLS.storbinary方法的典型用法代码示例。如果您正苦于以下问题:Python FTP_TLS.storbinary方法的具体用法?Python FTP_TLS.storbinary怎么用?Python FTP_TLS.storbinary使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ftplib.FTP_TLS
的用法示例。
在下文中一共展示了FTP_TLS.storbinary方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: doRequest
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import storbinary [as 别名]
def doRequest():
# Send the file up to the FTP server
print ("Upload picture start")
ftp = FTP_TLS('individual.utoronto.ca', 'USER','1PASS.')
file = open('data.jpg','rb') # file to send
ftp.storbinary('STOR data.jpg', file) # send the file
file.close() # close file and FTP
ftp.quit()
print ("Upload picture complete")
print ("Requesting file request")
reqUrlA = 'http://api.cloudsightapi.com/image_requests/' # get token
reqUrlB = 'http://api.cloudsightapi.com/image_responses/' # get the final recognition result with token
headers = {
'Authorization' : 'CloudSight 149xzcR0nYPrwThNXVLecQ',
}
postData = {
'image_request[remote_image_url]' : "http://individual.utoronto.ca/timlock/data.jpg",
'image_request[locale]': "en_us",
'image_request[language]': "en"
}
try:
response = requests.post(reqUrlA, headers=headers, params=postData)
except Exception, e:
print 'Error: connection error, please check your Internet and confirm the image url'
print e
return ("FAILED")
示例2: Push
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import storbinary [as 别名]
def Push( FtpServer, Username, Password, uploadlist = FilesToPut, port = 21, passive = False, StartTls = False ):
print "Login to %s:%s using %s:%s (%s%s)"%(FtpServer, port, Username, 'xxx',
'passive' if passive else 'active',
'/tls' if StartTls else '')
if StartTls:
ftp = FTP_TLS()
else:
ftp = FTP()
#ftp.set_debuglevel(2)
ftp.connect( FtpServer, port )
ftp.login( Username, Password ) # user anonymous, passwd [email protected]
ftp.set_pasv( passive )
if StartTls:
ftp.prot_p()
for f in uploadlist:
print "uploading %s"%f
fp = open( f, 'rb')
ftp.storbinary('STOR %s'%os.path.basename(f), fp) # send the file
ftp.quit()
示例3: sendPackagesFtp
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import storbinary [as 别名]
def sendPackagesFtp():
print "---- Send packages by FTP"
global serverFtp
global userFtp
global passFtp
from ftplib import FTP_TLS
ftps = FTP_TLS(serverFtp)
ftps.set_debuglevel(1)
ftps.login(userFtp, passFtp)
ftps.prot_p()
try:
ftps.sendcmd('MKD ' + '/files/' + strProductVer)
except Exception:
print 'Directory already exists'
ftps.cwd('/files/' + strProductVer)
filesListFtp = ftps.nlst()
filesList = os.listdir(packagesPath)
newFilesList = [e for e in filesList if not(e in filesListFtp)]
for fileName in newFilesList:
ftps.storbinary('STOR ' + fileName, open(packagesPath + '\\' + fileName, 'rb'))
ftps.quit()
示例4: ftpUpload
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import storbinary [as 别名]
def ftpUpload(filename):
from ftplib import FTP_TLS
import os
ftps = FTP_TLS()
ftps.connect('pwcrack.init6.me', '21')
ftps.auth()
ftps.login('DC214', 'passwordcrackingcontest')
ftps.prot_p()
ftps.set_pasv(True)
local_file = open(filename, 'rb')
ftps.storbinary('STOR '+filename, local_file)
示例5: file_ftps
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import storbinary [as 别名]
def file_ftps(host,un,pw,ftp_filename,source_filename):
try:
ftps = FTP_TLS(host)
ftps.auth_tls()
ftps.login(un,pw)
ftps.prot_p()
ftps.storbinary("STOR " + ftp_filename, file(source_filename, "rb"))
ftps.quit()
except ftplib.all_errors, error:
print 'Error:', str(error)
logging.info(mydate+ ' - '+'FTPS Error Encountered: '+ str(error))
sys.exit(0)
示例6: Push
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import storbinary [as 别名]
def Push( FtpServer, Username, Password, uploadlist = FilesToPut, port = 21, passive = False, StartTls = False, Sftp = False ):
print "Login to %s:%s using %s:%s (%s%s)"%(FtpServer, port, Username, 'xxx',
'passive' if passive else 'active',
'/tls' if StartTls else '')
if Sftp:
paramiko.util.log_to_file('/tmp/paramiko.log')
transport = paramiko.Transport((FtpServer,int(port)))
transport.connect(username = Username, password = Password)
sftp = paramiko.SFTPClient.from_transport(transport)
print "Uploading file"
filepath = '../php/basedata.php'
localpath = 'basedata.php'
sftp.put(filepath, localpath)
sftp.close()
transport.close()
else:
if StartTls:
ftp = FTP_TLS()
else:
ftp = FTP()
ftp.connect( FtpServer, port )
ftp.login( Username, Password)
ftp.set_pasv( passive )
if StartTls:
ftp.prot_p()
for f in uploadlist:
print "uploading %s"%f
fp = open( f, 'rb')
ftp.storbinary('STOR %s'%os.path.basename(f), fp) # send the file
ftp.quit()
if __name__ == "__main__":
if len(sys.argv) < 5:
print >> sys.stderr, "usage %s <server> <port> <username> <password>"%sys.argv[0]
exit( 1 )
FtpServer = sys.argv[1]
Port = sys.argv[2]
Username = sys.argv[3]
Passwd = sys.argv[4]
Push( FtpServer, Username, Passwd, port = Port )
print >> sys.stderr, "Done"
示例7: sendUpdateFilesFtp
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import storbinary [as 别名]
def sendUpdateFilesFtp():
print "---- Send update files by FTP"
global serverFtp
global userFtp
global passFtp
from ftplib import FTP_TLS
ftps = FTP_TLS(serverFtp)
ftps.set_debuglevel(1)
ftps.login(userFtp, passFtp)
ftps.prot_p()
ftps.cwd('/files/updates')
ftps.storbinary('STOR ' + 'file_list.md5', open(quiterssFileRepoPath + '\\file_list.md5', 'rb'))
ftps.storbinary('STOR ' + 'VersionNo.h', open(quiterssSourcePath + '\\src\\VersionNo.h', 'rb'))
ftps.storbinary('STOR ' + 'HISTORY_EN', open(quiterssSourcePath + '\\HISTORY_EN', 'rb'))
ftps.storbinary('STOR ' + 'HISTORY_RU', open(quiterssSourcePath + '\\HISTORY_RU', 'rb'))
prepareFileList7z = []
for file in prepareFileList:
prepareFileList7z.append(file + '.7z')
for fileName in prepareFileList7z:
ftps.storbinary('STOR ' + 'windows' + fileName.replace('\\','/'), open(quiterssFileRepoPath + '\\windows' + fileName, 'rb'))
ftps.quit()
示例8: ftp_files
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import storbinary [as 别名]
def ftp_files(domain, remote_paths, local_paths, direction, secure=True):
ftp = FTP_TLS(domain) if secure else FTP(domain)
ftp.login(prompt_usr(), prompt_pw())
if secure:
ftp.prot_p()
for remote_path, local_path in zip(remote_paths, local_paths):
if direction.lower() == 'up':
ftp.storbinary('STOR ' + remote_path, open(local_path, 'rb'))
elif direction.lower() == 'down':
ftp.retrbinary('RETR ' + remote_path, open(local_path, 'wb').write)
else:
raise Exception('Invalid direction: ' + direction)
ftp.quit()
示例9: ftpUpload
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import storbinary [as 别名]
def ftpUpload(filename, system):
from ftplib import FTP_TLS
import os
if os.path.isfile(filename):
zipFilename = compressit(filename, system)
ftps = FTP_TLS()
ftps.connect('pwcrack.init6.me', '21')
ftps.auth()
ftps.login('DC214', 'passwordcrackingcontest')
ftps.prot_p()
ftps.set_pasv(True)
local_file = open(zipFilename, 'rb')
ftps.storbinary('STOR '+zipFilename, local_file)
print "file %s has been uploaded." % zipFilename
return True
示例10: connect
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import storbinary [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
示例11: uploadToFtp
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import storbinary [as 别名]
def uploadToFtp(fileList, remoteDir, host, user, password):
"""
:type fileList: list
:type remoteDir: basestring
:type host: basestring
:type user: basestring
:type password: basestring
"""
ftps = FTP_TLS(host)
ftps.sendcmd('USER %s' % user)
ftps.sendcmd('PASS %s' % password)
for fileItem in fileList:
fileName = os.path.split(fileItem)[1]
remoteFilePath = os.path.join(remoteDir, fileName)
print('Uploading file [{0}] to ftp at [{1}]'.format(fileName, remoteFilePath))
ftps.storbinary('STOR {0}'.format(remoteFilePath), open(fileItem))
print('Done.')
ftps.quit()
示例12: FTP_TLS
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import storbinary [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)
示例13: __init__
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import storbinary [as 别名]
#.........这里部分代码省略.........
"""
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.
@type callback: Function
"""
self._uploadCallback = callback
zipfile_to_upload = open(self._absolute_zipfile_path, 'rb')
zipfile_basename = os.path.basename(self._absolute_zipfile_path)
self.ftps.storbinary('STOR %s' % zipfile_basename, zipfile_to_upload, 1024, self.handle_upload_state)
zipfile_to_upload.close()
def handle_upload_state(self, block):
"""
The callback function for the upload progress.
@param block: The StringIO of the current upload state
@type block: StringIO
"""
self._bytesWritten += 1024
progress = math.floor((float(self._bytesWritten) / float(self._totalFileSize)) * 100)
do_update = False
if progress > self._currentProgress:
do_update = True
self._currentProgress = progress
if self._uploadCallback is not None:
self._uploadCallback(progress, self, do_update)
def quit(self):
"""
Try to quit everything and close the session.
"""
self.ftps.quit()
@property
def upload_path(self):
"""
Returns the upload path of the FTP server.
@return: The path of the uploaded file on the FTP server.
@rtype: String
"""
tmp_remote_path = ''
if self._remote_path is not None:
tmp_remote_path = self._remote_path
return os.path.join(tmp_remote_path, os.path.basename(self._absolute_zipfile_path))
示例14: FTPClient
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import storbinary [as 别名]
#.........这里部分代码省略.........
Raises:
event: ftp_before_upload_file
event: ftp_after_upload_file
"""
try:
self._mh.demsg('htk_on_debug_info', self._mh._trn.msg(
'htk_ftp_uploading_file', local_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_upload_file', local_path, remote_path)
if (self._mh.fire_event(ev) > 0):
local_path = ev.argv(0)
remote_path = ev.argv(1)
if (not(path.exists(local_path) or path.exists(path.relpath(local_path)))):
self._mh.demsg('htk_on_error', self._mh._trn.msg(
'htk_ftp_unknown_file', local_path), self._mh.fromhere())
return False
filename = local_path.split('/')[-1]
rpath = filename if (remote_path == None) else path.join(
remote_path, filename)
if (ev.will_run_default()):
with open(local_path, 'rb') as f:
self._client.storbinary('STOR ' + rpath, f)
self._mh.demsg('htk_on_debug_info', self._mh._trn.msg(
'htk_ftp_file_uploaded'), self._mh.fromhere())
ev = event.Event('ftp_after_upload_file')
self._mh.fire_event(ev)
return True
except all_errors as ex:
self._mh.demsg(
'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere())
return False
def delete_file(self, path):
"""Method deletes file from server
Args:
path (str): remote path
Returns:
bool: result
Raises:
event: ftp_before_delete_file
"""
try:
self._mh.demsg('htk_on_debug_info', self._mh._trn.msg(
'htk_ftp_deleting_file', path), self._mh.fromhere())
示例15: FTPSession
# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import storbinary [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
#.........这里部分代码省略.........