def put_file(self, src, dest): """Uploads a file to the tftp server. .. note:: * TftpClient is not threadsafe, so we create a unique instance for each transfer. >>> e_tftp.put_file(src='local_file.txt', dest='remote_name.txt') :param src: Source file path (on your local machine). :type src: string :param dest: Destination path (on the TFTP server). :type dest: string :raises TftpException: If the file cannot be written to the TFTP server. :raises TftpException: If a TypeError is received from tftpy. """ try: client = TftpClient(self.ip_address, self.port) client.upload(input=src, filename=dest) except TftpException: if (self.verbose): traceback.format_exc() raise except TypeError: if (self.verbose): traceback.format_exc() raise TftpException("Failed to upload file to TFTP server")
class TestTFTPServer(unittest.TestCase): def setUp(self): conpot_core.initialize_vfs() self.tftp_server, self.greenlet = spawn_test_server(TftpServer, template="default", protocol="tftp") self.client = TftpClient(self.tftp_server.server.server_host, self.tftp_server.server.server_port) self._test_file = "/".join(conpot.__path__ + ["tests/data/test_data_fs/tftp/test.txt"]) def tearDown(self): teardown_test_server(self.tftp_server, self.greenlet) @freeze_time("2018-07-15 17:51:17") def test_tftp_upload(self): """Testing TFTP upload files. """ self.client.upload("test.txt", self._test_file) _, _data_fs = conpot_core.get_vfs("tftp") [_file] = [ i for i in _data_fs.listdir("./") if "2018-07-15 17:51:17-test-txt" in i ] self.assertEqual( _data_fs.gettext(_file), "This is just a test file for Conpot's TFTP server\n", ) _data_fs.remove(_file) @freeze_time("2018-07-15 17:51:17") def test_mkdir_upload(self): """Testing TFTP upload files - while recursively making directories as per the TFTP path.""" self.client.upload("/dir/dir/test.txt", self._test_file) _, _data_fs = conpot_core.get_vfs("tftp") [_file] = [ i for i in _data_fs.listdir("./") if "2018-07-15 17:51:17-test-txt" in i ] self.assertEqual( _data_fs.gettext(_file), "This is just a test file for Conpot's TFTP server\n", ) _data_fs.remove(_file) def test_tftp_download(self): _dst_path = "/".join(conpot.__path__ + ["tests/data/data_temp_fs/tftp/download"]) try: self.client.download("tftp_data.txt", _dst_path) self.assertTrue(filecmp.cmp(_dst_path, self._test_file)) finally: _, _data_fs = conpot_core.get_vfs("tftp") _data_fs.remove("download")
class Client: """ Create a Client object that uses the tftpy module to connect to a TFTP server. Makes it possible to download from or upload to a TFTP server. Only accepts .pdf files. """ def __init__(self, host_ip=socket.gethostbyname(socket.gethostname()), port=DEFAULT_PORT): self.client = TftpClient(host_ip, port) self.files = [] self.file_search = glob.glob def upload(self, local_file_name, remote_file_name=None): """ Uploads a file to the server. :param local_file_name: Path of the file locally :param remote_file_name: Path where the file will be written to on the server. """ if not remote_file_name: remote_file_name = DEFAULT_HOST_PATH + ntpath.basename( local_file_name) self.client.upload(remote_file_name, local_file_name) def upload_folder(self, path=DEFAULT_CLIENT_PATH, host_path=None): """ :param path: Local path of the folder. :param host_path: Path of the folder on the server where files will be written to. """ self.files = self.file_search(path + '/*.pdf') for f in self.files: if not host_path: self.upload(f) else: self.upload(f, host_path + ntpath.basename(f)) @staticmethod def enable_logging(): """ Enables logging for the tftpy module. """ tftpy.setLogLevel('INFO') fh = logging.FileHandler(os.getcwd() + '/logging/log_client_' + time.strftime('%d-%m-%Y_%H:%M:%S')) formatter = logging.Formatter( '%(asctime)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) tftpy.log.addHandler(fh)
def checkTFTP(url, port, block = '512'): response = {} try: tftp_options = {} tftp_options['blksize'] = int(block) b = time() cliente = TftpClient(url, int(port), tftp_options) a = time() - b response['Tiempo Conexion (s)'] = a b = time() cliente.download(file, file) a = time() - b response['Tiempo Descarga (s)'] = a b = time() cliente.upload(file, file) a = time() - b response['Tiempo Carga (s)'] = a response['status'] = 'Up' except: response['status'] = 'Down' return response
def verify_server(self): ip = self.server_info['address'] port = self.server_info['port'] path = self.server_info['path'] # Set up client logging logfile = self.server_info.get('logfile', None) if logfile: logfile = '%s.client%s' % os.path.splitext(logfile) ftp_logger = logging.getLogger('tftpy') ftp_logger.setLevel(logging.DEBUG) ftp_logger.propagate = False ftp_handler = logging.FileHandler(logfile) ftp_logger.addHandler(ftp_handler) # Create a temporary file to copy to the TFTP server with tempfile.TemporaryDirectory() as tmpdir: # Create a file that will not conflict with any existing files filename = self._generate_filename() filepath = os.path.join(tmpdir, filename) with open(filepath, 'w') as f: f.write('ab' * 100) # can't write to root. Use tmpdir instead if path == '/': filename = os.path.join(tmpdir, '%s2' % filename) client = TftpClient(ip, port) client.upload(filename, filepath) # Confirm file was copied upfilepath = os.path.join(path, filename) if not os.path.isfile(upfilepath): raise OSError('TFTP Upload unsuccessful') os.remove(upfilepath)
class FTPClient(object): """Class FTPClient """ _mh = None _client = None _host = None _port = None _verbose = None _is_connected = None _timeout = None def __init__(self, verbose=False): """Class constructor Called when the object is initialized Args: verbose (bool): verbose mode """ self._mh = MasterHead.get_head() self._verbose = verbose if (self._verbose): TftpShared.setLogLevel(2) @property def client(self): """ TFTP client property getter """ return self._client @property def host(self): """ server host property getter """ return self._host @property def port(self): """ server port property getter """ return self._port @property def verbose(self): """ verbose mode property getter """ return self._verbose @property def is_connected(self): """ is_connected property getter """ return self._verbose def connect(self, host, port=69, timeout=10): """Method connects to server Args: host (str): server host port (int): server port, default protocol port timeout (int): timeout Returns: bool: result Raises: event: ftp_before_connect event: ftp_after_connect """ try: message = '{0}:{1} timeout:{2}'.format(host, port, 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, timeout) if (self._mh.fire_event(ev) > 0): host = ev.argv(0) port = ev.argv(1) timeout = ev.argv(2) self._host = host self._port = port self._timeout = timeout if (ev.will_run_default()): self._client = TftpClient(self._host, self._port) self._is_connected = True self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_ftp_connected'), self._mh.fromhere()) ev = event.Event('ftp_after_connect') self._mh.fire_event(ev) return True except TftpShared.TftpException 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()): self._client.download(filename, lpath, timeout=self._timeout) 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 (TftpShared.TftpException, IOError) 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()): self._client.upload(rpath, local_path, timeout=self._timeout) 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 (TftpShared.TftpException, IOError) as ex: self._mh.demsg( 'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere()) return False