コード例 #1
0
    def __init__(self, sparkle):
        """Call parent constructors."""

        VirtManager.__init__(self)
        ModelManager.__init__(self, sparkle)
        UdevManager.__init__(self)
        NetworkManager.__init__(self)
コード例 #2
0
def main():
    config = Config()
    controller = Controller(config)
    net_man = NetworkManager(epochs=config.CNN_epochs,\
     child_batchsize=128, lr=config.CNN_lr, momentum=0.9, acc_beta=0.8)

    for i in range(config.max_no_of_sampled_networks):
        print('sampling ', i, 'th network')
        action = controller.get_action()
        print(action)
        sys.stdout.flush()
        while convertToString(action) in reward_dict:
            action = controller.get_action()

        acc, flops, params = net_man.get_peformance_statistics(action)

        reward_dict[convertToString(action)] = (acc, flops, params)
        completed_action_list.append(action)
        with open('completed_action_list.pickle', 'wb') as handle:
            pickle.dump(completed_action_list,
                        handle,
                        protocol=pickle.HIGHEST_PROTOCOL)
        with open('reward_dict.pickle', 'wb') as handle:
            pickle.dump(reward_dict, handle, protocol=pickle.HIGHEST_PROTOCOL)

        controller.train_step(reward_dict, completed_action_list)
        controller.save_model()
コード例 #3
0
ファイル: dgram_socket.py プロジェクト: heikipikker/ccsocket
 def __init__(self, channeltype, band):
     ''' Get encoder and pass it to NetworkManager '''
     self._channeltype = channeltype
     self._band = band
     encoder = MessageEncoderFactory.create(channeltype, band)
     self._encoder = encoder
     if not encoder:
         raise Error('Such encoder does not exist')
     self._netmanager = NetworkManager(encoder)        
     self._buffer = ('',  None)        
コード例 #4
0
ファイル: qkd_protocols.py プロジェクト: csdarling/AdvProject
    def setup_network_manager(self, k=None, edges=None):
        '''Set the protocol to run when run_one_step or run_n_steps is called.'''
        if k is None and edges is None:
            raise ValueError("Either k or edges must be specified.")

        # If k is not set then it defaults to the maximum node uid in edges.
        if k is None:
            k = max([max((a, b) for a, b in edges)])

        self.network_manager = NetworkManager(self.cchl, edges)
        self.reset()
コード例 #5
0
ファイル: main.py プロジェクト: CuriousLLC/QtTestMethods
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)

        # Create the name manager instance and move it to another thread.
        # This will cause all the slots to be run in that other thread
        # instead of our GUI thread.
        self.name_manager = NameManager()
        self.name_manager_thread = QThread()
        self.name_manager.moveToThread(self.name_manager_thread)
        self.name_manager_thread.start()

        # Create our network manager
        self.network_manager = NetworkManager()

        # When the name manager emits it's full name list, we want to
        # repopulate our list.
        self.name_manager.names_signal.connect(self.populate_list)

        # When the restore list button is clicked, let the name manager
        # know we need all the names in long term storage
        self.restore_list_button.clicked.connect(self.name_manager.get_all_names)

        self.add_name_signal.connect(self.name_manager.store_name)
        self.add_name_signal.connect(self.cache_name)
        self.submit_button.clicked.connect(self.say_hello)
        self.clear_list_button.clicked.connect(self.clear_list)
コード例 #6
0
 def __init__(self,networkmanager=None):
     if(networkmanager == None):
         self.nm = NetworkManager()
     else:
         self.nm = networkmanager
     self.dm = DockerManager(self.nm.selected_machine["compute_id"])
     pass
コード例 #7
0
    def __init__(self, networkManager=None, haveNat=False):

        if networkManager is None:
            self.nm = NetworkManager()
        else:
            self.nm = networkManager

        self.dm = DockerManager(self.nm.selected_machine["compute_id"])
        self.list_pcs = []
        self.nat = None
        self.flag_have_nat = haveNat
        self.switch_lan = None
        self.switch_services = None
        self.switch_out = None
        self.list_services = []
        self.net_config_dhcp = '''# DHCP
コード例 #8
0
def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=50))
    greet_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
    network_manager_pb2_grpc.add_NetworkManagerServicer_to_server(NetworkManager(), server)
    server.add_insecure_port("[::]:" + str(globals.port))
    logger.info("Server starting at port " + str(globals.port))
    server.start()
    server.wait_for_termination()
コード例 #9
0
def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=50))
    greet_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
    network_manager_pb2_grpc.add_NetworkManagerServicer_to_server(
        NetworkManager(), server)
    traversal_pb2_grpc.add_TraversalServicer_to_server(Traversal(), server)
    server.add_insecure_port("[::]:" + str(globals.port))
    logger.info("Server starting at port " + str(globals.port))
    storage_pb2_grpc.add_FileServerServicer_to_server(globals.storage_object,
                                                      server)
    server.add_insecure_port("[::]:" + str(globals.port))
    logger.info("Server starting at port " + str(globals.port))
    replication_pb2_grpc.add_FileserviceServicer_to_server(
        ReplicationService(), server)
    server.start()
    server.wait_for_termination()
コード例 #10
0
ファイル: dgram_socket.py プロジェクト: heikipikker/ccsocket
class DgramSocket(object):
#----------------------------------------------------------------------------------
    '''
        This class represents datagram socket. Handles sending and buffered recept-
        ion. Other calls are forwarded to NetworkManager.
    '''
#----------------------------------------------------------------------------------
    def __init__(self, channeltype, band):
        ''' Get encoder and pass it to NetworkManager '''
        self._channeltype = channeltype
        self._band = band
        encoder = MessageEncoderFactory.create(channeltype, band)
        self._encoder = encoder
        if not encoder:
            raise Error('Such encoder does not exist')
        self._netmanager = NetworkManager(encoder)        
        self._buffer = ('',  None)        
#----------------------------------------------------------------------------------
    def __del__(self):
        del self._netmanager
        del self._buffer
#----------------------------------------------------------------------------------
    def setblocking(self, value):
        ''' 
            Sets socket to blocking/non-blocking/timeout mode. Default is blocking 
            mode.
        '''
        if value not in [0, 1, 2]:
            raise Error('Illegal blocking argument: ' + str(value))	  
        self._netmanager.setblocking(value)
#----------------------------------------------------------------------------------
    def setactive(self, value):
        ''' Sets socket passive or active '''
        if value:
            value = 1
        self._netmanager.setactive(value)
#----------------------------------------------------------------------------------
    def bind(self, addr):
        ''' 
            Binds socket to given host and port. Fails if same port is already bou-
            nd or if privileges are insufficient. NFQueue loop is run in child pro-
            cces. addr is a tuple (host, port).    Localhost is denoted by empty 
            string (' ').
        '''
        if len(addr) < 2:
            raise Error('Invalid argument')
        try:
            if self._encoder.initpackets():
                self._encoder = MessageEncoderFactory.create(self._channeltype, 
                                                             self._band )
            self._netmanager.bind(addr)
        except gaierror,  e:
            raise Error('Given hostname or addres is not valid: ' + str(e))
コード例 #11
0
ファイル: qkd_protocols.py プロジェクト: csdarling/AdvProject
class QKDProtocol:

    def __init__(self, k=None, edges=None, check_bit_prob=0.2, protocol_id=0):
        self.cchl = components.ClassicalChannel()
        self.setup_network_manager(k, edges)
        self.check_bit_prob = check_bit_prob
        self.eavesdropping = False
        self.intercepted_edges = []
        self.computation_time = None
        self.memory_usage = None

    def reset(self):
        '''Reset the protocol to its configuration at timestep 0.'''
        self.timestep = 0
        self.num_iterations = 0
        self.num_generated_states = 0
        self.security = 0
        self.key_length = 0
        self.stored_data = {}
        self.cchl.reset()
        self.network_manager.reset()
        self.protocol_secure = True
        self.next_timestep()

    def setup_network_manager(self, k=None, edges=None):
        '''Set the protocol to run when run_one_step or run_n_steps is called.'''
        if k is None and edges is None:
            raise ValueError("Either k or edges must be specified.")

        # If k is not set then it defaults to the maximum node uid in edges.
        if k is None:
            k = max([max((a, b) for a, b in edges)])

        self.network_manager = NetworkManager(self.cchl, edges)
        self.reset()

    def add_eavesdropping(self, edges):
        '''Add eavesdropping to the specified edges.'''
        self.network_manager.intercept_edges(edges, self.cchl)
        self.eavesdropping = True
        self.intercepted_edges = edges

    def next_timestep(self):
        '''Store the data from this timestep and set up for the next timestep.'''
        self.cchl.next_timestep()
        self.network_manager.next_timestep()
        self.stored_data[self.num_iterations] = {
            "security": self.security,
            "key_length": self.key_length
        }
        self.timestep += 1

    def store_timestep_data(self):
        '''Store the data from this timestep.'''
        self.cchl.store_timestep_data()
        self.network_manager.store_timestep_data()
        self.stored_data[self.num_iterations] = {
            "security": self.security,
            "key_length": self.key_length
        }

    def get_stored_data_for_timestep(self, timestep):
        '''Retrieve all of the stored data for a given timestep.'''
        stored_data = {
            "protocol": copy.deepcopy(self.stored_data[timestep]),
            "cchl": self.cchl.get_stored_data_for_timestep(timestep),
            "parties": self.network_manager.get_party_stored_data_for_timestep(timestep),
            "qchls": self.network_manager.get_qchl_stored_data_for_timestep(timestep)
        }
        return stored_data

    def run_one_step(self, display_data=True):
        '''Run one iteration of the set protocol.'''
        if self.protocol_secure:
            # Run one iteration of the set protocol.
            protocol_secure = self.protocol()
            # If eavesdropping was detected in this run of the protocol, then
            # prevent any future attempts to run an iteration of the protocol.
            self.protocol_secure = protocol_secure
            # Optionally print the data to the terminal.
            if display_data:
                self.display_data()
            # Setup for the next timestep.
            if self.protocol_secure:
                self.next_timestep()
            else:
                self.store_timestep_data()
            # Update the security and the key length fields
            self.update_security()
            self.update_key_length()
            # Increment the iteration counter.
            self.num_iterations += 1

    def run_n_steps(self, n, display_bits=True):
        '''Run n iterations of the protocol.'''
        if self.protocol_secure:
            count = 0
            while self.protocol_secure and count < n:
                self.run_one_step(display_data=False)
                count += 1
            self.display_data(display_bits)

    def run(self, num_iterations=None, security=0.95, key_length=128):
        '''Run for the given number of iterations, or until the secret key reaches the required length.'''
        # If the number of iterations is explicitly specified, then run the
        # protocol for exactly this number of iterations.
        if num_iterations is not None:
            self.run_n_steps(num_iterations)
        # Otherwise, continue to run the protocol until the secret key reaches
        # the required length and enough bits have been used as check bits to
        # provide the required level of security.
        else:
            # Calculate the minimum number of check bits
            required_num_check_bits = self.required_num_check_bits(security)
            # Run the protocol until the required number of check bits and
            # key bits is reached.
            num_check_bits = self.get_shortest_check_bits()
            num_key_bits = self.get_shortest_key_length()
            while self.protocol_secure and (num_key_bits < key_length or
                                num_check_bits < required_num_check_bits):
                self.run_one_step(display_data=False)
                num_check_bits = self.get_shortest_check_bits()
                num_key_bits = self.get_shortest_key_length()

    def required_num_check_bits(self, security):
        '''Calculate the minimum number of check bits required for the given security level.'''
        return math.ceil(math.log(1 - security) / math.log(0.75))

    def get_shortest_key_length(self):
        '''Return the length of the shortest secret key in the network.'''
        # TODO Move this to NetworkManager
        parties = self.network_manager.get_parties()
        min_key_length = math.inf
        for uidA in parties:
            partyA = parties[uidA]
            secret_keys = partyA.secret_keys
            if not secret_keys:
                min_key_length = 0
                break
            secret_keys_by_uid = shared_fns.reorder_by_uid(secret_keys)
            for uidB in secret_keys_by_uid:
                key_length = len(list(secret_keys_by_uid[uidB]))
                if key_length < min_key_length:
                    min_key_length = key_length

        return min_key_length

    def get_shortest_check_bits(self):
        '''Return the length of the shortest check bits in the network.'''
        # TODO Move this to NetworkManager
        parties = self.network_manager.get_parties()
        min_check_bits = math.inf
        for uidA in parties:
            partyA = parties[uidA]
            check_bits = partyA.check_bits
            if not check_bits:
                min_check_bits = 0
                break
            check_bits_by_uid = shared_fns.reorder_by_uid(check_bits)
            for uidB in check_bits_by_uid:
                key_length = len(list(check_bits_by_uid[uidB]))
                if key_length < min_check_bits:
                    min_check_bits = key_length

        return min_check_bits

    def update_key_length(self):
        self.key_length = self.get_shortest_key_length()

    def update_security(self):
        # Given n matching check bits, calculate the least upper bound for the
        # probability that Eve has gotten away with eavesdropping.
        num_check_bits = self.get_shortest_check_bits()
        security = 0
        upper_bound = 1
        while upper_bound - security > 0.0001:
            candidate = security + (upper_bound - security) / 2
            n = self.required_num_check_bits(candidate)
            if n > num_check_bits:
                upper_bound = candidate
            elif n <= num_check_bits:
                security = candidate
        self.security = security

    def calculate_qubit_counts(self):
        '''
        Sum the qubit counts for all the parties in the network.

        Calculate how many qubits have been generated, transmitted and
        received in total across the entire network.

        :return: a tuple of the three qubit totals
        '''
        total_qstates_generated = 0
        total_qstates_transmitted = 0
        total_qstates_received = 0

        parties = self.network_manager.get_parties()
        for party_uid in parties:
            party = parties[party_uid]
            total_qstates_generated += party.total_qstates_generated
            total_qstates_transmitted += party.total_qstates_transmitted
            total_qstates_received += party.total_qstates_received

        return (total_qstates_generated,
                total_qstates_transmitted,
                total_qstates_received)

    def display_data(self, display_bits=True):
        '''Print the protocol data to the terminal.'''
        parties = self.network_manager.get_parties()
        qubit_counts = self.calculate_qubit_counts()

        print("Protocol iterations: {}".format(self.num_iterations))
        print("Generated qubits:    {}".format(qubit_counts[0]))
        print("Transmitted qubits:  {}".format(qubit_counts[1]))
        print("Received qubits:     {}".format(qubit_counts[2]))

        min_key_length = math.inf
        for uidA in parties:
            partyA = parties[uidA]
            secret_keys = partyA.secret_keys
            if not secret_keys:
                min_key_length = 0
                break
            secret_keys_by_uid = shared_fns.reorder_by_uid(secret_keys)
            for uidB in secret_keys_by_uid:
                key_length = len(list(secret_keys_by_uid[uidB]))
                if key_length < min_key_length:
                    min_key_length = key_length

        print("Secret key length:   {}".format(min_key_length))

        if not display_bits:
            return

        # Display the tx/rx bits & bases for each party.
        for uidA in parties:
            partyA = parties[uidA]
            # Display the tx bits & bases, if they exist.
            if partyA.tx_bits:
                print("\nParty {} (tx)".format(partyA.name))
                tx_bits = shared_fns.reorder_by_uid(partyA.tx_bits)
                tx_bases = shared_fns.reorder_by_uid(partyA.tx_bases)
                tx_bits_str = shared_fns.convert_dod_to_dos(tx_bits)
                tx_bases_chars = shared_fns.represent_bases_by_chars(tx_bases)
                tx_bases_str = shared_fns.convert_dod_to_dos(tx_bases_chars)

                for uidB in tx_bits:
                    partyB = parties[uidB]
                    partyB_tx_bits_str = tx_bits_str[uidB]
                    partyB_tx_bases_str = tx_bases_str[uidB]

                    print("    {} -> {}:  {}".format(partyA.name,
                                                     partyB.name,
                                                     partyB_tx_bits_str))

                    print("             {}".format(partyB_tx_bases_str))

            # Display the rx bits & bases, if they exist.
            if partyA.rx_bits:
                print("\nParty {} (rx)".format(partyA.name))
                rx_bits = shared_fns.reorder_by_uid(partyA.rx_bits)
                rx_bases = shared_fns.reorder_by_uid(partyA.rx_bases)
                rx_bits_str = shared_fns.convert_dod_to_dos(rx_bits)
                rx_bases_chars = shared_fns.represent_bases_by_chars(rx_bases)
                rx_bases_str = shared_fns.convert_dod_to_dos(rx_bases_chars)

                for uidB in rx_bits:
                    partyB = parties[uidB]
                    partyB_rx_bits_str = rx_bits_str[uidB]
                    partyB_rx_bases_str = rx_bases_str[uidB]

                    print("    {} -> {}:  {}".format(partyB.name,
                                                     partyA.name,
                                                     partyB_rx_bits_str))

                    print("             {}".format(partyB_rx_bases_str))

        # Display the sifted keys.
        print("\n")
        for uidA in parties:
            partyA = parties[uidA]
            sifted_keys = partyA.sifted_keys
            sifted_keys_by_uid = shared_fns.reorder_by_uid(sifted_keys)
            sifted_key_strs = shared_fns.convert_dod_to_dos(sifted_keys_by_uid)
            for uidB in sifted_keys_by_uid:
                partyB = parties[uidB]
                print("{} <-> {} key: {}".format(partyA.name,
                                                 partyB.name,
                                                 sifted_key_strs[uidB]))

        # Display the check bits.
        first_line = True
        for uidA in parties:
            partyA = parties[uidA]
            check_bits = partyA.check_bits
            check_bits_by_uid = shared_fns.reorder_by_uid(check_bits)
            check_bits_strs = shared_fns.convert_dod_to_dos(check_bits_by_uid)
            for uidB in check_bits_by_uid:
                check_bits_exist = True
                partyB = parties[uidB]
                if first_line:
                    print()
                    first_line = False
                print("{} <-> {} CBs: {}".format(partyA.name,
                                                 partyB.name,
                                                 check_bits_strs[uidB]))

        # Display the secret keys.
        first_line = True
        for uidA in parties:
            partyA = parties[uidA]
            secret_keys = partyA.secret_keys
            secret_keys_by_uid = shared_fns.reorder_by_uid(secret_keys)
            secret_key_strs = shared_fns.convert_dod_to_dos(secret_keys_by_uid)
            for uidB in secret_keys_by_uid:
                partyB = parties[uidB]
                if first_line:
                    print()
                    first_line = False
                print("{} <-> {} key: {}".format(partyA.name,
                                                 partyB.name,
                                                 secret_key_strs[uidB]))
コード例 #12
0
 def make_manager(self, host, port):
     dp_service = DebugPing()
     nwm = NetworkManager(host=host, port=port)
     nwm.add_service(dp_service)
     return nwm, dp_service
class TestNetworkManager(TestCase):
    nm = NetworkManager(0, {"compute_id": "vm", "name": "GNS3 VM (GNS3 VM)"})

    def test_get_all_templates(self):
        # expected= [
        #     {
        #         "adapter_type": "e1000",
        #         "adapters": 1,
        #         "bios_image": "",
        #         "boot_priority": "c",
        #         "builtin": False,
        #         "category": "guest",
        #         "cdrom_image": "",
        #         "compute_id": "vm",
        #         "console_auto_start": False,
        #         "console_type": "vnc",
        #         "cpu_throttling": 0,
        #         "cpus": 1,
        #         "custom_adapters": [],
        #         "default_name_format": "{name}-{0}",
        #         "first_port_name": "",
        #         "hda_disk_image": "linux-tinycore-linux-6.4-firefox-33.1.1-2.img",
        #         "hda_disk_interface": "ide",
        #         "hdb_disk_image": "",
        #         "hdb_disk_interface": "ide",
        #         "hdc_disk_image": "",
        #         "hdc_disk_interface": "ide",
        #         "hdd_disk_image": "",
        #         "hdd_disk_interface": "ide",
        #         "initrd": "",
        #         "kernel_command_line": "",
        #         "kernel_image": "",
        #         "legacy_networking": False,
        #         "linked_clone": True,
        #         "mac_address": "",
        #         "name": "Firefox 31.1.1~2",
        #         "on_close": "power_off",
        #         "options": "-vga std -usbdevice tablet",
        #         "platform": "i386",
        #         "port_name_format": "Ethernet{0}",
        #         "port_segment_size": 0,
        #         "process_priority": "normal",
        #         "qemu_path": "/usr/bin/qemu-system-i386",
        #         "ram": 256,
        #         "symbol": "firefox.svg",
        #         "template_id": "3279fa58-eef8-48ea-a6b9-a20bf1240d12",
        #         "template_type": "qemu",
        #         "usage": ""
        #     },
        #     {
        #         "adapter_type": "Intel PRO/1000 MT Desktop (82540EM)",
        #         "adapters": 1,
        #         "builtin": False,
        #         "category": "guest",
        #         "compute_id": "local",
        #         "console_auto_start": False,
        #         "console_type": "none",
        #         "custom_adapters": [],
        #         "default_name_format": "{name}-{0}",
        #         "first_port_name": "",
        #         "headless": False,
        #         "linked_clone": False,
        #         "name": "GNS3 VM",
        #         "on_close": "power_off",
        #         "port_name_format": "Ethernet{0}",
        #         "port_segment_size": 0,
        #         "ram": 2048,
        #         "symbol": ":/symbols/vbox_guest.svg",
        #         "template_id": "9893f914-515f-4baf-bdf8-e5dd3ac4e208",
        #         "template_type": "virtualbox",
        #         "usage": "",
        #         "use_any_adapter": False,
        #         "vmname": "GNS3 VM"
        #     },
        #     {
        #         "adapters": 1,
        #         "builtin": False,
        #         "category": "guest",
        #         "compute_id": "vm",
        #         "console_auto_start": False,
        #         "console_http_path": "/",
        #         "console_http_port": 80,
        #         "console_resolution": "1024x768",
        #         "console_type": "telnet",
        #         "custom_adapters": [],
        #         "default_name_format": "{name}-{0}",
        #         "environment": "",
        #         "extra_hosts": "",
        #         "extra_volumes": [],
        #         "image": "gns3/ubuntu:xenial",
        #         "name": "Ubuntu Docker Guest",
        #         "start_command": "",
        #         "symbol": "linux_guest.svg",
        #         "template_id": "d15fb3d1-0ba1-43d9-a725-e286bb6c1e56",
        #         "template_type": "docker",
        #         "usage": ""
        #     },
        #     {
        #         "adapter_type": "e1000",
        #         "adapters": 4,
        #         "bios_image": "",
        #         "boot_priority": "c",
        #         "builtin": False,
        #         "category": "router",
        #         "cdrom_image": "",
        #         "compute_id": "vm",
        #         "console_auto_start": False,
        #         "console_type": "telnet",
        #         "cpu_throttling": 0,
        #         "cpus": 1,
        #         "custom_adapters": [],
        #         "default_name_format": "{name}-{0}",
        #         "first_port_name": "",
        #         "hda_disk_image": "bird-tinycore64-1.5.0.img",
        #         "hda_disk_interface": "ide",
        #         "hdb_disk_image": "",
        #         "hdb_disk_interface": "ide",
        #         "hdc_disk_image": "",
        #         "hdc_disk_interface": "ide",
        #         "hdd_disk_image": "",
        #         "hdd_disk_interface": "ide",
        #         "initrd": "",
        #         "kernel_command_line": "",
        #         "kernel_image": "",
        #         "legacy_networking": False,
        #         "linked_clone": True,
        #         "mac_address": "",
        #         "name": "BIRD 1.5.0",
        #         "on_close": "power_off",
        #         "options": "",
        #         "platform": "i386",
        #         "port_name_format": "Ethernet{0}",
        #         "port_segment_size": 0,
        #         "process_priority": "normal",
        #         "qemu_path": "/usr/bin/qemu-system-x86_64",
        #         "ram": 128,
        #         "symbol": ":/symbols/classic/router.svg",
        #         "template_id": "6f38fbb5-ae7d-43b6-bd8f-8af1a06dd3cd",
        #         "template_type": "qemu",
        #         "usage": "Configure interfaces in /opt/bootlocal.sh, BIRD configuration is done in /usr/local/etc/bird"
        #     },
        #     {
        #         "adapters": 1,
        #         "builtin": False,
        #         "category": "guest",
        #         "compute_id": "vm",
        #         "console_auto_start": False,
        #         "console_http_path": "/",
        #         "console_http_port": 80,
        #         "console_resolution": "1024x768",
        #         "console_type": "telnet",
        #         "custom_adapters": [],
        #         "default_name_format": "{name}-{0}",
        #         "environment": "",
        #         "extra_hosts": "",
        #         "extra_volumes": [],
        #         "image": "alpine",
        #         "name": "Alpine Linux",
        #         "start_command": "",
        #         "symbol": "linux_guest.svg",
        #         "template_id": "0cf3b8a5-8a9c-4ba7-a900-e44ec8b13695",
        #         "template_type": "docker",
        #         "usage": ""
        #     },
        #     {
        #         "adapters": 1,
        #         "builtin": False,
        #         "category": "guest",
        #         "compute_id": "vm",
        #         "console_auto_start": False,
        #         "console_http_path": "/",
        #         "console_http_port": 80,
        #         "console_resolution": "1024x768",
        #         "console_type": "telnet",
        #         "custom_adapters": [],
        #         "default_name_format": "{name}-{0}",
        #         "environment": "",
        #         "extra_hosts": "",
        #         "extra_volumes": [],
        #         "image": "thomasbeckers/alpine-python3",
        #         "name": "thomasbeckers-alpine-python3",
        #         "start_command": "",
        #         "symbol": ":/symbols/docker_guest.svg",
        #         "template_id": "0fcf4286-b924-440a-88bd-f973871e4b9b",
        #         "template_type": "docker",
        #         "usage": ""
        #     },
        #     {
        #         "builtin": True,
        #         "category": "guest",
        #         "compute_id": None,
        #         "default_name_format": "Cloud{0}",
        #         "name": "Cloud",
        #         "symbol": ":/symbols/cloud.svg",
        #         "template_id": "39e257dc-8412-3174-b6b3-0ee3ed6a43e9",
        #         "template_type": "cloud"
        #     },
        #     {
        #         "builtin": True,
        #         "category": "guest",
        #         "compute_id": None,
        #         "default_name_format": "NAT{0}",
        #         "name": "NAT",
        #         "symbol": ":/symbols/cloud.svg",
        #         "template_id": "df8f4ea9-33b7-3e96-86a2-c39bc9bb649c",
        #         "template_type": "nat"
        #     },
        #     {
        #         "builtin": True,
        #         "category": "guest",
        #         "compute_id": None,
        #         "default_name_format": "PC{0}",
        #         "name": "VPCS",
        #         "properties": {
        #             "base_script_file": "vpcs_base_config.txt"
        #         },
        #         "symbol": ":/symbols/vpcs_guest.svg",
        #         "template_id": "19021f99-e36f-394d-b4a1-8aaa902ab9cc",
        #         "template_type": "vpcs"
        #     },
        #     {
        #         "builtin": True,
        #         "category": "switch",
        #         "compute_id": None,
        #         "console_type": "none",
        #         "default_name_format": "Switch{0}",
        #         "name": "Ethernet switch",
        #         "symbol": ":/symbols/ethernet_switch.svg",
        #         "template_id": "1966b864-93e7-32d5-965f-001384eec461",
        #         "template_type": "ethernet_switch"
        #     },
        #     {
        #         "builtin": True,
        #         "category": "switch",
        #         "compute_id": None,
        #         "default_name_format": "Hub{0}",
        #         "name": "Ethernet hub",
        #         "symbol": ":/symbols/hub.svg",
        #         "template_id": "b4503ea9-d6b6-3695-9fe4-1db3b39290b0",
        #         "template_type": "ethernet_hub"
        #     },
        #     {
        #         "builtin": True,
        #         "category": "switch",
        #         "compute_id": None,
        #         "default_name_format": "FRSW{0}",
        #         "name": "Frame Relay switch",
        #         "symbol": ":/symbols/frame_relay_switch.svg",
        #         "template_id": "dd0f6f3a-ba58-3249-81cb-a1dd88407a47",
        #         "template_type": "frame_relay_switch"
        #     },
        #     {
        #         "builtin": True,
        #         "category": "switch",
        #         "compute_id": None,
        #         "default_name_format": "ATMSW{0}",
        #         "name": "ATM switch",
        #         "symbol": ":/symbols/atm_switch.svg",
        #         "template_id": "aaa764e2-b383-300f-8a0e-3493bbfdb7d2",
        #         "template_type": "atm_switch"
        #     }
        # ]
        self.assertTrue(self.nm.get_all_templates() is not [])

    def test_get_all_gns3vm(self):
        # expected =[
        #     {
        #         "compute_id": "vmware",
        #         "name": "VMware Fusion (recommended)"
        #     },
        #     {
        #
        #         "compute_id": "virtualbox",
        #         "name": "VirtualBox"
        #     },
        #     {
        #         "compute_id": "remote",
        #         "name": "Remote"
        #     }
        # ]
        self.assertTrue(self.nm.get_all_gns3vm() is not [])

    def test_get_all_machines(self):
        # expected = [
        #     {
        #         "compute_id": "local",
        #         "name": "MacBook-Pro-de-Maxime-9.local"
        #     },
        #     {
        #         "compute_id": "vm",
        #         "name": "GNS3 VM (GNS3 VM)"
        #     }
        # ]
        self.assertTrue(self.nm.get_all_machines() is not [])

    def test_get_all_drawings(self):
        # expected = [
        #     {
        #         "drawing_id": "63aa2322-577a-45b2-8e79-074da5184899",
        #         "locked": False,
        #         "project_id": "8cf37f7e-76a1-418c-9317-82e8586a1560",
        #         "rotation": 0,
        #         "svg": "<svg></svg>",
        #         "x": 0,
        #         "y": 0,
        #         "z": 2
        #     },
        #     {
        #         "drawing_id": "1f40e801-68e4-4ba0-87bd-458374ee8768",
        #         "locked": False,
        #         "project_id": "8cf37f7e-76a1-418c-9317-82e8586a1560",
        #         "rotation": 0,
        #         "svg": "<svg height=\"374\" width=\"528\"><rect fill=\"#ffffff\" fill-opacity=\"1.0\" height=\"374\" stroke=\"#000000\" stroke-width=\"2\" width=\"528\" /></svg>",
        #         "x": -465,
        #         "y": -360,
        #         "z": 1
        #     },
        #     {
        #         "drawing_id": "1a65ffb8-7283-466f-a8e1-8dc917eb8660",
        #         "locked": False,
        #         "project_id": "8cf37f7e-76a1-418c-9317-82e8586a1560",
        #         "rotation": 0,
        #         "svg": "<svg></svg>",
        #         "x": 0,
        #         "y": 0,
        #         "z": 2
        #     },
        #     {
        #         "drawing_id": "1d0bf1ff-5d16-406f-83ac-58a4603f5438",
        #         "locked": False,
        #         "project_id": "8cf37f7e-76a1-418c-9317-82e8586a1560",
        #         "rotation": 0,
        #         "svg": "<svg></svg>",
        #         "x": 0,
        #         "y": 0,
        #         "z": 2
        #     }
        # ]
        self.assertTrue(self.nm.get_all_drawings() is not [])

    def test_get_all_links(self):
        # expected = [
        #     {
        #         "capture_compute_id": None,
        #         "capture_file_name": None,
        #         "capture_file_path": None,
        #         "capturing": False,
        #         "filters": {},
        #         "link_id": "87321383-2e39-452f-b30a-dd71f46ca4c3",
        #         "link_type": "ethernet",
        #         "nodes": [],
        #         "project_id": "8cf37f7e-76a1-418c-9317-82e8586a1560",
        #         "suspend": False
        #     },
        #     {
        #         "capture_compute_id": None,
        #         "capture_file_name": None,
        #         "capture_file_path": None,
        #         "capturing": False,
        #         "filters": {},
        #         "link_id": "775aa0ed-911c-4e8e-9ff3-0e9bf55c37e1",
        #         "link_type": "ethernet",
        #         "nodes": [],
        #         "project_id": "8cf37f7e-76a1-418c-9317-82e8586a1560",
        #         "suspend": False
        #     },
        #     {
        #         "capture_compute_id": None,
        #         "capture_file_name": None,
        #         "capture_file_path": None,
        #         "capturing": False,
        #         "filters": {},
        #         "link_id": "2f9101dd-bdac-4ff2-bc90-e05ac07ced3b",
        #         "link_type": "ethernet",
        #         "nodes": [],
        #         "project_id": "8cf37f7e-76a1-418c-9317-82e8586a1560",
        #         "suspend": False
        #     },
        #     {
        #         "capture_compute_id": None,
        #         "capture_file_name": None,
        #         "capture_file_path": None,
        #         "capturing": False,
        #         "filters": {},
        #         "link_id": "b6bff2a2-1638-4384-a1e2-ffa9bf24ce72",
        #         "link_type": "ethernet",
        #         "nodes": [
        #             {
        #                 "adapter_number": 0,
        #                 "label": {
        #                     "rotation": 0,
        #                     "style": "font-family: TypeWriter;font-size: 10.0;font-weight: bold;fill: #000000;fill-opacity: 1.0;",
        #                     "text": "e1",
        #                     "x": 71,
        #                     "y": -1
        #                 },
        #                 "node_id": "27515250-dbac-422e-9e11-1eefaf7ae76b",
        #                 "port_number": 1
        #             },
        #             {
        #                 "adapter_number": 0,
        #                 "label": {
        #                     "rotation": 0,
        #                     "style": "font-family: TypeWriter;font-size: 10.0;font-weight: bold;fill: #000000;fill-opacity: 1.0;",
        #                     "text": "e0",
        #                     "x": -3,
        #                     "y": 46
        #                 },
        #                 "node_id": "72e118c6-6799-4291-8fed-41d8c75fc522",
        #                 "port_number": 0
        #             }
        #         ],
        #         "project_id": "8cf37f7e-76a1-418c-9317-82e8586a1560",
        #         "suspend": False
        #     },
        #     {
        #         "capture_compute_id": None,
        #         "capture_file_name": None,
        #         "capture_file_path": None,
        #         "capturing": False,
        #         "filters": {},
        #         "link_id": "14aa31f2-e44d-4b59-94f4-9215565d4b1b",
        #         "link_type": "ethernet",
        #         "nodes": [
        #             {
        #                 "adapter_number": 0,
        #                 "label": {
        #                     "rotation": 0,
        #                     "style": "font-family: TypeWriter;font-size: 10.0;font-weight: bold;fill: #000000;fill-opacity: 1.0;",
        #                     "text": "e0",
        #                     "x": 75,
        #                     "y": 21
        #                 },
        #                 "node_id": "27515250-dbac-422e-9e11-1eefaf7ae76b",
        #                 "port_number": 0
        #             },
        #             {
        #                 "adapter_number": 0,
        #                 "label": {
        #                     "rotation": 0,
        #                     "style": "font-family: TypeWriter;font-size: 10.0;font-weight: bold;fill: #000000;fill-opacity: 1.0;",
        #                     "text": "e0",
        #                     "x": -7,
        #                     "y": 23
        #                 },
        #                 "node_id": "97e285e3-f752-4052-8a5a-6f2b4e2fb72d",
        #                 "port_number": 0
        #             }
        #         ],
        #         "project_id": "8cf37f7e-76a1-418c-9317-82e8586a1560",
        #         "suspend": False
        #     },
        #     {
        #         "capture_compute_id": None,
        #         "capture_file_name": None,
        #         "capture_file_path": None,
        #         "capturing": False,
        #         "filters": {},
        #         "link_id": "8a95382f-653f-4777-9b41-520a610ddbaf",
        #         "link_type": "ethernet",
        #         "nodes": [
        #             {
        #                 "adapter_number": 0,
        #                 "label": {
        #                     "rotation": 0,
        #                     "style": "font-family: TypeWriter;font-size: 10.0;font-weight: bold;fill: #000000;fill-opacity: 1.0;",
        #                     "text": "e2",
        #                     "x": 28,
        #                     "y": -23
        #                 },
        #                 "node_id": "27515250-dbac-422e-9e11-1eefaf7ae76b",
        #                 "port_number": 2
        #             },
        #             {
        #                 "adapter_number": 0,
        #                 "label": {
        #                     "rotation": 0,
        #                     "style": "font-family: TypeWriter;font-size: 10.0;font-weight: bold;fill: #000000;fill-opacity: 1.0;",
        #                     "text": "eth0",
        #                     "x": 39,
        #                     "y": 68
        #                 },
        #                 "node_id": "914d1c91-f727-4c95-a767-cb831b4fd264",
        #                 "port_number": 0
        #             }
        #         ],
        #         "project_id": "8cf37f7e-76a1-418c-9317-82e8586a1560",
        #         "suspend": False
        #     },
        #     {
        #         "capture_compute_id": None,
        #         "capture_file_name": None,
        #         "capture_file_path": None,
        #         "capturing": False,
        #         "filters": {},
        #         "link_id": "7d88732d-4c7c-455b-9f1a-d9d7a5774149",
        #         "link_type": "ethernet",
        #         "nodes": [],
        #         "project_id": "8cf37f7e-76a1-418c-9317-82e8586a1560",
        #         "suspend": False
        #     },
        #     {
        #         "capture_compute_id": None,
        #         "capture_file_name": None,
        #         "capture_file_path": None,
        #         "capturing": False,
        #         "filters": {},
        #         "link_id": "67c8e9b7-a8e5-4bce-9291-8fe491cf3a39",
        #         "link_type": "ethernet",
        #         "nodes": [],
        #         "project_id": "8cf37f7e-76a1-418c-9317-82e8586a1560",
        #         "suspend": False
        #     }
        # ]
        self.assertTrue(self.nm.get_all_links() is not [])

    def test_get_all_nodes(self):
        # expected =[
        #     {
        #         "name": "AlpineLinux-1",
        #         "node_id": "914d1c91-f727-4c95-a767-cb831b4fd264"
        #     },
        #     {
        #         "name": "thomasbeckers-alpine-python3-1",
        #         "node_id": "fac28a86-2be5-4219-832c-a06837389ff7"
        #     },
        #     {
        #         "name": "PC1",
        #         "node_id": "72e118c6-6799-4291-8fed-41d8c75fc522"
        #     },
        #     {
        #         "name": "PC2",
        #         "node_id": "97e285e3-f752-4052-8a5a-6f2b4e2fb72d"
        #     },
        #     {
        #         "name": "Switch1",
        #         "node_id": "27515250-dbac-422e-9e11-1eefaf7ae76b"
        #     }
        # ]
        self.assertTrue(self.nm.get_all_nodes() is not [])

    def test_get_all_project(self):
        # expected =[
        #     {
        #         "auto_close": True,
        #         "auto_open": False,
        #         "auto_start": False,
        #         "drawing_grid_size": 25,
        #         "filename": "proto1.gns3",
        #         "grid_size": 75,
        #         "name": "proto1",
        #         "path": "/Users/maximebeugoms/GNS3/projects/proto1",
        #         "project_id": "8cf37f7e-76a1-418c-9317-82e8586a1560",
        #         "scene_height": 1000,
        #         "scene_width": 2000,
        #         "show_grid": False,
        #         "show_interface_labels": True,
        #         "show_layers": False,
        #         "snap_to_grid": True,
        #         "status": "opened",
        #         "supplier": None,
        #         "variables": None,
        #         "zoom": 35
        #     }
        # ]
        self.assertTrue(self.nm.get_all_project() is not [])

    def test_get_all_snapshots(self):
        # expected =[
        #     {
        #         "created_at": 1584656065,
        #         "name": "snapshot_testing_nm",
        #         "project_id": "8cf37f7e-76a1-418c-9317-82e8586a1560",
        #         "snapshot_id": "0ab187e5-2f4b-41d1-9b6d-8f7ecc57c988"
        #     }
        # ]
        self.assertTrue(self.nm.get_all_snapshots() is not [])

    def test_post_template(self):
        machine_template = {
            "adapters": 1,
            "builtin": False,
            "category": "guest",
            "compute_id": "vm",
            "console_auto_start": False,
            "console_http_path": "/",
            "console_http_port": 80,
            "console_resolution": "1024x768",
            "console_type": "telnet",
            "custom_adapters": [],
            "default_name_format": "{name}-{0}",
            "environment": "",
            "extra_hosts": "",
            "extra_volumes": [],
            "image": "gns3/ubuntu:xenial",
            "name": "Ubuntu Docker Guest",
            "start_command": "",
            "symbol": "linux_guest.svg",
            "template_id": "d15fb3d1-0ba1-43d9-a725-e286bb6c1e56",
            "template_type": "docker",
            "usage": ""
        }
        # result_expected = {
        #     "command_line": None,
        #     "compute_id": "vm",
        #     "console": 5009,
        #     "console_auto_start": False,
        #     "console_host": "192.168.56.104",
        #     "console_type": "telnet",
        #     "custom_adapters": [],
        #     "first_port_name": None,
        #     "height": 59,
        #     "label": {
        #         "rotation": 0,
        #         "style": None,
        #         "text": "UbuntuDockerGuest-1",
        #         "x": None,
        #         "y": -40
        #     },
        #     "locked": False,
        #     "name": "UbuntuDockerGuest-1",
        #     "node_directory": "/opt/gns3/projects/8cf37f7e-76a1-418c-9317-82e8586a1560/project-files/docker/49cfbb85-a553-48cb-9193-c66c411339e8",
        #     "node_id": "49cfbb85-a553-48cb-9193-c66c411339e8",
        #     "node_type": "docker",
        #     "port_name_format": "Ethernet{0}",
        #     "port_segment_size": 0,
        #     "ports": [
        #         {
        #             "adapter_number": 0,
        #             "data_link_types": {
        #                 "Ethernet": "DLT_EN10MB"
        #             },
        #             "link_type": "ethernet",
        #             "name": "eth0",
        #             "port_number": 0,
        #             "short_name": "eth0"
        #         }
        #     ],
        #     "project_id": "8cf37f7e-76a1-418c-9317-82e8586a1560",
        #     "properties": {
        #         "adapters": 1,
        #         "aux": 5010,
        #         "console_http_path": "/",
        #         "console_http_port": 80,
        #         "console_resolution": "1024x768",
        #         "container_id": "4aa379c99a5a8cc64dcd6155cf511b394019794c3852deec0977537cba63980c",
        #         "environment": None,
        #         "extra_hosts": None,
        #         "extra_volumes": [],
        #         "image": "gns3/ubuntu:xenial",
        #         "start_command": None,
        #         "usage": ""
        #     },
        #     "status": "stopped",
        #     "symbol": "linux_guest.svg",
        #     "template_id": "d15fb3d1-0ba1-43d9-a725-e286bb6c1e56",
        #     "width": 65,
        #     "x": 200,
        #     "y": 300,
        #     "z": 1
        # }
        self.assertTrue(
            self.nm.post_template(machine_template, 300, 100) is not {})

    def test_create_template_by_name(self):
        self.assertEqual(
            'd15fb3d1-0ba1-43d9-a725-e286bb6c1e56',
            self.nm.create_template_by_name('Ubuntu Docker Guest', 300,
                                            200)['template_id'])

    def test_create_template_by_id(self):
        self.assertEqual(
            'd15fb3d1-0ba1-43d9-a725-e286bb6c1e56',
            self.nm.create_template_by_id(
                'd15fb3d1-0ba1-43d9-a725-e286bb6c1e56', 300,
                300)['template_id'])

    def test_get_one_machine_by_id(self):
        expected_machine = {"compute_id": "vm", "name": "GNS3 VM (GNS3 VM)"}
        self.assertEqual(
            expected_machine,
            self.nm.get_one_machine_by_id(expected_machine['compute_id']))

    def test_get_one_machine_by_name(self):
        expected_machine = {"compute_id": "vm", "name": "GNS3 VM (GNS3 VM)"}
        self.assertEqual(
            expected_machine,
            self.nm.get_one_machine_by_name(expected_machine['name']))

    def test_set_current_machine(self):
        expected_machine = {"compute_id": "vm", "name": "GNS3 VM (GNS3 VM)"}
        self.assertEqual(expected_machine, self.nm.selected_machine)

    # def test_post_drawing(self):
    #     self.fail()
    #
    # def test_get_drawing(self):
    #     self.fail()
    #
    # def test_put_drawing(self):
    #     self.fail()
    #
    # def test_delete_drawing(self):
    #     self.fail()
    #

    def test_link_method(self):
        # Test create link between 2 nodes
        self.nm.create_template_by_name('Firefox', 200, 200)
        self.nm.create_template_by_name('Alpine', 200, 300)
        node1 = self.nm.get_one_node_by_name('Firefox')
        node2 = self.nm.get_one_node_by_name('Alpine')

        result = self.nm.link_nodes(node1['node_id'], node2['node_id'])

        self.assertTrue(result is not {})

        list_link = self.nm.get_all_links()

        # Test to get one specific link
        result = self.nm.get_one_link(list_link[0]['link_id'])
        self.assertEqual(list_link[0], result)

        # Infos about link
        result = self.nm.get_link_node(node1['node_id'])
        self.assertTrue(result is not [])

        # Test the capture on a link
        # Starting
        # self.nm.start_node(node1['node_id'])
        # self.nm.start_node(node2['node_id'])
        # result = self.nm.start_capture_link(list_link[0]['link_id'])
        # self.assertEqual(201, result.status_code)
        # sleep(1)
        # # Stopping
        # result = self.nm.stop_capture_link(list_link[0]['link_id'])
        # self.assertEqual(201,result.status_code)
        # # Get the capturing file
        # result = self.nm.get_pcap_link(list_link[0]['link_id'])
        # self.assertEqual(200, result.status_code)
        #
        # self.nm.stop_node(node1['node_id'])
        # self.nm.stop_node(node2['node_id'])

        # Test to delete on specific link
        result = self.nm.delete_link(list_link[0]['link_id'])
        self.assertEqual(204, result.status_code)

        self.nm.delete_node(node1['node_id'])
        self.nm.delete_node(node2['node_id'])

    def test_node_method(self):
        list_nodes = self.nm.get_all_nodes()
        # Update node
        self.nm.put_node(list_nodes[0]['node_id'], {'x': 300, 'y': 300})
        # Get specific node
        result = self.nm.get_one_node_by_id(list_nodes[0]['node_id'])
        result = self.nm.get_one_machine_by_name(list_nodes[0]['name'])

        # Duplicate node
        self.nm.duplicate_node(list_nodes[0]['node_id'], {'x': 400, 'y': 300})

        # Starting node
        self.nm.start_node(list_nodes[0]['node_id'])
        # Stopping node
        self.nm.stop_node(list_nodes[0]['node_id'])
        # General manage
        self.nm.start_all_nodes()
        self.nm.stop_all_node()
        self.nm.reload_all_node()
        self.nm.stop_all_node()
        # File manager
        result = self.nm.add_file_to_node(list_nodes[0]['node_id'],
                                          "/tmp/test.txt", "Hello word!")
        self.assertEqual(201, result.status_code)

        # Delete specific node
        self.nm.delete_node(list_nodes[0]['node_id'])

    def test_method_snapshot(self):
        result = self.nm.post_snapshot({'name': 'snap_test'})

        self.assertEqual(201, result.status_code)
        result = result.json()
        list_snaps = self.nm.get_all_snapshots()
        snap_id = ''
        for snap in list_snaps:
            if snap['name'] == 'snap_test':
                snap_id = snap['snapshot_id']
        # print(list_snaps)
        # res = self.nm.restore_snapshot(snap_id)
        # self.assertEqual(201, res.status_code)

        res = self.nm.delete_snapshot(snap_id)
        self.assertEqual(204, res.status_code)
コード例 #14
0
ファイル: main.py プロジェクト: MelkMerle/Werewolves
# coding=utf-8
from network_manager import NetworkManager
import sys

cmd = sys.argv[1:]
assert len(cmd) ==2  #verifier qu'on a bien seulement 2 arguments
ip, port = cmd

# Lancement du network manager
manager = NetworkManager(ip, int(port))


#Envoi du nom
groupname = "Agar.ia"
manager.send('NME', len(groupname), groupname)


#boucle principale
while True:
    manager.update()
    if manager.game_over == 1:
        print("Bye bye.")
        break

コード例 #15
0
    with fiona.open(os.path.join(DATA_RAW, 'crystal_palace_to_mursley.shp'),
                    'r') as source:
        unprojected_line = next(iter(source))
        unprojected_point = unprojected_line['geometry']['coordinates'][0]

    for inter_site_distance in inter_site_distances:

        print('--working on {}'.format(inter_site_distance))

        transmitter, interfering_transmitters, cell_area, interfering_cell_areas = \
            produce_sites_and_cell_areas(unprojected_point, inter_site_distance)

        receivers = generate_receivers(cell_area, inter_site_distance,
                                       SIMULATION_PARAMETERS)

        MANAGER = NetworkManager(transmitter, interfering_transmitters,
                                 receivers, cell_area, SIMULATION_PARAMETERS)

        results = MANAGER.estimate_link_budget(
            # frequency, bandwidth, generation, mast_height,
            # environment,
            MODULATION_AND_CODING_LUT,
            SIMULATION_PARAMETERS)

        csv_writer(results, os.path.join(DATA_PROCESSED, 'test_results'),
                   'test_capacity_data_{}.csv'.format(inter_site_distance))

        geojson_receivers = convert_results_geojson(results)

        write_shapefile(geojson_receivers,
                        'receivers_{}.shp'.format(inter_site_distance))
        write_shapefile(transmitter,
コード例 #16
0
ファイル: main.py プロジェクト: aramayyes/NNComparison
from aiohttp import web
import socketio
import numpy as np
import base64
import imageio
from skimage.transform import resize

from network_manager import NetworkManager

# network
network_manager = NetworkManager(4000, 64, 0.0001)

# server
sio = socketio.AsyncServer(logger=True)
app = web.Application()
sio.attach(app)


async def index(_):
    return web.Response(text="Server is running...")


app.router.add_get('/', index)


# socket events
@sio.on('connect')
def connect(sid, environ):
    print("connected ", sid)

コード例 #17
0
ファイル: main.py プロジェクト: CuriousLLC/QtTestMethods
class MainWindow(QMainWindow, Ui_MainWindow):

    add_name_signal = Signal(unicode)

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)

        # Create the name manager instance and move it to another thread.
        # This will cause all the slots to be run in that other thread
        # instead of our GUI thread.
        self.name_manager = NameManager()
        self.name_manager_thread = QThread()
        self.name_manager.moveToThread(self.name_manager_thread)
        self.name_manager_thread.start()

        # Create our network manager
        self.network_manager = NetworkManager()

        # When the name manager emits it's full name list, we want to
        # repopulate our list.
        self.name_manager.names_signal.connect(self.populate_list)

        # When the restore list button is clicked, let the name manager
        # know we need all the names in long term storage
        self.restore_list_button.clicked.connect(self.name_manager.get_all_names)

        self.add_name_signal.connect(self.name_manager.store_name)
        self.add_name_signal.connect(self.cache_name)
        self.submit_button.clicked.connect(self.say_hello)
        self.clear_list_button.clicked.connect(self.clear_list)

    def clean_up(self):
        """
        You can't rely on __del__ properly closing down all your threads. So use
        a clean_up method that will be called manually.
        :return:
        """
        if hasattr(self, 'network_manager_thread'):
            self.network_manager.api.end_connection()
            self.network_manager.api.join()
            self.network_manager_thread.quit()

        self.name_manager_thread.quit()

    def start_api(self, ip, port):
        """
        Connect to an external API service which will send us names
        :param ip: IP address of server
        :param port: Port of service
        :return:
        """
        self.network_manager_thread = QThread()
        self.network_manager.moveToThread(self.network_manager_thread)
        self.network_manager.message_signal.connect(self.handle_message)
        self.network_manager_thread.start()

        self.network_manager.connect_signal.emit(ip, port)

    @Slot()
    def handle_message(self, message):
        """
        Handle incoming names from the API. We simply want to follow the
        established procedure to add a new name. So we just emit on that
        signal.
        :param message: String name
        :return:
        """
        self.add_name_signal.emit(message)

    @Slot()
    def say_hello(self):
        self.add_name_signal.emit(self.name_text.text())
        self.hello_label.setText(u"{} {}".format(GREETING, self.name_text.text()))
        self.name_text.setText('')

    @Slot()
    def cache_name(self, name):
        self.names_list.addItem(name)

    @Slot()
    def clear_list(self):
        self.names_list.clear()

    @Slot()
    def populate_list(self, names):
        """
        Clears and repopulates the list with the given list
        :param names: List of names
        :return:
        """
        self.clear_list()
        for name in names:
            self.names_list.addItem(name)
コード例 #18
0
 def __init__(self):
     print(colored.green("[*] Fetching active servers"))
     self.net_manager = NetworkManager()
     ip_list = self.net_manager.get_all_ip()
     self.ips = self.net_manager.filter_active_server(ip_list)
     print(colored.green("[+] Successfully extracted active servers."))
コード例 #19
0
class TopologyManager:
    """
    Class to manage the topology of any network we want on the gns3 server

    """
    def __init__(self, networkManager=None, haveNat=False):

        if networkManager is None:
            self.nm = NetworkManager()
        else:
            self.nm = networkManager

        self.dm = DockerManager(self.nm.selected_machine["compute_id"])
        self.list_pcs = []
        self.nat = None
        self.flag_have_nat = haveNat
        self.switch_lan = None
        self.switch_services = None
        self.switch_out = None
        self.list_services = []
        self.net_config_dhcp = '''# DHCP
                                  auto eth0
                                  iface eth0 inet dhcp
                               '''

    def set_net_config_dhcp(self, new_config):
        """
        This method set basic net config dhcp
        :param new_config: str

        """
        self.net_config_dhcp = new_config

    pass

    def create_n_node(self,
                      n: int,
                      template_name: str,
                      switch_selected: str = 'in_lan'):
        """
        This method create n pcs (vpcs, vm, docker) link it to one switch (lan_switch)
        :param n: number of pcs
        :param template_name:The name of the template pc
        :param switch_selected: the name of switch where we want create n vpcs
        :return: add to list of pc the n new pcs
        """

        self.check_switch_service()

        if switch_selected == 'in_lan':
            if self.switch_lan is None:
                self.switch_lan = self.nm.create_template_by_name(
                    "Ethernet switch", self.switch_services['x'] + 300,
                    self.switch_services['y'])
                self.nm.link_nodes(
                    self.switch_services['node_id'],
                    self.switch_lan['node_id'], [
                        0,
                        self.get_switch_port(self.switch_services),
                        self.get_switch_port(self.switch_lan)
                    ])
            # add n pc of template name
            for i in range(n):
                current_pc = self.nm.create_template_by_name(
                    template_name, self.switch_lan['x'] + 200,
                    self.switch_lan['y'] + (len(self.list_pcs)) * 100)
                self.nm.add_file_to_node(current_pc["node_id"],
                                         "/etc/network/interfaces",
                                         self.net_config_dhcp)
                self.nm.link_nodes(
                    self.switch_lan['node_id'], current_pc['node_id'],
                    [0, self.get_switch_port(self.switch_lan)], [0, 0])
                self.list_pcs.append(current_pc)

        elif switch_selected == 'in_service':
            for i in range(n):
                current_pc = self.nm.create_template_by_name(
                    template_name, self.switch_services['x'] +
                    (len(self.list_services)) * 100,
                    self.switch_services['y'] + 200)
                self.nm.add_file_to_node(current_pc["node_id"],
                                         "/etc/network/interfaces",
                                         self.net_config_dhcp)
                self.nm.link_nodes(
                    self.switch_services['node_id'], current_pc['node_id'],
                    [0, self.get_switch_port(self.switch_services)], [0, 0])
                self.list_services.append(current_pc)

        elif switch_selected == 'out':
            if self.switch_out is None:
                self.switch_out = self.nm.create_template_by_name(
                    "Ethernet switch", 130, 100)
            net_config = '''# Static config
                            auto eth0
                            iface eth0 inet static
                                address 192.168.122.30
                                netmask 255.255.255.0
                                gateway 192.168.122.1
                                up echo nameserver 8.8.8.8 > /etc/resolv.conf
            '''
            for i in range(n):
                current_pc = self.nm.create_template_by_name(
                    template_name, self.switch_out['x'],
                    self.switch_out['y'] + 200)
                self.nm.add_file_to_node(current_pc["node_id"],
                                         "/etc/network/interfaces", net_config)
                self.nm.link_nodes(
                    self.switch_out['node_id'], current_pc['node_id'],
                    [0, self.get_switch_port(self.switch_out)], [0, 0])
                self.list_pcs.append(current_pc)
        else:
            print(ColorOutput.ERROR_TAG + ": your position of switch flag (" +
                  switch_selected + ") isn't supported!")
            exit(1)
            pass

    def get_switch_port(self, switch):
        """
        Get the first empty port and add some if necessary ports to the specific switch
        :param switch: the specific switch
        :return: the number of the first empty port
        """
        list_ports = []
        for port in switch['properties']['ports_mapping']:
            list_ports.append(port['port_number'])
        last_port = list_ports[-1]

        list_links = self.nm.get_link_node(switch['node_id'])
        for link in list_links:
            for node in link['nodes']:
                if node['node_id'] == switch['node_id']:
                    list_ports.remove(node['port_number'])

        if len(list_ports) == 0:
            # must add port
            for i in range(last_port + 1, 2 * last_port):
                switch['properties']['ports_mapping'].append({
                    'name':
                    'Ethernet' + str(i),
                    'port_number':
                    i,
                    'type':
                    'access',
                    'vlan':
                    1
                })

            self.nm.put_node(switch['node_id'],
                             {'properties': switch['properties']})
            return last_port + 1
        else:
            return list_ports[0]

    def add_dns_adapter(self, node):
        """
        Add one adapter to the specified node
        :param node: the node where we want to add an adapter
        :return: 
        """
        current_adapter = node['properties']['adapters']
        node['properties']['adapters'] = current_adapter + 1
        res = self.nm.put_node(
            node['node_id'], {
                'properties': {
                    'adapters': node['properties']['adapters'],
                    'start_command': ''
                },
                'node_type': node['node_type'],
                'node_id': node['node_id'],
                'compute_id': node['compute_id']
            })
        return res.json()

    def clean(self):
        """
        This method delete all nodes in the project
        """
        list_nodes = self.nm.get_all_nodes()
        for node in list_nodes:
            self.nm.delete_node(node['node_id'])
        pass

    def create_DNS(self, personal_net_config_dns=None):
        """
        This method create a dns
        :param personal_net_config_dns: customize net config of dns
        :return: the dns node
        """
        self.check_switch_service()

        if personal_net_config_dns is None:
            personal_net_config_dns = """# Static config
                                            auto eth0
                                            iface eth0 inet static
                                                address 192.168.122.10
                                                netmask 255.255.255.0
                                                gateway 192.168.122.1
                                                up echo nameserver 8.8.8.8 > /etc/resolv.conf
                                            auto eth1
                                            iface eth1 inet static
                                                address 10.0.0.1
                                                netmask 255.255.255.0"""

        dns = self.nm.create_template_by_name("thomasbeckers/dns", 250, 100)
        dns = self.add_dns_adapter(dns)
        self.nm.add_file_to_node(dns['node_id'], "/etc/network/interfaces",
                                 personal_net_config_dns)

        # linking to switch service
        if self.flag_have_nat and self.nat is None:
            self.nat = self.create_NAT()
            self.nm.link_nodes(self.nat["node_id"], self.switch_out["node_id"],
                               [0, 0],
                               [0, self.get_switch_port(self.switch_out)])
        if self.switch_out is None:
            self.switch_out = self.nm.create_template_by_name(
                "Ethernet switch", dns['x'] - 300, dns['y'])

        self.nm.link_nodes(dns["node_id"], self.switch_out["node_id"], [0, 0],
                           [0, self.get_switch_port(self.switch_out)])
        self.nm.link_nodes(dns["node_id"], self.switch_services["node_id"],
                           [1, 0],
                           [0, self.get_switch_port(self.switch_services)])
        return dns

    # dns must be started
    def dns_config(self, dns):
        """
        Add some config to the specific dns
        :param dns: the specific dns

        """
        self.nm.start_node(dns["node_id"])
        time.sleep(2)
        self.dm.exec_to_docker(
            dns['properties']['container_id'],
            "iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE")
        self.dm.copy_to_docker("./config_files/dns/dnsmasq.conf",
                               dns["properties"]["container_id"], "/etc/")
        self.dm.copy_to_docker("./config_files/dns/hosts",
                               dns["properties"]["container_id"], "/etc/")
        self.dm.exec_to_docker(dns["properties"]["container_id"],
                               "service dnsmasq restart")
        pass

    def create_HTTP(self, personal_net_config_http=None):
        """
        This method create an HTTP server
        :param personal_net_config_http: custom net config http
        :return: http node
        """
        self.check_switch_service()

        if personal_net_config_http is None:
            personal_net_config_http = '''# Static config
                                            auto eth0
                                            iface eth0 inet static
                                                address 10.0.0.14
                                                netmask 255.255.255.0
                                                gateway 10.0.0.1
                                                up echo nameserver 8.8.8.8 > /etc/resolv.conf'''

        http = self.nm.create_template_by_name(
            "thomasbeckers/http",
            self.switch_services['x'] + (len(self.list_services)) * 100,
            self.switch_services['y'] + 200)
        self.nm.add_file_to_node(http["node_id"], "/etc/network/interfaces",
                                 personal_net_config_http)

        # linking to switch services
        self.nm.link_nodes(self.switch_services["node_id"], http['node_id'],
                           [0, self.get_switch_port(self.switch_services)],
                           [0, 0])
        self.list_services.append(http)
        return http

    def get_http_nodes(self):
        """

        :return: a list of all http server in the project
        """
        list_http = []
        for service in self.list_services:
            if 'http' in service['name']:
                list_http.append(service)

        return list_http

    def http_config(self, http):
        """
        Add some config to a specific http server
        :param http: the specific http server

        """
        self.nm.start_node(http['node_id'])
        self.dm.copy_to_docker("./config_files/http/database.php",
                               http["properties"]["container_id"],
                               '/var/www/html/')
        pass

    def create_FTP(self, personal_net_config_ftp=None):
        """
        This method create a ftp server
        :param personal_net_config_ftp: the custom net config ftp
        :return: The ftp node
        """
        self.check_switch_service()

        if personal_net_config_ftp is None:
            personal_net_config_ftp = '''# Static config
                                            auto eth0
                                            iface eth0 inet static
                                                address 10.0.0.15
                                                netmask 255.255.255.0
                                                gateway 10.0.0.1
                                                up echo nameserver 8.8.8.8 > /etc/resolv.conf'''

        ftp = self.nm.create_template_by_name(
            "thomasbeckers/ftp",
            self.switch_services['x'] + (len(self.list_services)) * 100,
            self.switch_services['y'] + 200)
        self.nm.add_file_to_node(ftp['node_id'], "/etc/network/interfaces",
                                 personal_net_config_ftp)

        # linking to switch services
        self.nm.link_nodes(self.switch_services['node_id'], ftp["node_id"],
                           [0, self.get_switch_port(self.switch_services)],
                           [0, 0])
        self.list_services.append(ftp)

        return ftp

    def get_ftp_nodes(self):
        """

        :return: a list of all ftp server in the project
        """
        list_ftp = []
        for service in self.list_services:
            if 'ftp' in service['name']:
                list_ftp.append(service)

        return list_ftp

    # node must be started
    def ftp_config(self, ftp):
        """
        Add some config to the ftp server
        :param ftp: the specific ftp server

        """
        self.nm.start_node(ftp["node_id"])
        time.sleep(2)
        self.dm.copy_to_docker("./config_files/ftp/vsftpd.conf",
                               ftp["properties"]["container_id"],
                               "/etc/vsftpd.conf")
        self.dm.copy_to_docker("./python_scripts/write_file.py",
                               ftp["properties"]["container_id"],
                               "/srv/ftp/write_file.py")
        self.dm.copy_to_docker("./config_files/ftp/files",
                               ftp["properties"]["container_id"], "/srv/ftp/")
        self.dm.exec_to_docker(ftp["properties"]["container_id"],
                               "chown root:root /etc/vsftpd.conf")
        self.dm.exec_to_docker(ftp["properties"]["container_id"],
                               "service vsftpd restart")
        # time.sleep(2)
        # self.nm.stop_node(ftp["node_id"])
        pass

    def set_net_config_dhcp_on(self, personal_net_config_dhcp):
        """
        This method set the basic net config dhcp

        """
        self.net_config_dhcp = personal_net_config_dhcp
        pass

    def create_NAT(self):
        """
        This method create a NAT
        """
        self.flag_have_nat = True
        if self.switch_out is None:
            self.switch_out = self.nm.create_template_by_name(
                "Ethernet switch", 130, 100)
        return self.nm.create_template_by_name("NAT", 0, 100)

    def create_MAIL(self, personal_net_config_mail=None):
        """
        This method create a mail server
        :param personal_net_config_mail: custom net config mail server
        :return: mail node
        """
        self.check_switch_service()

        if personal_net_config_mail is None:
            personal_net_config_mail = '''# Static config
                                            auto eth0
                                            iface eth0 inet static
                                                address 10.0.0.16
                                                netmask 255.255.255.0
                                                gateway 10.0.0.1
                                                up echo nameserver 8.8.8.8 > /etc/resolv.conf'''

        mail = self.nm.create_template_by_name(
            "thomasbeckers/mail",
            self.switch_services['x'] + (len(self.list_services)) * 100,
            self.switch_services['y'] + 200)
        self.nm.add_file_to_node(mail['node_id'], "/etc/network/interfaces",
                                 personal_net_config_mail)

        self.nm.link_nodes(self.switch_services['node_id'], mail["node_id"],
                           [0, self.get_switch_port(self.switch_services)],
                           [0, 0])
        self.list_services.append(mail)
        return mail

    def check_switch_service(self):
        """
        This method check if the switch service is already created otherwise create it

        """
        if self.switch_services is None:
            self.switch_services = self.nm.create_template_by_name(
                "Ethernet switch", 450, 100)
            # linking to switch_lan
            if self.switch_lan is not None:
                self.nm.link_nodes(
                    self.switch_services['node_id'],
                    self.switch_lan['node_id'],
                    [0, self.get_switch_port(self.switch_services)],
                    [0, self.get_switch_port(self.switch_lan)])
        pass

    def create_db(self, personal_net_config_db=None):
        """
        This method create a server database
        :param personal_net_config_db: custom personal net config for the db server
        :return: db node
        """
        self.check_switch_service()

        if personal_net_config_db is None:
            personal_net_config_db = '''# Static config
                                            auto eth0
                                            iface eth0 inet static
                                                address 10.0.0.17
                                                netmask 255.255.255.0
                                                gateway 10.0.0.1
                                                up echo nameserver 8.8.8.8 > /etc/resolv.conf'''

        db = self.nm.create_template_by_name(
            "thomasbeckers/db",
            self.switch_services['x'] + (len(self.list_services)) * 100,
            self.switch_services['y'] + 200)
        self.nm.add_file_to_node(db["node_id"], "/etc/network/interfaces",
                                 personal_net_config_db)

        # linking to switch services
        self.nm.link_nodes(self.switch_services["node_id"], db['node_id'],
                           [0, self.get_switch_port(self.switch_services)],
                           [0, 0])
        self.list_services.append(db)
        return db

    def get_db_nodes(self):
        """
        list all db servers in the project
        :return:
        """
        list_db = []
        for service in self.list_services:
            if 'db' in service['name']:
                list_db.append(service)

        return list_db

    # db must be started
    def db_config(self, db):
        """
        Add some config to the specific db server
        :param db: the specific db server
        """
        self.nm.start_node(db['node_id'])
        # wait mysql to start
        time.sleep(5)
        self.dm.copy_to_docker("./config_files/db/setup.sql",
                               db["properties"]["container_id"])
        self.dm.exec_to_docker(db["properties"]["container_id"],
                               "/bin/sh -c 'mysql -u root < setup.sql'")
        pass

    def get_pc_nodes(self, name):
        """
        This method allows to get a list of specific type of pcs.

        :param name: The name of the specific pcs
        :return: The list of the specific pcs
        """
        list_template = []
        for pc in self.list_pcs:
            if name in pc['name']:
                list_template.append(pc)

        return list_template
コード例 #20
0
class Seeker:
    '''
	Seeker class - consists of search and fetch operation from various servers in the subnet.
	Main intention of this class is to traverse the network and perform various operations in a distributed manner.
	Yet to add a way to traverse and index the whole network.
	'''
    def __init__(self):
        print(colored.green("[*] Fetching active servers"))
        self.net_manager = NetworkManager()
        ip_list = self.net_manager.get_all_ip()
        self.ips = self.net_manager.filter_active_server(ip_list)
        print(colored.green("[+] Successfully extracted active servers."))

    def process(self, operation, data):
        '''
		Receives argument from command line parser.
		:param operation - defines the type of operation to be performed. Can be search or fetch yet.
		:param data - defines resources required by the operation. handled by parser.
		'''
        if operation == 'search':
            self._search_net(tag=data["tag"],
                             name=data["name"],
                             hash_val=data["hash"])
        elif operation == 'fetch':
            self._fetch_resource(data['url'], data['filename'])
        elif operation == 'news':
            self._get_broadcasts()
        else:
            print(colored.red("[!] Operation not found!!"))

    def _search_net(self, tag=None, name=None, hash_val=None):
        '''
		Searches the subnet for files.
		:param tag - type: str, a tag for searching among text files with various hashtags.
		:param name - type: str, a name of file for searching, this parameter is least reliable
		:param hash_val - type: str, a hash for a specific file for search, return quickest result

		:return void

		'''
        # TODO:- find an efficient server search method, maybe an indexing server
        # TODO:- Switch to Async await Multithreading
        for ip in self.ips:
            r = requests.get(f"http://{ip}:5000/search",
                             params=(("search_tag", tag),
                                     ("search_name", name), ("search_hash",
                                                             hash_val)))
            print(ip, r.text)

    def _get_broadcasts(self):
        '''
		Gets broadcasts from all servers in the subnet.

		:return void
		'''
        for ip in self.ips:
            r = requests.get(f"http://{ip}:5000/newsFlash")
            print(colored.green(f"{ip} ==> {r.text}"))

    def _fetch_resource(self, url, filename):
        '''
		Fetches file from a certain server using hash value.

		:param url - type: str, url of the file to be downloaded.
		Usually of the form:- http://127.0.0.1:5000/fetch/27e82jl58ue29ol91kn11h96xb

		:param filename - type: str, file name to be used for downloaded file.

		Filename can also be full path for file to be saved.

		:return void
		'''
        r = requests.get(url)

        if r.status_code == 200:
            with open(filename, 'wb') as local_file:
                for chunk in r.iter_content(chunk_size=128):
                    local_file.write(chunk)
コード例 #21
0
ファイル: main.py プロジェクト: MelkMerle/Werewolves
# coding=utf-8
from network_manager import NetworkManager
import sys

cmd = sys.argv[1:]
assert len(cmd) == 2  #verifier qu'on a bien seulement 2 arguments
ip, port = cmd

# Lancement du network manager
manager = NetworkManager(ip, int(port))

#Envoi du nom
groupname = "Agar.ia"
manager.send('NME', len(groupname), groupname)

#boucle principale
while True:
    manager.update()
    if manager.game_over == 1:
        print("Bye bye.")
        break
コード例 #22
0
import sys
sys.path.append("../protos")
sys.path.append("..")
import signal
import threading

import services
from network_manager import NetworkManager

# This file is meant to serve as a way to run a network manager indefinitely

# Boot up and wait for a keyboard interrupt
if __name__ == "__main__":
    print('Starting Network Manager')
    nwm = NetworkManager(host="172.18.0.1", port=13173)
    nwm.add_service(services.DebugPing())
    nwm.start()

    def stop_server(signal, frame):
        print('\nStopping Network Manager')
        nwm.stop()
        sys.exit(0)

    signal.signal(signal.SIGINT, stop_server)
    print("Ctr-c to stop")
    forever = threading.Event()
    forever.wait()
コード例 #23
0
    # put ping for the check co
    for i in tqdm.tqdm(range(60)):
        time.sleep(0.1)
    network = None
    if args.start:
        time.sleep(1)
        input("Press Enter after choose the recent project to continue...")
        print("*"*10+" Launching the basic network topology "+"*"*10)
        network = SimpleTopology()

    if args.updater:
        print("*"*10+"Network manager"+"*"*10)
        net_manager = None
        if network == None:
            # Start a new topology
            net_manager = NetworkManager()
        else:
            net_manager = network.nm
            # Ready to modify the basic topology

    if args.analyser:
        print("analyser manager")
        # os.system("python3 analyser_manager.py")
    if args.Attacker:
        print("attacker manager")
        # os.system("python3 attacker_manager.py")

    exit_key = input("Press 'q' to exit.\n").lower()
    while exit_key != 'q':
        exit_key = input("You enter a wrong value: "+str(exit_key)+". Please try with 'q' or 'Q'.").lower()