# -*- coding: utf-8 -*- """ Test SFTP client """ import tempfile import logging import sys import os import getpass from mylib.sftp import SFTPClient from mylib.scripts.helpers import get_opts_parser, add_sftp_opts from mylib.scripts.helpers import init_logging log = logging.getLogger('mylib.scripts.sftp_test') def main(argv=None): # pylint: disable=too-many-locals,too-many-statements """ Script main """ if argv is None: argv = sys.argv[1:] # Options parser parser = get_opts_parser(just_try=True) add_sftp_opts(parser) test_opts = parser.add_argument_group('Test SFTP options') test_opts.add_argument( '-p', '--remote-upload-path', action="store", type=str, dest="upload_path", help="Remote upload path (default: on remote initial connection directory)", ) options = parser.parse_args() # Initialize logs init_logging(options, 'Test SFTP client') if options.sftp_user and not options.sftp_password: options.sftp_password = getpass.getpass('Please enter SFTP password: ') log.info('Initialize Email client') sftp = SFTPClient(options=options, just_try=options.just_try) sftp.connect() log.debug('Create tempory file') tmp_file = tempfile.NamedTemporaryFile() # pylint: disable=consider-using-with log.debug('Temporary file path: "%s"', tmp_file.name) tmp_file.write(b'Juste un test.') log.debug( 'Upload file %s to SFTP server (in %s)', tmp_file.name, options.upload_path if options.upload_path else "remote initial connection directory") if not sftp.upload_file(tmp_file.name, options.upload_path): log.error('Fail to upload test file on SFTP server') else: log.info('Test file uploaded on SFTP server') remote_filepath = ( os.path.join(options.upload_path, os.path.basename(tmp_file.name)) if options.upload_path else os.path.basename(tmp_file.name) ) if sftp.remove_file(remote_filepath): log.info('Test file removed on SFTP server') else: log.error('Fail to remove test file on SFTP server') sftp.close()