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()
def ftp_connection(): ftp_conn = None try: logger = get_logger() logger.info("Creating object FTP_TLS()") ftp_conn = FTP_TLS() logger.info("Trying to connect to FTP(%s, %d)", FTP_HOST_NAME, FTP_PORT_NUMBER) ftp_conn.connect(FTP_HOST_NAME, FTP_PORT_NUMBER) ftp_conn.auth() logger.info("auth() 0k") ftp_conn.prot_p() logger.info("prot_p() 0k") logger.info("Trying with FTP_USER_NAME = %s", FTP_USER_NAME) ftp_conn.login(user=FTP_USER_NAME, passwd=FTP_ACCESS_KEY) ftp_conn.set_debuglevel(2) logger.info('Connected') except Exception as e: logger.error('Not connected %s', e) return ftp_conn
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()
def connect_ftps(): #Connect to the server print("Step 1") if SECURE_CONN == '1': ftps = FTP_TLS(SERVER) print("Secure connection") else: ftps = FTP(SERVER) print("Unsecure connection") print("Step 2") ftps.set_debuglevel(2) print("Step 3") ftps.set_pasv(False) print("Step 4") ftps.connect(port=int(PORT), timeout=160) print("Step 5") ftps.login(USER, PASS) print("Step 6") ftps.cwd(TARGET_DIR) print("Step 7") ftps.set_pasv(True) print("Step 8") #Set up the secure connection only in FTPS mode if SECURE_CONN == '1': ftps.prot_p() else: pass #ftps.ccc() return ftps
def _open_ftp(self): # type: () -> FTP """Open a new ftp object.""" _ftp = FTP_TLS() if self.tls else FTP() _ftp.set_debuglevel(0) with ftp_errors(self): _ftp.connect(self.host, self.port, self.timeout) _ftp.login(self.user, self.passwd, self.acct) try: _ftp.prot_p() # type: ignore except AttributeError: pass self._features = {} try: feat_response = _decode(_ftp.sendcmd("FEAT"), "latin-1") except error_perm: # pragma: no cover self.encoding = "latin-1" else: self._features = self._parse_features(feat_response) self.encoding = "utf-8" if "UTF8" in self._features else "latin-1" if not PY2: _ftp.file = _ftp.sock.makefile( # type: ignore "r", encoding=self.encoding) _ftp.encoding = self.encoding self._welcome = _ftp.welcome return _ftp
def get_ftp_list(): ftp = FTP_TLS() ftp.connect(host, port) ftp.set_debuglevel(2) ftp.login("account_id", "account_password") files, dir = get_list_ftp(ftp, "/") return files, dir
def upload_to_ftp(root_dir, upload_path): ftp = FTP_TLS() ftp.connect(host, port) ftp.set_debuglevel(2) ftp.login("account_id", "account_password") files, directories = get_list_local(upload_path) directory_name = os.path.dirname(upload_path) directory_name = os.path.basename(directory_name) root_dir = root_dir + directory_name + "/" directories.insert(0, "") for directory in directories: path = directory.replace(upload_path, "").replace("\\", "/") path = root_dir + path # for fName in ftp.nlst(): # print(fName) # if folderName in ftp.nlst(): # continue try: ftp.mkd(path) except: continue print("Make directory is " + path) for file in files: path = file.replace(upload_path, "").replace("\\", "/") with open(file, "rb") as localfile: path = root_dir + path ftp.storbinary('STOR ' + path, localfile) print("Upload file is " + path) print("done upload")
def check_ftps(hostname, temp_name, username, password, verbose): ftps_services_failed = [] if verbose: print("-" * 60) if verbose: print(temp_name) ftps = FTP_TLS(hostname) ftps.login(username, password) ftps.prot_p() #ftps.retrlines('LIST') if verbose: ftps.set_debuglevel(2) # Upload the file if verbose: print("FTPS: Uploading the file.") try: ftps.storbinary('STOR {0}'.format('ftps.txt'), open(temp_name, 'rb')) except: if verbose: print("FTPS: Uploading the file failed.") ftps_services_failed.append('ftps_upload') else: if verbose: print("FTPS: Uploaded file successfully.") pass # Download the file if verbose: print("FTPS: Downloading the file.") try: myfile = open('/tmp/ftps.txt', 'wb') ftps.retrbinary('RETR {0}'.format('ftps.txt'), myfile.write) except: if verbose: print("FTPS: Downloading the uploaded file failed.") ftps_services_failed.append('ftps_download') else: if verbose: print("FTPS: Downloaded the uploaded file successfully.") # Delete the file from remote system try: ftps.delete('ftps.txt') except: if verbose: print("FTPS: Deleting uploaded file failed.") ftps_services_failed.append('ftps_delete') else: if verbose: print("FTPS: Deleted the uploaded file successfully.") pass # Close the ftps connection. ftps.close() # Detel the file which is downloaded delete_temp_file('/tmp/ftps.txt', verbose) return ftps_services_failed
def send(self): ftp = FTP(self.ftp_destination) ftp.set_debuglevel(2) ftp.ssl_version = ssl.PROTOCOL_TLSv1_2 ftp.login() ftp.cwd("upload") ftp.prot_p() self.zip.close() self.zip_contents.seek(0) ftp.storbinary("STOR {}".format(self.zip_contents.name), self.zip_contents)
def upload_file(): if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] # if filename is empty if file.filename == '': flash('No file selected for uploading') return redirect(request.url) # if file is available and have extension of mp4, avi, webm is saved in proect directory if file and allowed_file(file.filename): filename = secure_filename(file.filename) # saving the video file file.save(filename) flash('File successfully uploaded') secure = request.form['secure'] if secure == "FTP": ftp = FTP() ftp.connect('localhost', 21) status = ftp.login('testuser1', 'testuser') print("FTP Connected", status) fp = open(filename, 'rb') ftp.storbinary('STOR %s' % os.path.basename(filename), fp, 1024) return render_template('success.html', name=filename) elif secure == "FTP TLS": ftps = FTP_TLS('localhost') ftps.set_debuglevel(2) ftps.login('testuser1', 'testuser') ftps.set_pasv(False) ftps.prot_p() fp = open(filename, 'rb') ftps.storbinary('STOR %s' % os.path.basename(filename), fp, 1024) return render_template('success.html', name=filename) else: flash('Allowed file types are txt, pdf, png, jpg, jpeg, gif') # return to the same page return redirect(request.url)
def _ftp_connect(): """ FTP TLS Connection from settings """ settings = request.env['b2b.settings'].get_default_params( fields=['server', 'user', 'password']) ftps = FTP_TLS(settings['server'], settings['user'], settings['password']) # Set debug (if debug mode is ON) if request.debug: ftps.set_debuglevel(_debug_level) # Secure connection ftps.prot_p() return ftps
def __SetupOneTest(self, user=None, passwd=''): if self.use_tls: ftp = FTP_TLS() else: ftp = FTP() ftp.connect(self.host, int(self.port)) ftp.set_debuglevel(self.debug_level) ftp.set_pasv(self.pasv_mode) if user: ftp.login(user, passwd) if self.__IsTransferTlsEnabled(): ftp.prot_p() return ftp
def linkFtp(folder=''): """ Handlser FTP per il caricamento dei dati su server remoto :param folder: sotto cartella di salvataggio remota :return: handler per la gestione """ # ftp = FTP_TLS() ftp = FTP_TLS(host=rl['host']) ftp.set_debuglevel(2) status = ftp.login(user=rl['username'], passwd=rl['password']) # comando per il cambio della directory di upload ftp.cwd(backup_folder+'/'+folder) # print the content of directory print(ftp.dir()) return ftp, status
def FTPconnect(self): #initial FTP object and login the HCA FTP server try: ftp = FTP_TLS() ftp.set_pasv(True,self.host) ftp.ssl_version = ssl.PROTOCOL_TLSv1 ftp.connect(host=self.host,port=21) ftp.set_debuglevel(2) ftp.auth() ftp.login(self.user,self.password) ftp.prot_p() print (time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())+' FTP login successful') return ftp except Exception as e: self.sns.informError() print (e)
def store_file(self, temp_path: str) -> str: conn = FTP_TLS(host=self.ftp_host) conn.set_debuglevel(2) conn.login( user=self.ftp_user, passwd=self.ftp_pass, ) conn.prot_p() ext = temp_path.split('.')[-1] file_name = f'{str(uuid4())}.{ext}' storage_path = f'{self.static_folder}/{file_name}' with open(temp_path, 'rb') as f: conn.storbinary(f'STOR {storage_path}', f) conn.quit() return f'https://{self.ftp_host}/sera/{file_name}'
def login(self,debug=2,set_pasv=True): _old_makepasv = FTP_TLS.makepasv def _new_makepasv(self): host, port = _old_makepasv(self) host = self.sock.getpeername()[0] return host, port FTP_TLS.makepasv = _new_makepasv ftps = FTP_TLS(self.host) ftps.set_debuglevel(debug) ftps.auth() ftps.login(self.user,self.pwd) ftps.makepasv() ftps.sendcmd('pbsz 0') ftps.set_pasv(set_pasv) ftps.prot_p() print("hello ") ftps.getwelcome() return ftps
def uploadFilesToFTP(ftpURL, ftpUser, ftpPassword, ftpPath, localPath, filematch, historyBackupPath): ftps = FTP_TLS(ftpURL) ftps.set_debuglevel(1) ftps.set_pasv(False) ftps.connect(port=21, timeout=80) ftps.login(ftpUser, ftpPassword) ftps.prot_p() ftps.ccc() try: ftps.cwd(ftpPath) except Exception: ftps.mkd(ftpPath) for (localPathDir, _, files) in os.walk(localPath): newdir = ftpPath try: ftps.cwd(newdir) except Exception: ftps.mkd(newdir) LOGGER.info("filematch=" + filematch) for f in fnmatch.filter(files, filematch): fileLocalPath = os.path.join(localPathDir, f) file = open(fileLocalPath, 'rb') ftps.storbinary('STOR ' + f, file, blocksize=8192) file.close() LOGGER.info("Fichero transferido #:# " + fileLocalPath) sleep(1) now = datetime.datetime.now() historyBackupPathYear = os.path.join(historyBackupPath, str(now.year)) try: os.stat(historyBackupPathYear) except: os.mkdir(historyBackupPathYear) moveFilesUUID(fileLocalPath, historyBackupPathYear) ftps.close()
def sauvegarde(self): lg = logging.getLogger() lg.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s;%(levelname)s;%(message)s;') file_handler = FileHandler('logs/' + datetime.now().strftime("%Y%m%d-%H-%M-%S") + '.log', 'a') file_handler.setLevel(logging.INFO) file_handler.setFormatter(formatter) lg.addHandler(file_handler) lg.info('Start Log') if not os.path.isdir('temp'): os.mkdir('temp') lg.info('Temp folder created') splogs = Thread(None, supplogs(lg)) flt = self.search([])[0].filestore_path flstr = Thread(None, filestoring(lg,flt)) db = str(self._cr.dbname) dbdp = Thread(None, dbdumping(lg, db)) splogs.start() flstr.start() dbdp.start() flstr.join() dbdp.join() splogs.join() lg.info('Start of the transfer') ftp = FTP_TLS() ftp.set_debuglevel(2) sauvegardes = self.search([]) for sauvegarde in sauvegardes: if sauvegarde.active: multiple_transfer(lg, ftp, db, sauvegarde)
def ftp_orders_b2c_tecnofin_connector(): cfg = get_config_constant_file() remote_host = cfg['ACCESS_B2C']['HOST'] remote_port = cfg['ACCESS_B2C']['PORT'] remote_username = cfg['ACCESS_B2C']['USERNAME'] remote_password = cfg['ACCESS_B2C']['PASSWORD'] remote_timeout = cfg['ACCESS_B2C']['TIME_OUT'] ftps = FTP_TLS(remote_host) ftps.set_debuglevel(2) ftps.set_pasv(True) ftps.connect(port=remote_port, timeout=remote_timeout) ftps.login(remote_username, remote_password) logger.info('FTP Connected to: %s', remote_username+'@'+str(remote_host)) ftps.prot_p() return ftps
def make_msg(self, args): # make connection conn = None if args.ssl or args.starttls: conn = FTP_TLS() conn.ssl_version = PROTOCOL_TLSv1 else: conn = FTP() if args.verbose: conn.set_debuglevel(1) conn.connect(args.host, args.port, args.timeout) if args.starttls: conn.auth() conn.prot_p() conn.login(args.user, args.password) self.conn = conn return args.message
def mainframe_connect(host, user='******', password='******'): ''' Creates ftp object, opens a connection to mainframe, login and secures de connection. Returns server output. Parameters: - host - server host or IP. - user - mainframe user name. If not given, 'anonymous' is used. - password - mainframe password. If not given, 'anonymous@' is used. ''' global rfftp output_msg = "" if __check_ftp_tls_status(True): rfftp = FTP_TLS(host) output_msg = rfftp.set_debuglevel(MAX_DEBUG_OUTPUT) rfftp.auth() output_msg = rfftp.login( user, password) # login before securing control channel print("Response login: "******"Response prot_p: " + output_msg) return
title = lead[0] #print url this_title = title["title"] this_url = url["url"] #print this_url leads_with_keywords[current_url_number] = [] leads_with_keywords[current_url_number].append( {'title': this_title}) leads_with_keywords[current_url_number].append( {'url': this_url}) current_url_number += 1 break current_lead_number += 1 with open('out2_lead.json', 'w') as outfile: json.dump(leads_with_keywords, outfile) exit ftp = FTP_TLS() ftp.set_debuglevel(2) ftp.connect('0000', 0000) ftp.sendcmd("USER user") ftp.sendcmd("PASS password") file = open('out2_lead.json', 'rb') ftp.storbinary('STOR out2_lead.json', file) file.close() ftp.close() os.remove("lead2.json") os.remove("out2_lead.json")
def lambda_handler(event, context): exec_id = f"{time.time()}".split('.')[0] ### RETRIEVE FILE FROM TAW ### # Set up connection to FTP server ftps = FTP_TLS() ftps.connect('ftp.tapww.com', 22, timeout=120) ftps.set_debuglevel(1) ftps.set_pasv(True) ftps.login(os.environ['taw_user'], os.environ['taw_pass']) ftps.prot_p() # Create local file to store contents of Inventory file f = open('/tmp/inv.txt', 'wb') # Retrieve the Inventory file contents and store locally ftps.retrbinary('RETR Inventory.txt', f.write) # Close local file f.close() # Close the connection ftps.quit() ### END RETRIEVE FILE FROM TAW ### ### READ INVENTORY FILE ### item_list = [] with open('/tmp/inv.txt', newline='') as items: reader = csv.reader(items, delimiter='\t') item_list = [[item[2], item[12]] for item in reader if item[2][:3] in LINES] print(f"Items found: {len(item_list)}") # Divide list into chunks for threading chunks = [] for i in range(0, len(item_list), 200): chunks.append(item_list[i:i + 200]) ### END READ INVENTORY FILE ### numChunks = len(chunks) print(f"Number of chunks: {numChunks}") ### INVOKE LAMBDA ONCE FOR EACH CHUNK ### i = 1 # only execute the first chunk while testing for eachChunk in chunks: print(f"Invoking lambda for chunk {i} of {numChunks}") lambda_client.invoke(FunctionName='updateInventory', InvocationType='Event', Payload=json.dumps({ 'id': exec_id, 'chunk': eachChunk, 'chunkNum': i })) i = i + 1 ### END INVOKE LAMBDA ONCE FOR EACH CHUNK ### return { 'statusCode': 202, 'headers': { 'Access-Control-Allow-Origin': '*' }, 'body': json.dumps({ 'id': exec_id, 'numItems': len(item_list), 'numChunks': numChunks }) }
class Ftps_client: ##初始化的时候会把登录参数赋值初始化 def __init__(self, host, user, pwd, port=21): self.host = host self.port = port self.user = user self.pwd = pwd self.Ftp = None #self._old_makepasv=FTP_TLS.makepasv ## ftp 登录项 含有闭包项 def login(self, debug=2, set_pasv=True): _old_makepasv = FTP_TLS.makepasv def _new_makepasv(self): host, port = _old_makepasv(self) host = self.sock.getpeername()[0] return host, port FTP_TLS.makepasv = _new_makepasv self.Ftp = FTP_TLS(self.host) self.Ftp.set_debuglevel(debug) self.Ftp.auth() self.Ftp.login(self.user, self.pwd) self.Ftp.makepasv() self.Ftp.sendcmd('pbsz 0') self.Ftp.set_pasv(set_pasv) self.Ftp.prot_p() print("您好 您已经登录 ftp: %s 服务器" % self.host) self.Ftp.getwelcome() return self.Ftp #显示 目录下的 文件列表 def ftplistDir(self, ftps, sever_path): self.Ftp.cwd("/") #首先切换得到根目录下,否则会出现问题 self.Ftp.cwd(sever_path) files = ftps.nlst() for f in files: print(f) # 下载服务器文件 def ftpDownloadSeverFile(self, sever_path, sever_file, new_localfile, buffersize=1024): self.Ftp.cwd("/") self.Ftp.cwd(sever_path) with open(new_localfile, 'wb') as download_file: self.Ftp.retrbinary('RETR %s' % sever_file, download_file.write, buffersize) ##上传文件 需要注意 上传文件的 new_severfile 只能是文件名,不能包含带目录 的 文件全路径 def ftpUploadLocalFile(self, local_filepath, sever_path, new_severfile, buffersize=1024): self.Ftp.cwd("/") self.Ftp.cwd(sever_path) with open(local_filepath, 'rb') as upload_file: self.Ftp.storbinary('STOR ' + new_severfile, upload_file, buffersize)
from ftplib import FTP_TLS import os ftps = FTP_TLS(timeout=100) ftps.set_debuglevel(1) ftps.connect("192.168.1.35", 21) ftps.auth() ftps.prot_p() ftps.login('pan', '1') print(ftps.getwelcome()) print(ftps.pwd()) ftps.dir() # 下载文件 os.chdir(r'D:\Desktop\FTP_TLS\FTP\00临时存储') ftps.cwd('/') ftps.nlst() # 获取目录下的文件 filename = 'vsftpd.key' file_handle = open(filename, "wb").write ftps.retrbinary('RETR %s' % os.path.basename(filename), file_handle, blocksize=1024) # 下载ftp文件 # 上传到服务器 bufsize = 1024 localpath = 'D:\\Desktop\\FTP_TLS\FTP\\00临时存储\\test.txt' remotepath = '/test.txt' fp = open(localpath, 'rb') ftps.storbinary('STOR ' + remotepath, fp, bufsize) # 打印证书 print(ftps.context) print(ftps.certfile)
class FTPClient(object): """Class FTPClient """ _mh = None _client = None _secured = None _host = None _port = None _user = None _passw = None _path = None _verbose = None _is_connected = None def __init__(self, secured=False, verbose=False): """Class constructor Called when the object is initialized Args: secured (bool): secured FTP verbose (bool): verbose mode """ self._mh = MasterHead.get_head() self._secured = secured if (not self._secured): self._client = FTP() else: if (not(version_info[0] == 2 and version_info[1] == 6)): self._client = FTP_TLS() else: raise NotImplementedError( 'Secured mode is not supported for Python 2.6') self._verbose = verbose if (self._verbose): self._client.set_debuglevel(2) @property def client(self): """ FTP client property getter """ return self._client @property def secured(self): """ secured protocol mode property getter """ return self._secured @property def host(self): """ server host property getter """ return self._host @property def port(self): """ server port property getter """ return self._port @property def user(self): """ username property getter """ return self._user @property def passw(self): """ user password property getter """ return self._passw @property def path(self): """ remote path property getter """ return self._path @property def verbose(self): """ verbose mode property getter """ return self._verbose @property def is_connected(self): """ is_connected property getter """ return self._is_connected def connect(self, host, port=21, user=None, passw=None, path='/', timeout=10): """Method connects to server Args: host (str): server host port (int): server port, default protocol port user (str): username passw (str): password path (str): server path timeout (int): timeout Returns: bool: result Raises: event: ftp_before_connect event: ftp_after_connect """ try: message = '{0}/{1}@{2}:{3}{4} timeout:{5}'.format( user, passw, host, port, path, timeout) self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_connecting', message), self._mh.fromhere()) ev = event.Event( 'ftp_before_connect', host, port, user, passw, path, timeout) if (self._mh.fire_event(ev) > 0): host = ev.argv(0) port = ev.argv(1) user = ev.argv(2) passw = ev.argv(3) path = ev.argv(4) timeout = ev.argv(5) self._host = host self._port = port self._user = user self._passw = passw if (ev.will_run_default()): self._client.connect(self._host, self._port, timeout=timeout) if (self._user != None): self._client.login(self._user, self._passw) if (self._secured): self._client.prot_p() self._is_connected = True self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_connected'), self._mh.fromhere()) if (path != None): self.change_dir(path) ev = event.Event('ftp_after_connect') 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 disconnect(self): """Method disconnects from server Args: none Returns: bool: result """ try: if (not self._is_connected): self._mh.demsg('htk_on_warning', self._mh._trn.msg( 'htk_ftp_not_connected'), self._mh.fromhere()) return False else: self._client.quit() self._is_connected = False self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_disconnected'), 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 list_dir(self): """Method lists remote working directory Args: none Returns: list: names """ try: self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_list_dir', self._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 names = self._client.nlst() if ('.' in names): names.remove('.') if ('..' in names): names.remove('..') return names except all_errors as ex: self._mh.demsg( 'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere()) return None def change_dir(self, path): """Method changes remote working directory Args: path (str): new remote path Returns: bool: result Raises: event: ftp_before_change_dir """ try: self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_change_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_change_dir', path) if (self._mh.fire_event(ev) > 0): path = ev.argv(0) if (ev.will_run_default()): self._client.cwd(path) self._path = self._client.pwd() self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_cur_dir', self._path), 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 download_file(self, remote_path, local_path=None): """Method downloads file from server Args: remote_path (str): remote path local_path (str): local path, default ./filename Returns: bool: result Raises: event: ftp_before_download_file event: ftp_after_download_file """ try: self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_downloading_file', remote_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_download_file', remote_path, local_path) if (self._mh.fire_event(ev) > 0): remote_path = ev.argv(0) local_path = ev.argv(1) if (local_path != None and not path.exists(local_path)): self._mh.demsg('htk_on_error', self._mh._trn.msg( 'htk_ftp_unknown_dir', local_path), self._mh.fromhere()) return False filename = remote_path.split('/')[-1] lpath = filename if (local_path == None) else path.join( local_path, filename) if (ev.will_run_default()): with open(lpath, 'wb') as f: self._client.retrbinary('RETR ' + remote_path, f.write) self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_file_downloaded'), self._mh.fromhere()) ev = event.Event('ftp_after_download_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()) if (path.exists(lpath)): remove(lpath) return False def upload_file(self, local_path, remote_path=None): """Method uploads file to server Args: local_path (str): local path remote_path (str): remote path, default ./filename Returns: bool: result 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()) 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
os.makedirs(dir_path) os.chmod(dir_path, 0777) picamera = picamera.PiCamera() #picamera.resolution = (1920, 1080) #HD Quality Size=1.5MB、研究材料としては最低限これくらいはほしい。稲穂の様子はこの撮影データを拡大して確認したい #picamera.resolution = (1024, 768) # こちらは554KBで済む picamera.resolution = (800, 600) # こちらは●●●KBで済む #picamera.start_preview() # Camera warm-up time、Whiteバランスをとるための猶予時間。これがないと色が青白くて使い物にならない time.sleep(2) file_name = file_name+'.jpg' picamera.capture(dir_path+'/'+file_name) print "Now start Upload." _ftps = FTP_TLS(userID) _ftps.set_debuglevel(1) # デバッグログをリアルタイムで確認 _ftps.login(archive_server,pw) _file = open(dir_path+'/'+file_name, 'rb') #target file. 次のステップでアップロード成功したら削除した方がよいのではないか? #SD Memoryがパンクする恐れがあるので、次のステップでアップロードが成功したらファイルは削除するように、改良しましょう。 _ftps.cwd(put_directory) try: _ftps.cwd(dir_name) #target_dir 撮影データは日付付きのフォルダ内に納められる。 except Exception as e: #ディレクトリがなければ '550 Failed to change directory.' が帰ってくる。 #もし、"550"があれば...まだその日のフォルダはないので、新規作成 ## if str(e).count('550') : 文字列が含まれるかどうかの判定はこの関数を使ってもよいが、次の書き方が分かりやすい。 if '550' in str(e): _ftps.mkd(dir_name) _ftps.cwd(dir_name)