Exemple #1
0
class PYTFTPServer(object):
    def __init__(self, tftp_ip_addr, tftp_folder, tftp_log_level):
        self.tftp_ip_addr = tftp_ip_addr
        self.tftp_folder = tftp_folder
        self.tftp_server = TftpServer(self.tftp_folder)
        self.tftp_log_level = tftp_log_level

    def start_tftp_server(self):
        try:
            self.tftp_server.listen(self.tftp_ip_addr, 69)
        except KeyboardInterrupt:
            pass

    def stop_tftp_server(self):
        self.tftp_server.stop()  # Do not take any new transfers, but complete the existing ones.
Exemple #2
0
class Server(object):

    _server = None
    _ip = None
    _port = None
    _path = None

    def __init__(self, path='/var/local/hydratk'):

        self._server = TftpServer(tftproot=path)
        self._path = path

    def start(self, ip='127.0.0.1', port=69, timeout=10):

        self._server.listen(ip, port, timeout)
        self._ip = ip
        self._port = port

    def stop(self):

        self._server.stop()
Exemple #3
0
    def run_server(self):
        # Run server in separate process
        signal.signal(signal.SIGINT, lambda x, y: None)

        address = self.server_info['address']
        port = self.server_info.get('port', DEFAULT_PORT)
        self.path = self.server_info.setdefault('path', '/')

        server = TftpServer(self.path)

        logfile = self.server_info.get('logfile', None)
        if 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)

        # Port is only allocated after server is running, so start a thread
        # to retrieve
        threading.Thread(target=self.get_port, args=(server, )).start()
        server.listen(address, port)
Exemple #4
0
    def __init__(self, ip_address=None, port=0, verbose=False):
        super(InternalTftp, self).__init__()
        self.daemon = True

        self.tftp_dir = temp_dir()
        self.verbose = verbose

        self.server = TftpServer(tftproot=self.tftp_dir)
        self.ip_address = ip_address
        self.port = port
        self.start()

        # Get the port we actually hosted on
        if port == 0:
            deadline = datetime.now() + timedelta(seconds=10)
            while datetime.now() < deadline:
                try:
                    self.port = self.server.sock.getsockname()[1]
                    break
                except (AttributeError, socket.error):
                    pass
            else:
                # don't catch the error on our last attempt
                self.port = self.server.sock.getsockname()[1]
Exemple #5
0
    def __init__(self, ip_address=None, port=0, verbose=False):
        super(InternalTftp, self).__init__()
        self.daemon = True

        self.tftp_dir = temp_dir()
        self.verbose = verbose

        self.server = TftpServer(tftproot=self.tftp_dir)
        self.ip_address = ip_address
        self.port = port
        self.start()

        # Get the port we actually hosted on
        if port == 0:
            deadline = datetime.now() + timedelta(seconds=10)
            while datetime.now() < deadline:
                try:
                    self.port = self.server.sock.getsockname()[1]
                    break
                except (AttributeError, socket.error):
                    pass
            else:
                # don't catch the error on our last attempt
                self.port = self.server.sock.getsockname()[1]
Exemple #6
0
class InternalTftp(Thread):
    """Internally serves files using the `Trivial File Transfer Protocol \
<http://en.wikipedia.org/wiki/Trivial_File_Transfer_Protocol>`_.

    >>> # Typical instantiation ...
    >>> from cxmanage_api.tftp import InternalTftp
    >>> i_tftp = InternalTftp()
    >>> # Alternatively, you can specify an address or hostname ...
    >>> i_tftp = InternalTftp(ip_address='localhost')

    :param ip_address: Ip address for the Internal TFTP server to use.
    :type ip_address: string
    :param port: Port for the internal TFTP server.
    :type port: integer
    :param verbose: Flag to turn on additional messaging.
    :type verbose: boolean

    """
    _default = None

    @staticmethod
    def default():
        """ Return the default InternalTftp server """
        if InternalTftp._default == None:
            InternalTftp._default = InternalTftp()
        return InternalTftp._default

    def __init__(self, ip_address=None, port=0, verbose=False):
        super(InternalTftp, self).__init__()
        self.daemon = True

        self.tftp_dir = temp_dir()
        self.verbose = verbose

        self.server = TftpServer(tftproot=self.tftp_dir)
        self.ip_address = ip_address
        self.port = port
        self.start()

        # Get the port we actually hosted on
        if port == 0:
            deadline = datetime.now() + timedelta(seconds=10)
            while datetime.now() < deadline:
                try:
                    self.port = self.server.sock.getsockname()[1]
                    break
                except (AttributeError, socket.error):
                    pass
            else:
                # don't catch the error on our last attempt
                self.port = self.server.sock.getsockname()[1]

    def run(self):
        """ Run the server. Listens indefinitely. """
        if not self.verbose:
            setLogLevel(logging.CRITICAL)
        self.server.listen(listenport=self.port)

    def get_address(self, relative_host=None):
        """Returns the ipv4 address of this server.
        If a relative_host is specified, then we discover our address to them.

        >>> i_tftp.get_address(relative_host='10.10.14.150')
        'localhost'

        :param relative_host: Ip address to the relative host.
        :type relative_host: string

        :return: The ipv4 address of this InternalTftpServer.
        :rtype: string

        """
        if (self.ip_address != None):
            return self.ip_address
        elif (relative_host == None):
            return "localhost"
        else:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            sock.connect((relative_host, self.port))
            ipv4 = sock.getsockname()[0]
            sock.close()
            return ipv4

    def get_file(self, src, dest):
        """Download a file from the tftp server to local_path.

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

        :param src: Source file path on the tftp_server.
        :type src: string
        :param dest: Destination path (local machine) to copy the TFTP file to.
        :type dest: string

        """
        src = "%s/%s" % (self.tftp_dir, src)
        if (src != dest):
            try:
                # Ensure the file exists ...
                with open(src) as a_file:
                    a_file.close()
                shutil.copy(src, dest)

            except Exception:
                traceback.format_exc()
                raise

    def put_file(self, src, dest):
        """Upload a file from src to dest on the tftp server (path).

        >>> i_tftp.put_file(src='/local/file.txt', dest='remote_file_name.txt')

        :param src: Path to the local file to send to the TFTP server.
        :type src: string
        :param dest: Path to put the file to on the TFTP Server.
        :type dest: string

        """
        dest = "%s/%s" % (self.tftp_dir, dest)
        if (src != dest):
            try:
                # Ensure that the local file exists ...
                with open(src) as a_file:
                    a_file.close()
                shutil.copy(src, dest)
            except Exception:
                traceback.format_exc()
                raise
Exemple #7
0
    def __init__(self, path='/var/local/hydratk'):

        self._server = TftpServer(tftproot=path)
        self._path = path
Exemple #8
0
 def __init__(self, tftp_ip_addr, tftp_folder, tftp_log_level):
     self.tftp_ip_addr = tftp_ip_addr
     self.tftp_folder = tftp_folder
     self.tftp_server = TftpServer(self.tftp_folder)
     self.tftp_log_level = tftp_log_level
 def __init__(self, listen, handler=None):
     (ip, port) = listen
     self.ip = ip
     self.port = port
     TftpServer.__init__(self, tftproot='./')
Exemple #10
0
 def __init__(self, listen, handler=None):
     (ip, port) = listen
     self.ip = ip
     self.port = port
     TftpServer.__init__(self, tftproot='./')
Exemple #11
0
class InternalTftp(Thread):
    """Internally serves files using the `Trivial File Transfer Protocol \
<http://en.wikipedia.org/wiki/Trivial_File_Transfer_Protocol>`_.

    >>> # Typical instantiation ...
    >>> from cxmanage_api.tftp import InternalTftp
    >>> i_tftp = InternalTftp()
    >>> # Alternatively, you can specify an address or hostname ...
    >>> i_tftp = InternalTftp(ip_address='localhost')

    :param ip_address: Ip address for the Internal TFTP server to use.
    :type ip_address: string
    :param port: Port for the internal TFTP server.
    :type port: integer
    :param verbose: Flag to turn on additional messaging.
    :type verbose: boolean

    """
    _default = None

    @staticmethod
    def default():
        """ Return the default InternalTftp server """
        if InternalTftp._default == None:
            InternalTftp._default = InternalTftp()
        return InternalTftp._default

    def __init__(self, ip_address=None, port=0, verbose=False):
        super(InternalTftp, self).__init__()
        self.daemon = True

        self.tftp_dir = temp_dir()
        self.verbose = verbose

        self.server = TftpServer(tftproot=self.tftp_dir)
        self.ip_address = ip_address
        self.port = port
        self.start()

        # Get the port we actually hosted on
        if port == 0:
            deadline = datetime.now() + timedelta(seconds=10)
            while datetime.now() < deadline:
                try:
                    self.port = self.server.sock.getsockname()[1]
                    break
                except (AttributeError, socket.error):
                    pass
            else:
                # don't catch the error on our last attempt
                self.port = self.server.sock.getsockname()[1]

    def run(self):
        """ Run the server. Listens indefinitely. """
        if not self.verbose:
            setLogLevel(logging.CRITICAL)
        self.server.listen(listenport=self.port)

    def get_address(self, relative_host=None):
        """Returns the ipv4 address of this server.
        If a relative_host is specified, then we discover our address to them.

        >>> i_tftp.get_address(relative_host='10.10.14.150')
        'localhost'

        :param relative_host: Ip address to the relative host.
        :type relative_host: string

        :return: The ipv4 address of this InternalTftpServer.
        :rtype: string

        """
        if (self.ip_address != None):
            return self.ip_address
        elif (relative_host == None):
            return "localhost"
        else:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            sock.connect((relative_host, self.port))
            ipv4 = sock.getsockname()[0]
            sock.close()
            return ipv4

    def get_file(self, src, dest):
        """Download a file from the tftp server to local_path.

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

        :param src: Source file path on the tftp_server.
        :type src: string
        :param dest: Destination path (local machine) to copy the TFTP file to.
        :type dest: string

        """
        src = "%s/%s" % (self.tftp_dir, src)
        if (src != dest):
            try:
                # Ensure the file exists ...
                with open(src) as a_file:
                    a_file.close()
                shutil.copy(src, dest)

            except Exception:
                traceback.format_exc()
                raise

    def put_file(self, src, dest):
        """Upload a file from src to dest on the tftp server (path).

        >>> i_tftp.put_file(src='/local/file.txt', dest='remote_file_name.txt')

        :param src: Path to the local file to send to the TFTP server.
        :type src: string
        :param dest: Path to put the file to on the TFTP Server.
        :type dest: string

        """
        dest = "%s/%s" % (self.tftp_dir, dest)
        if (src != dest):
            try:
                # Ensure that the local file exists ...
                with open(src) as a_file:
                    a_file.close()
                shutil.copy(src, dest)
            except Exception:
                traceback.format_exc()
                raise