Пример #1
0
    def download(self, host, port, fname):
        output = DummyIO()
        client = TftpClient(host, port)

        self.env.write("Trying " + host + ":" + str(port) + " ... ")
        client.download(fname, output, timeout=5, packethook=self.pkt)
        return output.data
Пример #2
0
    def get_file(self, src, dest):
        """Download a file from the ExternalTftp Server.

        .. note::
            * TftpClient is not threadsafe, so we create a unique instance for
              each transfer.

        >>> e_tftp.get_file(src='remote_file_i_want.txt', dest='/local/path')

        :param src: The path to the file on the Tftp server.
        :type src: string
        :param dest: The local destination to copy the file to.
        :type dest: string

        :raises TftpException: If the file does not exist or cannot be obtained
                               from the TFTP server.
        :raises TftpException: If a TypeError is received from tftpy.

        """
        try:
            client = TftpClient(self.ip_address, self.port)
            client.download(output=dest, filename=src)
        except TftpException:
            if (self.verbose):
                traceback.format_exc()
            raise
        except TypeError:
            if (self.verbose):
                traceback.format_exc()
            raise TftpException("Failed download file from TFTP server")
Пример #3
0
    def get_file(self, src, dest):
        """Download a file from the ExternalTftp Server.

        .. note::
            * TftpClient is not threadsafe, so we create a unique instance for
              each transfer.

        >>> e_tftp.get_file(src='remote_file_i_want.txt', dest='/local/path')

        :param src: The path to the file on the Tftp server.
        :type src: string
        :param dest: The local destination to copy the file to.
        :type dest: string

        :raises TftpException: If the file does not exist or cannot be obtained
                               from the TFTP server.
        :raises TftpException: If a TypeError is received from tftpy.

        """
        try:
            client = TftpClient(self.ip_address, self.port)
            client.download(output=dest, filename=src)
        except TftpException:
            if (self.verbose):
                traceback.format_exc()
            raise
        except TypeError:
            if (self.verbose):
                traceback.format_exc()
            raise TftpException("Failed download file from TFTP server")
Пример #4
0
    def download(self, host, port, fname):
        if config.get("fake_dl", optional=True, default=False):
            return str(hash(host + str(port) + fname))

        output = DummyIO()
        client = TftpClient(host, port)

        self.env.write("Trying " + host + ":" + str(port) + " ... ")
        client.download(fname, output, timeout=5, packethook=self.pkt)
        return output.data
Пример #5
0
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")
Пример #6
0
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
Пример #7
0
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