Exemplo n.º 1
0
    def __init__(self, name, sports="", dports="", include="", loginfo=""):
        """
		Create new service object with string parameters

		sports -- source port specifications like "www/tcp dns/udp"
		dports -- destination port specifications
		include -- include rules for other services to be included/aliased
		loginfo -- reference line number for user error messages
		"""
        if name == "" or not Util.verify_name(name, servicename=True):
            raise PyromanException("service lacking a proper name: '%s' at %s" \
             % (name, loginfo))
        if Firewall.services.has_key(name):
            raise PyromanException(
                "Duplicate service specification: '%s' at %s" %
                (name, loginfo))
        if sports == "" and dports == "" and include == "" and (name != "ANY"):
            raise PyromanException(
                "service specification invalid: '%s' at %s" % (name, loginfo))

        self.name = name
        self.loginfo = loginfo
        try:
            self.sports = map(lambda p: Port(p), Util.splitter.split(sports))
            self.dports = map(lambda p: Port(p), Util.splitter.split(dports))
        except PortInvalidSpec, p:
            raise PyromanException("Service '%s' contains invalid port spec '%s' at %s: %s" \
             % (name, p.spec, loginfo, p.err))
Exemplo n.º 2
0
    def parse_ryu_switches(self):

        ryu_switches = None

        with open(self.network_configuration.conf_path + "ryu_switches.json",
                  "r") as in_file:
            ryu_switches = json.loads(in_file.read())

        #  Go through each node and grab the ryu_switches and the corresponding hosts associated with the switch
        for dpid in ryu_switches:

            #  prepare a switch id
            switch_id = "s" + str(dpid)

            # Check to see if a switch with this id already exists in the graph,
            # if so grab it, otherwise create it
            sw = self.get_node_object(switch_id)
            if not sw:
                sw = Switch(switch_id, self)
                self.graph.add_node(switch_id, node_type="switch", sw=sw)
                self.switch_ids.append(switch_id)

            # Parse out the information about all the ports in the switch
            switch_ports = {}
            for port in ryu_switches[dpid]["ports"]:
                if port["port_no"] == 4294967294:
                    continue

                if port["port_no"] == "LOCAL":
                    continue

                switch_ports[int(port["port_no"])] = Port(sw, port_json=port)

            if (not ryu_switches[dpid]["ports"]):
                #import pdb; pdb.set_trace()
                ovs_sw = self.network_configuration.mininet_obj.get(switch_id)
                for intf in ovs_sw.intfList():
                    if intf.name != 'lo':
                        new_port_obj = Port(sw, None, intf)
                        switch_ports[new_port_obj.port_number] = new_port_obj

            sw.ports = switch_ports

            # Parse group table if one is available
            if "groups" in ryu_switches[dpid]:
                sw.group_table = GroupTable(sw, ryu_switches[dpid]["groups"])

            # Parse all the flow tables and sort them by table_id in the list
            switch_flow_tables = []
            for table_id in ryu_switches[dpid]["flow_tables"]:
                switch_flow_tables.append(
                    FlowTable(sw, table_id,
                              ryu_switches[dpid]["flow_tables"][table_id]))
                sw.flow_tables = sorted(
                    switch_flow_tables,
                    key=lambda flow_table: flow_table.table_id)
Exemplo n.º 3
0
    def setUp(self):
        # GIVEN
        self._devices = Devices()

        for dev_id in range(5):
            device=Device(dev_id, Port(), Port())
            for idx in range(5):
                device.primary.assign(idx, NOTSET)
                device.secondary.assign(idx, NOTSET)
            self._devices.all.append(device)
Exemplo n.º 4
0
    def link_add_handler(self, event):
        """
            populate link information from event argument,
            then create bidirectional link between two nodes.
        """
        src_port = Port(port=event.link.src, neighbor=event.link.dst)
        dst_port = Port(port=event.link.dst, neighbor=event.link.src)

        # Create bidirectional link
        self.update_port_link(src_port.dpid, src_port)
        self.update_port_link(dst_port.dpid, dst_port)
Exemplo n.º 5
0
 def _add_port(devices_lst, ref_dev_id, ref_prim_port):
     """
     Add/create a port to the reference device.
     If config entry is:
         * 1 then its a primary port
         * 0 then its a secondary port
     """
     if ref_prim_port == 0 and not devices_lst[ref_dev_id].secondary:
         devices_lst[ref_dev_id].secondary = Port()
     if ref_prim_port == 1 and not devices_lst[ref_dev_id].primary:
         devices_lst[ref_dev_id].primary = Port()
Exemplo n.º 6
0
    def __init__(self, data, browser):
        profile = data['profile']

        #
        # Setup the environment.
        #
        self.env = data
        self.env['redfish_base'] = '/redfish/v1'
        self.env['browser'] = browser

        #
        # Create a socket endpoint for all dead-ended ports.
        #
        self.dead_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.dead_address = socket.gethostbyname('127.0.0.1')
        self.dead_socket.bind((self.dead_address, Port.PORT_DEAD))

        #
        # Create the ports for IO.
        #
        self.ports = [
            None for i in range(profile['portStart'], profile['portEnd'])
        ]

        port_info = self.env['profile']['ports']
        for src_port, dst_addr, dst_port, _, _ in self.env['remote']:
            if port_info[src_port]['State'] == 'Enabled':
                dst_uid = profile['ports'][src_port]['Remote']['UID']
                self.ports[src_port] = Port(self, 'Enabled', src_port,
                                            dst_addr, dst_port, dst_uid)

        #
        # Create the ports which are not linked.  This code will have them send packets to a dead address.
        #
        for i in range(profile['portStart'], profile['portEnd']):
            if not self.ports[i]:
                self.ports[i] = Port(self, 'Disabled', i, '127.0.0.1', -1, 0x0)

        #
        # Create the thread to run the ports.
        #
        self.thread = Thread(target=self.run, daemon=True)
        self.thread.start()

        #
        # Setup the underlying REDFish server.
        #
        self.server = RedfishServer(self)
        self.server.start()
Exemplo n.º 7
0
 def createPort(self, name, media_type, direction='in'):
     port = Port(name, media_type, direction)
     self.ports.append(port)
     self.prepareGeometryChange()
     port.setParentItem(self)
     self.arrangePorts()
     self.sizeBackground()
Exemplo n.º 8
0
    def setUp(self):
        # GIVEN
        device0 = Device(0, Port(), Port())

        for idx in range(5):
            device0.primary.assign(idx, NOTSET)
        for idx in range(4, 7):
            device0.secondary.assign(idx, NOTSET)

        device1 = Device(1, Port(), Port())
        for idx in range(5):
            device1.primary.assign(idx, NOTSET)
        for idx in range(3, 4):
            device1.secondary.assign(idx, NOTSET)

        self._devices = [device0, device1]
Exemplo n.º 9
0
 def createVlcContainer(self):
     port = Port()
     newPort = port.getNewPort()
     sp.getoutput(
         "sudo docker run -dit --device /dev/snd  -p {}:3333  xpra_vlc:v4".
         format(newPort))
     return newPort
Exemplo n.º 10
0
    def add_port(self, port_num, port_conf=None):
        # add port specific vlans or fall back to defaults
        port_conf = copy.copy(port_conf) if port_conf else {}

        port = self.ports.setdefault(port_num, Port(port_num, port_conf))

        port_conf.setdefault('mirror', None)
        if port_conf['mirror'] is not None:
            from_port_num = port_conf['mirror']
            self.mirror_from_port[from_port_num] = port_num
            # other configuration entries ignored.
            return

        # add native vlan
        port_conf.setdefault('native_vlan', None)
        if port_conf['native_vlan'] is not None:
            vid = port_conf['native_vlan']
            if vid not in self.vlans:
                self.vlans[vid] = VLAN(vid)
            self.vlans[vid].untagged.append(self.ports[port_num])

        # add vlans
        port_conf.setdefault('tagged_vlans', [])
        for vid in port_conf['tagged_vlans']:
            if vid not in self.vlans:
                self.vlans[vid] = VLAN(vid)
            self.vlans[vid].tagged.append(port)

        # add ACL
        port_conf.setdefault('acl_in', None)
        if port_conf['acl_in'] is not None:
            self.acl_in[port_num] = port_conf['acl_in']
Exemplo n.º 11
0
    def __init__(self, component_dict=None):
        """ The ``Component`` class represents a device.

        A component stores state individually for each instance and can be
        configured by passing in parameters using a structure that reprsents
        the state.

        Args:
            path (str): path to a model yaml file.
        """

        self.name = None
        self.ports = []

        # Load name from component data file
        if 'name' in component_dict:
            self.name = component_dict['name']

        # Load host flag from component data file
        if 'host' in component_dict:
            self.host = component_dict['host']
        else:
            self.host = False

        # Load ports from component data file
        for port_dict in component_dict['ports']:
            port = Port(self, port_dict)
            self.ports.append(port)
Exemplo n.º 12
0
 def start_tunnel(self):
     if self is not currentThread():
         self._send_cmd('start')
         return
     self._op_lock.acquire()
     try:
         self.is_active = 1
         # set up Port object for the tunnel that reads\writes to the 
         # slave device file of the pseudo-terminal pair. 
         if not self._serial_port:
             self._serial_port = Port()
         cfg = self._vcp.configuration()
         cfg['dev'] = self.tty
         cfg['name'] = '_slave'
         cfg['parent'] = self._vcp
         self._serial_port.configure(cfg)
         self._op_lock.release()
     except:
         self._op_lock.release()
     while self.is_active:
         if not self._serial_port.is_open():
             self._serial_port.open()
             self._serial_port.drain()
         try:
             if self.is_server:
                 self._do_listen()
             else:
                 self._do_connect()
         except:
             msglog.exception()
             if self._serial_port and not self._serial_port.is_open():
                 self._serial_port.close()
Exemplo n.º 13
0
 def create_port_list(self, start_port):
     """
     创建可用端口
     """
     port = Port()
     port_list = port.create_port_list(start_port, self.device_list)
     return port_list
Exemplo n.º 14
0
def get_suspicious():
    recent_ip, recent_port = sniff_ip(TIME_TO_SNIFF)
    for ip_src in recent_ip:
        if not ip_src in IP_DICT.keys():
            new_ip = IP(ip_src, TIME_TO_SNIFF)
            IP_DICT[ip_src] = new_ip

        IP_DICT[ip_src].add_count(recent_ip[ip_src])

    for port_src in recent_port:
        if not port_src in PORT_DICT.keys():
            new_port = Port(port_src, TIME_TO_SNIFF)
            PORT_DICT[port_src] = new_port

        PORT_DICT[port_src].add_count(recent_port[port_src])

    for ip_src in IP_DICT:
        data = IP_DICT[ip_src].get_data()
        if data['velocity'] > SUSPICIOUS_VELOCITY or data[
                'acceleration'] > SUSPICIOUS_ACCELERATION:
            SUSPICIOUS_IPS.append(ip_src)

    for port_src in PORT_DICT:
        data = PORT_DICT[port_src].get_data()
        if data['velocity'] > SUSPICIOUS_VELOCITY or data[
                'acceleration'] > SUSPICIOUS_ACCELERATION:
            SUSPICIOUS_PORTS.append(port_src)

    return SUSPICIOUS_IPS, SUSPICIOUS_PORTS
Exemplo n.º 15
0
    def parse_sel_switches(self, sel_switches):
        for each_id, switch in sel_switches.iteritems():
            # prepare the switch id
            switch_id = "s" + str(each_id)

            sw = self.get_node_object(switch_id)
            # Check to see if a switch with this id already exists in the graph,
            # if so grab it, otherwise create it
            if not sw:
                sw = Switch(switch_id, self)
                self.graph.add_node(switch_id, node_type="switch", sw=sw)
                self.switch_ids.append(switch_id)
            # Parse out the information about all the ports in the switch
            switch_ports = {}
            for port in switch["ports"]:
                switch_ports[port["portId"]] = Port(sw, port_json=port)

            sw.ports = switch_ports

            # Parse group table if one is available
            if "groups" in sel_switches[each_id]:
                sw.group_table = GroupTable(sw,
                                            sel_switches[each_id]["groups"])

            # Parse all the flow tables and sort them by table_id in the list
            switch_flow_tables = []
            for table_id in sel_switches[each_id]["flow_tables"]:
                switch_flow_tables.append(
                    FlowTable(sw, table_id,
                              sel_switches[each_id]["flow_tables"][table_id]))

            sw.flow_tables = sorted(switch_flow_tables,
                                    key=lambda flow_table: flow_table.table_id)
    def porty_wstawianie(self):
        #wstawianie portow pomiedzy srodkami wskazanymi przed kandydatow
        wybrancy = self.porty_kandydaci()
        wybor = [i % 5 for i in range(len(wybrancy) // 5 * 5)]
        wybor += [5 for i in range(len(wybrancy) - len(wybor))]
        self.porty = []

        #ustawienie tak, zeby porty nie staly na hexie surowca ktory wymieniaja
        for a in range(len(wybrancy)):
            i = wybrancy[a]
            temp = wybor.copy()
            for j in (i[0].sas_hexy + i[1].sas_hexy):
                if j.surowiec in temp:
                    temp.remove(j.surowiec)
            if len(temp) == 0:
                print("Polegl port")
                temp = wybor.copy()
            ustawienie = choice(temp)
            wybor.remove(ustawienie)
            i[0].handel, i[1].handel = ustawienie, ustawienie

            #wstawienie portu na mapke
            self.porty.append(Port(ustawienie))
            self.porty[a].setZValue(3)
            self.porty[a].setPos((i[0].pos().x() + i[1].pos().x()) // 2,
                                 (i[0].pos().y() + i[1].pos().y()) // 2)
            self.scene.addItem(self.porty[a])
Exemplo n.º 17
0
 def createContainer(self):
     port = Port()
     newPort = port.getNewPort()
     sp.getoutput(
         "sudo docker run -dit -p {}:3333 --device /dev/snd -v /videos:/root/video  xpra_vlc:v4"
         .format(newPort))
     return newPort
Exemplo n.º 18
0
    def create_port_list(self, start_port):
        '''
		创建可用端口
		'''
        port = Port()
        port_list = []
        port_list = port.create_port_list(start_port, self.device_list)
        return port_list
Exemplo n.º 19
0
 def Place(self, seg):
     self.placed = True
     self.Go()
     segport = Port([Vertex(*pnt) for pnt in seg])
     tmat = self.GetInport(self.innum).Overlay(segport)
     for prim in self.prims:
         prim.SelfTrans()
     self.Trans(tmat)
Exemplo n.º 20
0
    def enable_ports(self):
        for host, port in self.router.connections:
            new_port = Port(port=port, host=host)
            new_port_name = str(new_port)
            self.router.ports.update({new_port_name: new_port})
            self.port_locks.update({new_port_name: RLock()})

        for port in self.router.ports.keys():
            self.get_up_port(port)
Exemplo n.º 21
0
    def add_port(self, name, is_output=False, flags=0, ptr=None):
        port = Port(self, self.scene())
        port.set_is_output(is_output)
        port.set_name(name)
        port.set_node(node=self)
        port.set_port_flags(flags)
        port.set_ptr(ptr)

        self._ports.append(port)
Exemplo n.º 22
0
    def get_ports(self):
        """
        Get all ports of this switch.

        Returns Port objects.
        """
        from hpswitch.port import Port
        base_ports = self.snmp_get_subtree(("dot1dBasePort", ))
        return [Port(self, base_port=int(p[1])) for p in base_ports]
Exemplo n.º 23
0
    def EnumeratePorts(self):
        """Enumerate all storage ports on the system

        returns:
            An array of object paths for ports
        """
        l = list()
        for i in self.iface.EnumeratePorts():
            obj = Port(i)
            l.append(obj)
        return l
Exemplo n.º 24
0
    def addPort(self, portType=None, dataType=None, name=None):
        #Redefined
        # [ [portIN, portOUT], ... ]

        self._inputs.append(
            Port(dataType=dataType,
                 portType="IN",
                 name=name + "_IN",
                 nodePointer=self))
        portIN = self._inputs[-1]
        self._outputs.append(
            Port(dataType=dataType,
                 portType="OUT",
                 name=name + "_OUT",
                 nodePointer=self))
        portOUT = self._outputs[-1]

        self.addPair(portIN=portIN, portOUT=portOUT)

        return self._portsPairs[-1]
Exemplo n.º 25
0
def ListPorts(Where=''):
    out = []
    DbConnection = sqlite3.connect('main.db')
    DbCursor = DbConnection.cursor()
    #cursor=DbCursor.execute("SELECT * FROM PORTS "+Where)
    for row in DbCursor.execute("SELECT * FROM PORTS " + Where).fetchall():
        Obj = Port()
        Obj.Id = row[0]
        Obj.RouterId = row[1]
        Obj.Ip = row[2]
        out.append(Obj)
    DbConnection.close()
    return out
Exemplo n.º 26
0
    def get_port_for_mac(self, mac):
        """
        Returns the port that a specified mac is learned on, or None if no such port exists.
        """
        oid = tuple([
            'dot1dTpFdbPort',
        ] + [int(x, 16) for x in mac.split(":")])
        portID = self.snmp_get(oid)

        if not portID:
            return None

        port = Port(self, base_port=int(portID))
        return port
Exemplo n.º 27
0
 def port_add_handler(self, event):
     """
         event handler triggered when port added.
         get Swtich instance and creat a Port object.
     """
     port = Port(event.port)
     try:
         switch = self.switches[port.dpid]
         switch.ports[port.port_no] = port
         logger.info('port added, port_no=%s (dpid=%s)',
                     portno_lib.port_no_to_str(port.port_no),
                     dpid_lib.dpid_to_str(port.dpid))
     except:
         pass
Exemplo n.º 28
0
 def port_delete_handler(self, event):
     """
         event handler triggered when port deleted.
         get Switch instance and delete specific Port object.
     """
     port = Port(event.port)
     logger.info('port deleted, port_no=%s (dpid=%s)',
                 portno_lib.port_no_to_str(port.port_no),
                 dpid_lib.dpid_to_str(port.dpid))
     try:
         switch = self.switches[port.dpid]
         del switch.ports[port.port_no]
     except KeyError:
         pass
Exemplo n.º 29
0
def port_parser(dp_id, p_identifier, port_conf, vlans):
    port = Port(p_identifier, port_conf)

    if port.mirror is not None:
        # ignore other config
        return port
    if port.native_vlan is not None:
        v_identifier = port.native_vlan
        vlan = vlans.setdefault(v_identifier, VLAN(v_identifier, dp_id))
        vlan.untagged.append(port)
    for v_identifier in port.tagged_vlans:
        vlan = vlans.setdefault(v_identifier, VLAN(v_identifier, dp_id))
        vlan.tagged.append(port)

    return port
Exemplo n.º 30
0
def port_parser(dp_id, p_identifier, port_conf, vlans):
    port = Port(p_identifier, port_conf)

    if port.mirror is not None:
        # ignore other config
        return port
    if port.native_vlan is not None:
        v_identifier = port.native_vlan
        vlan = _get_vlan_by_identifier(dp_id, v_identifier, vlans)
        vlan.add_untagged(port)
    for v_identifier in port.tagged_vlans:
        vlan = _get_vlan_by_identifier(dp_id, v_identifier, vlans)
        vlan.add_tagged(port)

    return port