def listen(self, host): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, SERVICE_PORT)) port = Port(sock) port.write(self.subs) while True: res = port.read() if res: self.queue.put(res)
def listen_telescreens(self, listen_port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(("", listen_port)) sock.listen(10000) while True: client_sock, _ = sock.accept() port = Port(client_sock) uuid = port.read() self.telescreens[uuid] = port
class Source(object): def __init__(self, host): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, SERVICE_PORT)) self.port = Port(sock) def sendall(self, list): for item in list: self.port.write(item) def send(self, item): self.port.write(item)
def __init__(self, client, server, ip, port, dport, dir, loginfo): """ Create a new NAT rule client -- clients allowed to access this NAT rule server -- host nick the NAT is applied to ip -- IP that is used in NAT port -- Ports that are used in NAT dport -- Destination port for single port redirections dir -- incoming, outgoing or bidirecitonal NAT Note that the NAT is always applied to the "server" host, the UI accessible function is responsible to eventually exchange client and server for "outgoing" NATs (where the naming of client, server makes more sense the other way, think of workstations accessing web server via a NAT) """ if server == "": raise PyromanException("Nat lacking a server host (client: %s, server: %s, ip: %s) at %s" % (client, server, ip, loginfo)) if ip == "": raise PyromanException("Nat lacking IP address: (client: %s, server: %s) at %s" % (client, server, loginfo)) if dir not in ["in", "out", "both"]: raise PyromanException("Nat with invalid direction: (client: %s, server: %s, ip: %s, dir: %s) at %s" % (client, server, ip, dir, loginfo)) if not Util.verify_ip4(ip): raise PyromanException("Nat with invalid IP address: (client: %s, server: %s, ip: %s) at %s" % (client, server, ip, loginfo)) if port: try: self.port = Port(port) except PortInvalidSpec: raise PyromanException("Nat port specification invalid: (client: %s, server: %s, ip: %s, port: %s) at %s " % (client, server, ip, port, loginfo)) if not self.port.forIPv4(): raise PyromanException("Non-IPv4 port specified: "+port) else: self.port = None if dport: try: self.dport = Port(dport) except PortInvalidSpec: raise PyromanException("Nat dport specification invalid: (client: %s, server: %s, ip: %s, port: %s, dport: %s) at %s " % (client, server, ip, port, dport, loginfo)) if not self.dport.forIPv4(): raise PyromanException("Non-IPv4 port specified: "+dport) else: self.dport = None if self.dport and not (self.port.proto == self.dport.proto): raise PyromanException("Nat ports have different protocols: (client: %s, server: %s, ip: %s, port: %s, dport: %s) at %s" % (client, server, ip, port, dport, loginfo)) if dport and not port: raise PyromanException("Nat with destination port, but no source port: (client: %s, server: %s, ip: %s, dport: %s) at %s" % (client, server, ip, dport, loginfo)) self.client = Util.splitter.split(client) self.server = Util.splitter.split(server) self.ip = ip # port, dport are set above self.dir = dir self.loginfo = loginfo
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()
def port_scan(self): """ Scan range of ports """ scan_ports = list(Port.ports_list(self.address[1])) random.shuffle(scan_ports) for port in scan_ports: self.ports[port] = Port(self.address[0], port) print(self.ports[port]) return self.ports
def _finish_init_(self): for p in self._obj.ports: self._children.append(Port.getPort(p, self, self._outbox)) for prop in self._obj._propertySet: try: pp = Property(prop, self, self._outbox) self._children.append(pp) except: pass
def parse(tkns): """ Parse a verilog module module := 'module' identifier [module_param_port_list] [list_of_ports] ';' {module_item} 'endmodule' | 'module' identifier [module_param_port_list] [list_of_port_declarations] ';' {non_port_module_item} 'endmodule' """ tkns.expect(Tokens.KW_MODULE) # get module name name = tkns.current().text tkns.expect(Tokens.IDENTIFIER) # get parameter port list, if it exists params = [] if tkns.check(Tokens.HASH): params = Parameter.parse_module_param_port_list(tkns) # get i/o port list, if it exists io = [] if tkns.check(Tokens.OPEN_PAREN): if tkns.peek(Tokens.CLOSE_PAREN): tkns.next() tkns.next() elif tkns.peek(Tokens.KW_INOUT) or tkns.peek(Tokens.KW_INPUT) or tkns.peek(Tokens.KW_OUTPUT): io = Port.parse_list_of_port_declarations(tkns) else: io = Port.parse_list_of_ports(tkns) # get module contents # TODO: look at contents for more parameters, do other parsing contents = [] while not tkns.accept(Tokens.KW_ENDMODULE): contents.append(tkns.next()) return Module(name, params, io, contents)
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
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
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) 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)
def __init__(self): super(PiInterface, self).__init__(40) for number in range(1, 41): if number not in self._FORBIDDEN: self._ports[number] = Port(self, number) # Defines the pull up or pull down rezistor for inputs. # Possible values are: # 1. self.PULL_UP # 2. self.PULL_DOWN # 3. None (input fluctuating by default) self.pull_up_down_rezistor = self.PULL_UP self._port_listeners = {} self._initialize_ports()
def get_ports(self, refresh=False): """ Get all ports on this OVS node :param refresh: (boolean) If true, force refresh of all items :return: (list) of port nodes """ if not refresh and self._ports is not None: return self._ports self._ports = Port.get_ports(parent=self, port_ids=self.metadata['ports'], address=self.ssh_address, ssh_credentials=self._ssh_credentials, ovs_topology=self.ovs_topology) return self._ports
def parse_onos_switches(self): onos_switches = None with open(self.network_configuration.conf_path + "onos_switches.json", "r") as in_file: onos_switches = json.loads(in_file.read()) for onos_switch in onos_switches["devices"]: # prepare a switch id switch_id = self.onos_sw_device_id_to_node_id_mapping( onos_switch["id"]) # 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_num in onos_switch["ports"]: switch_ports[int(port_num)] = Port( sw, port_json=onos_switch["ports"][port_num]) sw.ports = switch_ports # Parse group table if one is available if "groups" in onos_switch: sw.group_table = GroupTable(sw, onos_switch["groups"]) # Parse all the flow tables and sort them by table_id in the list switch_flow_tables = [] for table_id in onos_switch["flow_tables"]: switch_flow_tables.append( FlowTable(sw, table_id, onos_switch["flow_tables"][table_id])) sw.flow_tables = sorted( switch_flow_tables, key=lambda flow_table: flow_table.table_id)
def parse_onos_switches(self, onos_switches): for onos_switch in onos_switches["devices"]: if not onos_switch["available"]: continue # prepare a switch id switch_id = self.onos_sw_device_id_to_node_id_mapping( onos_switch["id"]) # 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_json in onos_switch["ports"]: if port_json["port"] == "local": continue switch_ports[int(port_json["port"])] = Port(sw, port_raw=port_json) sw.ports = switch_ports # Parse group table if one is available if "groups" in onos_switch: sw.group_table = GroupTable(sw, onos_switch["groups"]) # Parse all the flow tables and sort them by table_id in the list switch_flow_tables = [] for table_id in onos_switch["flow_tables"]: switch_flow_tables.append( FlowTable(sw, table_id, onos_switch["flow_tables"][table_id])) sw.flow_tables = sorted( switch_flow_tables, key=lambda flow_table: flow_table.table_id)
def switch_feature_handler(self, event): """ event handler when receiving feature information from switch. """ dpid = event.msg.datapath_id try: switch = self.switches[dpid] except KeyError: self.switches[dpid] = Switch(event.msg.datapath, self.switches) switch = self.switches[dpid] for port_no, port in event.msg.ports.iteritems(): if port_no not in switch.ports: p = Port(port=port, datapath=event.msg.datapath) switch.ports[port_no] = p p = switch.ports[port_no] if port_no == ofproto_v1_0.OFPP_LOCAL: switch.name = port.name.rstrip('\x00')
def parse_grpc_switches(self, grpc_switches): # Go through each node and grab the ryu_switches and the corresponding hosts associated with the switch for switch in grpc_switches: # 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.switch_id) if not sw: sw = Switch(switch.switch_id, self) self.graph.add_node(switch.switch_id, node_type="switch", sw=sw) self.switch_ids.append(switch.switch_id) # Parse out the information about all the ports in the switch switch_ports = {} for port in switch.ports: if port.port_num == 4294967294: continue if port.port_num == "LOCAL": continue switch_ports[int(port.port_num)] = Port(sw, port_raw=port) sw.ports = switch_ports # Parse group table if one is available if len(switch.group_table) > 0: sw.group_table = GroupTable(sw, switch.group_table) # Parse all the flow tables and sort them by table_id in the list switch_flow_tables = [] for flow_table in switch.flow_tables: switch_flow_tables.append( FlowTable(sw, flow_table.table_num, flow_table)) sw.flow_tables = sorted( switch_flow_tables, key=lambda flow_table: flow_table.table_id)
def logic(self): nr_containers = totContainers() port = Port("PiraeusPier2", nr_containers) threads = [] groups = [] nr_groups = 13 colours = [] colours.append(pygame.Color(228, 197, 73)) colours.append(pygame.Color(185, 0, 37)) colours.append(pygame.Color(78, 87, 111)) colours.append(pygame.Color(12, 63, 50)) colours.append(pygame.Color(236, 110, 0)) colours.append(pygame.Color(68, 22, 33)) colours.append(pygame.Color(143, 149, 160)) colours.append(pygame.Color(185, 197, 201)) colours.append(pygame.Color(35, 127, 125)) colours.append(pygame.Color(149, 132, 103)) colours.append(pygame.Color(0, 44, 125)) colours.append(pygame.Color(0, 160, 213)) colours.append(pygame.Color(166, 202, 87)) colours.append(pygame.Color(228, 166, 156)) for i in range(nr_groups - port.nr_docks): groups.append(Group(i, port, "outbound", nr_containers, colours[i])) for i in range(nr_groups - port.nr_docks, nr_groups): groups.append(Group(i, port, "inbound", nr_containers, colours[i])) info = InfoPanel(port, groups) for i in range(nr_groups): thread = Thread(target=groups[i].manage, name=str(i), daemon=True) threads.append(thread) """info = Thread(target = info.give_info, name = str(nr_groups + 1), daemon = True) threads.append(info)""" for t in threads: t.start() graphics = Graphics(port, groups) graphics.display() while True: pass
def scanIp(self, Ip, Mac): # if Mac is None: # Mac = getmacbyip(Ip) self.nm.scan(Ip, '1-200') ports = [] for protocol in self.nm[Ip].all_protocols(): lport = self.nm[Ip][protocol].keys() lport.sort() for port in lport: name = self.nm[Ip][protocol][port]['name'] state = self.nm[Ip][protocol][port]['state'] product = self.nm[Ip][protocol][port]['product'] p = Port(port, name, state, product, protocol) ports.append(p) m = Machine(Ip, Mac, ports) if 'hostnames' in self.nm[Ip]: m.hostname = self.nm[Ip]['hostnames'] so, accuracy = self.findSO(m) m.so = so m.accuracy = accuracy self.lmachine.append(m)
def __init__(self, path=None): """ The ``Device`` class represents a device. Args: path (str): path to a model yaml file. """ self.name = None self.ports = [] if path != None: model = util.load_yaml_file(path) # Load name from device model file if 'name' in model: self.name = model['name'] # Load ports from device model file for port_model in model['ports']: port = Port(port_model['number']) # Parse port state space: # 1. search for 'mode', 'direction', 'voltage' (a) values or (b) lists of values # 2. search for 'states' list if 'mode' in port_model and 'direction' in port_model and 'voltage' in port_model: state = {} state['mode'] = [port_model['mode']] state['direction'] = [port_model['direction']] state['voltage'] = [port_model['voltage']] port.states.append(state) elif 'states' in port_model: for state in port_model['states']: port.states.append(state) #print state['mode'] #print state['direction'] #print state['voltage'] self.ports.append(port)
class Agent(object): def __init__(self, addr): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(addr) self.port = Port(sock) def list(self): self.port.write("?") return json.loads(self.port.read()) def fetch(self, want="*"): if want == "*": req = "*" else: req = json.dumps(want) self.port.write(req) return json.loads(self.port.read())
def __init__(self, address): """ Creates new instance of interface with some address defined by I2C. It DOES NOT validate if an interface instance with the same address was already created. :param address: Address of I2C interface, eg. 0x20. """ super(MCP23017, self).__init__(16) self._address = address # _MCP23017ListenerThread self._read_events_thread = None # Determines if pull up rezistor should be set for inputs. # If False nothing will be set, so by default input will be # fluctuating. self.use_pullup_rezistor = True for number in range(1, 17): self._ports[number] = Port(self, number) _REGISTRY.append(self) self._initialize_ports()
def createContainer(self): port = Port() newPort = port.getNewPort() sp.getoutput( "sudo docker run -dit -p {}:4200 paas:v1".format(newPort)) return newPort
def __init__(self, direction, protocol, port, ip): self._direction = direction self._protocol = protocol self._port = Port(port) self._ip = Ip(ip)
def SetOutport(self, ptups): vecs = [] for ptup in ptups: vecs.append(self.prims[ptup[0]].vertices[ptup[1]]) self.outports.append(Port(vecs))
def port(self): return Port(self.client)
def _packet_in_handler(self, ev): msg = ev.msg dp = msg.datapath ofproto = dp.ofproto parser = dp.ofproto_parser pkt = packet.Packet(msg.data) ethernet_proto = pkt.get_protocols(ethernet.ethernet)[0] src = ethernet_proto.src dst = ethernet_proto.dst eth_type = ethernet_proto.ethertype in_port = msg.match['in_port'] self.mac_to_port.setdefault(dp.id, {}) # Configure logging to include datapath id self.set_dpid_log_formatter(dp.id) if dp.id not in self.dps: self.logger.error("Packet_in on unknown datapath") self.set_default_log_formatter() return else: datapath = self.dps[dp.id] if not datapath.running: self.logger.error("Packet_in on unconfigured datapath") if in_port not in datapath.ports: self.set_default_log_formatter() return if eth_type == ether.ETH_TYPE_8021Q: # tagged packet vlan_proto = pkt.get_protocols(vlan.vlan)[0] vid = vlan_proto.vid if Port(in_port, 'tagged') not in datapath.vlans[vid].tagged: self.logger.warn("HAXX:RZ in_port:%d isn't tagged on vid:%s" % \ (in_port, vid)) self.set_default_log_formatter() return else: # untagged packet vid = datapath.get_native_vlan(in_port).vid if not vid: self.logger.warn("Untagged packet_in on port:%d without native vlan" % \ (in_port)) self.set_default_log_formatter() return self.mac_to_port[dp.id].setdefault(vid, {}) self.logger.info("Packet_in src:%s dst:%s in_port:%d vid:%s", src, dst, in_port, vid) # learn a mac address to avoid FLOOD next time. self.mac_to_port[dp.id][vid][src] = in_port # generate the output actions for broadcast traffic tagged_act = self.tagged_output_action(parser, datapath.vlans[vid].tagged) untagged_act = self.untagged_output_action( parser, datapath.vlans[vid].untagged) matches = [] action = [] if datapath.ports[in_port].is_tagged(): # send rule for mathcing packets arriving on tagged ports strip_act = [parser.OFPActionPopVlan()] if tagged_act: action += tagged_act if untagged_act: action += strip_act + untagged_act matches.append( parser.OFPMatch(vlan_vid=vid | ofproto_v1_3.OFPVID_PRESENT, in_port=in_port, eth_src=src, eth_dst='ff:ff:ff:ff:ff:ff')) matches.append( parser.OFPMatch(vlan_vid=vid | ofproto_v1_3.OFPVID_PRESENT, in_port=in_port, eth_src=src, eth_dst=('01:00:00:00:00:00', '01:00:00:00:00:00'))) elif datapath.ports[in_port].is_untagged(): # send rule for each untagged port push_act = [ parser.OFPActionPushVlan(ether.ETH_TYPE_8021Q), parser.OFPActionSetField(vlan_vid=vid | ofproto_v1_3.OFPVID_PRESENT) ] if untagged_act: action += untagged_act if tagged_act: action += push_act + tagged_act matches.append( parser.OFPMatch(in_port=in_port, eth_src=src, eth_dst='ff:ff:ff:ff:ff:ff')) matches.append( parser.OFPMatch(in_port=in_port, eth_src=src, eth_dst=('01:00:00:00:00:00', '01:00:00:00:00:00'))) # install broadcast/multicast rules onto datapath if datapath.config_default['smart_broadcast']: for match in matches: priority = datapath.config_default['low_priority'] cookie = datapath.config_default['cookie'] self.add_flow(dp, match, action, priority, cookie) # install unicast flows onto datapath if dst in self.mac_to_port[dp.id][vid]: # install a flow to avoid packet_in next time out_port = self.mac_to_port[dp.id][vid][dst] if out_port == in_port: self.logger.info("in_port is the same as out_port, skipping unicast flow " \ "dl_dst:%s dl_src:%s vid:%d", dst, src, vid) self.set_default_log_formatter() return self.logger.info("Adding unicast flow dl_dst:%s vid:%d", dst, vid) actions = [] if datapath.ports[in_port].is_tagged(): match = parser.OFPMatch(in_port=in_port, eth_src=src, eth_dst=dst, vlan_vid=vid | ofproto_v1_3.OFPVID_PRESENT) if datapath.ports[out_port].is_untagged(): actions.append(parser.OFPActionPopVlan()) if datapath.ports[in_port].is_untagged(): match = parser.OFPMatch(in_port=in_port, eth_src=src, eth_dst=dst) if datapath.ports[out_port].is_tagged(): actions.append(parser.OFPActionPushVlan()) actions.append( parser.OFPActionSetField( vlan_vid=vid | ofproto_v1_3.OFPVID_PRESENT)) actions.append(parser.OFPActionOutput(out_port)) priority = datapath.config_default['high_priority'] cookie = datapath.config_default['cookie'] self.add_flow(dp, match, actions, priority, cookie) # Reset log formatter self.set_default_log_formatter()
class Nat: """ Represents a Network Address Translation rule. """ def __init__(self, client, server, ip, port, dport, dir, loginfo): """ Create a new NAT rule client -- clients allowed to access this NAT rule server -- host nick the NAT is applied to ip -- IP that is used in NAT port -- Ports that are used in NAT dport -- Destination port for single port redirections dir -- incoming, outgoing or bidirecitonal NAT Note that the NAT is always applied to the "server" host, the UI accessible function is responsible to eventually exchange client and server for "outgoing" NATs (where the naming of client, server makes more sense the other way, think of workstations accessing web server via a NAT) """ if server == "": raise PyromanException("Nat lacking a server host (client: %s, server: %s, ip: %s) at %s" % (client, server, ip, loginfo)) if ip == "": raise PyromanException("Nat lacking IP address: (client: %s, server: %s) at %s" % (client, server, loginfo)) if dir not in ["in", "out", "both"]: raise PyromanException("Nat with invalid direction: (client: %s, server: %s, ip: %s, dir: %s) at %s" % (client, server, ip, dir, loginfo)) if not Util.verify_ip4(ip): raise PyromanException("Nat with invalid IP address: (client: %s, server: %s, ip: %s) at %s" % (client, server, ip, loginfo)) if port: try: self.port = Port(port) except PortInvalidSpec: raise PyromanException("Nat port specification invalid: (client: %s, server: %s, ip: %s, port: %s) at %s " % (client, server, ip, port, loginfo)) if not self.port.forIPv4(): raise PyromanException("Non-IPv4 port specified: "+port) else: self.port = None if dport: try: self.dport = Port(dport) except PortInvalidSpec: raise PyromanException("Nat dport specification invalid: (client: %s, server: %s, ip: %s, port: %s, dport: %s) at %s " % (client, server, ip, port, dport, loginfo)) if not self.dport.forIPv4(): raise PyromanException("Non-IPv4 port specified: "+dport) else: self.dport = None if self.dport and not (self.port.proto == self.dport.proto): raise PyromanException("Nat ports have different protocols: (client: %s, server: %s, ip: %s, port: %s, dport: %s) at %s" % (client, server, ip, port, dport, loginfo)) if dport and not port: raise PyromanException("Nat with destination port, but no source port: (client: %s, server: %s, ip: %s, dport: %s) at %s" % (client, server, ip, dport, loginfo)) self.client = Util.splitter.split(client) self.server = Util.splitter.split(server) self.ip = ip # port, dport are set above self.dir = dir self.loginfo = loginfo def gen_snat(self, client, server): """ Internal helper function, with client, server objects """ iff = client.iface.get_filter("d") target = "SNAT --to-source %s" % self.ip # do we have a port restriction? pfilter = "" if self.port and self.dport: pfilter = self.dport.get_filter_proto() + " " + self.dport.get_filter_port("s") target = target + ":%s" % self.port.port elif self.port: pfilter = self.port.get_filter_proto() + " " + self.port.get_filter_port("s") c = Firewall.chains["natPOST"] for sip in server.ip: filter = iff[0] + " -s %s" % sip c.append4("%s %s -j %s" % (filter, pfilter, target), self.loginfo) def gen_dnat(self, client, server): """ Internal helper function, with client, server objects """ iff = client.iface.get_filter("s") filter = iff[0] + " -d %s" % self.ip # do we have a port restriction? pfilter = "" if self.port: pfilter = self.port.get_filter_proto() + " " + self.port.get_filter_port("d") c = Firewall.chains["natPRE"] for sip in server.ip: target = "DNAT --to-destination %s" % sip if self.dport: target = target + ":%s" % self.dport.port c.append4("%s %s -j %s" % (filter, pfilter, target), self.loginfo) def generate(self): for c in self.client: for s in self.server: client = Firewall.hosts[c] server = Firewall.hosts[s] # sanity checks, that should be moved to "verify" if not client or not server: raise PyromanException("Client or server not found for NAT defined at %s" % self.loginfo) if client.iface == server.iface: raise PyromanException("client interface and server interface match (i.e. cannot NAT!) for NAT defined at %s" % self.loginfo) if self.dir in ["in", "both"]: self.gen_dnat(client, server) if self.dir in ["out", "both"]: self.gen_snat(client, server)
totalProfits[0] += profit elif self.containerInfo[containerID][2] == "Metro": totalProfits[1] += profit # if containerID in self.promoted2updatedPrice: movesDetails.append(f"Deliver container {containerID} from coordinate ({x+1}, {y+1}, {z+1}) with updated price {contractPrice}") # else: # movesDetails.append(f"Deliver container {containerID} from coordinate ({x+1}, {y+1}, {z+1})") amount2deliver -= 1 z -= 1 with open("Final report.txt", 'w') as f: for line in movesDetails: f.write(line+"\n") with open("Final report performance.txt", 'w') as f: f.write(f"Total contract prices = {totalContractPrice}\n") f.write(f"Carrefour profits = {totalProfits[0]}\n") f.write(f"Metro profits = {totalProfits[1]}\n") f.write(f"Port Throughput = {totalDelivered}\n") print(totalContractPrice, totalProfits, totalDelivered) if __name__ == "__main__": carrefour = Customer("carrefour_report.csv", "container.csv", name="carrefour") metro = Customer("metro_report.csv", "container.csv", name='metro') port = Port("container.csv") moop = Moop(port, [carrefour, metro], ["carrefour_output.csv", "metro_output.csv"]) moop.optimize()
car2 = Car('辽B12345', '黄色', '745', '宝马') car3 = Car('辽C12345', '蓝色', 'GLC', '奔驰') car4 = Car('辽D12345', '黑色', 'DSG', '迈腾') car5 = Car('辽E12345', '白色', 'CS35', '长安') car_list = [car1, car2, car3, car4, car5] owner1 = CarOwner('1', 'Uzi', '13845789865', car1) owner2 = CarOwner('2', 'Letme', '14578956858', car2) owner3 = CarOwner('3', 'Xiaohu', '15858585858', car3) owner4 = CarOwner('4', 'Mlxg', '16688666688', car4) owner5 = CarOwner('5', 'Ming', '17985465258', car5) owner_list = [owner1, owner2, owner3, owner4, owner5] port1 = Port('5', 5, '0') port2 = Port('15', 5, '0') port3 = Port('25', 5, '0') port_list = [port1, port2, port3] park1 = Park('浑南停车场', 100, '浑南', 100) park2 = Park('大东停车场', 100, '大东', 100) park3 = Park('沈河停车场', 100, '沈河', 100) park_list = [park1, park2, park3] '''随机一次场景的各项属性''' this_owner = random.sample(owner_list, 1) #随机一个车主 this_park = random.sample(park_list, 1) #随机一个停车场 this_port = random.sample(port_list, 1) #随机一个车位
print(f"Host {self.ip}") print(f"OS fingerprint: {self.os} - {self.version}") if not len(self.ports): print(f"Ports: none") return print(f"Ports: ") for p in self.ports.values(): p.print() if __name__ == "__main__": print(f"### device.py example ###\n") d = Device("127.0.0.1", "Windows 10", "Build 1901") p = Port(25, "tcp") p.service = "smtp" p.software = "postfix" p.version = "2.13" v = Vulnerability() v.software = p.software v.version = p.version v.type = "RCE" v.description = "sample RCE desc" v.addExploit("https://cve.truc/exp1") v.addExploit("https://cve.truc/exp2") p.addVuln(v) d.addPort(p) d.print()
def __init__(self, addr): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(addr) self.port = Port(sock)
def add_port(self, k, v={}): # add port specific vlans or fall back to defaults v = copy.copy(v) if v else {} if 'exclude' in self.config_default: excluded = self.is_excluded(self.config_default['exclude'], k) else: excluded = False # set default vlans if we have any if not excluded and 'vlans' in self.config_default: v.setdefault('vlans', self.config_default['vlans']) else: v.setdefault('vlans', []) # set default type if not excluded and 'type' in self.config_default: v.setdefault('type', self.config_default['type']) else: v.setdefault('type', self.default_type) # set default acls if not excluded and 'acls' in self.config_default: v.setdefault('acls', self.config_default['acls']) else: v.setdefault('acls', []) # add vlans & acls configured on a port for vid in v['vlans']: if vid not in self.vlans: self.vlans[vid] = VLAN(vid) if k not in self.ports: self.ports[k] = Port(k, v['type'], v['acls']) self.vlans[vid].add_port(self.ports[k]) # add configuration that should be on all ports for c in self.config_all: c.setdefault('vlans', []) c.setdefault('type', v['type']) c.setdefault('exclude', []) c.setdefault('acls', []) # exclude ports if self.is_excluded(c['exclude'], k): continue # add port to 'all' vlans for vid in c['vlans']: if k not in self.ports: self.ports[k] = Port(k, c['type'], v['acls']) port = self.ports[k] if vid in self.vlans and port in self.vlans[vid].get_ports(): # port is already in vlan, skip continue if vid not in self.vlans: self.vlans[vid] = VLAN(vid) self.vlans[vid].add_port(port) # add 'all' acls to port for acl in c['acls']: self.ports[k].add_acl(acl)
def createContainer(self): port=Port() newPort=port.getNewPort() sp.getoutput("sudo docker run -dit -p {}:3333 xpra_vlc:v4".format(newPort)) return newPort
def process_optional_input(pop = None, conc = None, port_y = None): global port_name, port_ambient_conc, port_y0, port_c0, port_pop_struc, port_pop, base_conc, port_real_em, ratio if pop is not None: port_pop = pop if conc is not None: port_ambient_conc = conc # call Port class to do calc, if use inputs his own y, then pass y to port class instead of y0 to calc ymin if port_y is None: port = Port(port_name, port_ambient_conc, port_y0, port_c0, port_pop_struc, port_pop, base_conc, port_real_em, ratio) indicator = 0 else: port = Port(port_name, port_ambient_conc, port_y, port_c0, port_pop_struc, port_pop, base_conc, port_real_em, ratio) indicator = 1 name_t = port_name ambient_t = port_ambient_conc y0_t = port_y0 c0_t = port_c0 pop_struc_t = port_pop_struc pop_t = port_pop base_t = base_conc em_t = port_real_em #print impact.key impact = port.get_impact(indicator) # process/aggregate the impact in some way result_disease_age = {} result_disease_time = {} result_disease_zone = {} result_disease_age_yll = {} for key in impact.keys(): if key != 'ARI': impact_all_age = np.empty(age_group) for i in range(age_group): impact_all_age[i] = sum(impact[key][i][4, :]) result_disease_age[key] = np.around(impact_all_age, 2) else: result_disease_age[key] = np.around(np.array([sum(impact[key][0][4, :])]),2) # does not matter if ARI or not for key in impact.keys(): impact_sum_age = sum(impact[key]) result_disease_zone[key] = np.around(impact_sum_age[4, :],2) #print impact_sum_age.key temp = np.empty(time_interval) for i in range(time_interval): temp[i] = sum(impact_sum_age[i, :]) result_disease_time[key] = np.around(temp, 2) #sum_age_t = impact_sum_age #print sum_age_t.key for key in impact.keys(): if key != "ARI": result_disease_age_yll[key] = np.around(np.array(life_exp) * result_disease_age[key], 2) #-- add total col for yll except its ARI result_disease_age_yll[key] = np.append(result_disease_age_yll[key], sum(result_disease_age_yll[key])) #-- add total col for age except its ARI result_disease_age[key] = np.append(result_disease_age[key], sum(result_disease_age[key])) else: result_disease_age_yll[key] = np.around(np.array(life_exp[0]) * result_disease_age[key], 2) #exp_t = life_exp #age_t = result_disease_age_yll["ARI"] #print exp_t.key #--- Add N/A and total in cols for ARI result_disease_age['ARI'] = np.append(result_disease_age['ARI'], np.array([ 0 for i in range(age_group - 1)])) result_disease_age['ARI'] = np.append(result_disease_age['ARI'], result_disease_age['ARI'][0]) result_disease_age_yll['ARI'] = np.append(result_disease_age_yll['ARI'], np.array([ 0 for i in range(age_group - 1)])) result_disease_age_yll['ARI'] = np.append(result_disease_age_yll['ARI'], result_disease_age_yll['ARI'][0]) #-- add total row below each table #result_disease_age['Total'] = np.zeros(age_group + 1) #result_disease_time['Total'] = np.zeros(age_group + 1) #result_disease_age_yll['Total'] = np.zeros(age_group + 1) #result_disease_zone['Total'] = np.zeros(age_group + 1) #for i in range(age_group + 1): # for key in result_disease_age.keys(): # if key!= 'Total' and result_disease_age[key][i] != 'N/A': # result_disease_age['Total'][i] = result_disease_age['Total'][i] + float(result_disease_age[key][i]) #-- get rid of 0-4 value for age time before adding up cols #result_disease_age['LC'][0] = 0 #result_disease_age['CP'][0] = 0 #result_disease_age_yll['LC'][0] = 0 #result_disease_age_yll['CP'][0] = 0 #-- add total row below table add_total(result_disease_age) add_total(result_disease_time, time_interval) add_total(result_disease_age_yll) add_total(result_disease_zone, len(result_disease_zone['ARI'])) return {'age': result_disease_age, 'time': result_disease_time, 'zone': result_disease_zone, 'yll': result_disease_age_yll, 'indicator': indicator}
class TcpTunnel(ImmortalThread): def __init__(self, vcp): #super(TcpTunnel, self).__init__(self) ImmortalThread.__init__(self) self._needs_reconfig = 0 # link to the port object self._vcp = vcp self._lock = Lock() self._op_lock = Lock() # list of operations to apply to an {out|in}bound tcp # segment. In the future this might include operations # such as encryption or compression - for now, only the # header info. that is applied by devices such as # Lantronix's UDS-10 is supported. Up refers to what is # being applied to outbound tcp data, down to received. # Methods should be added to these lists in the order they # are to be applied. self._up_segment_ops = [] self._down_segment_ops = [] # transaction identifier - used only in vcp mode. self.__tid = 0 self._pending_tid = 0 # one and only poll object. socket, serial fd and # command pipe are all polled. self._poll_obj = None # command pipe allows other threads to insert control # messages. self._cmd_pipe = None # both sides (serial & socket) of the tunnel self._sock_listen_fd = None self._sock_fd = None self._serial_port = None # tcp state management self._is_connected = 0 self.is_active = 0 # tunnel statistics self.tcp_bytes_rcvd = 0 self.tcp_bytes_sent = 0 self.serial_bytes_rcvd = 0 self.serial_bytes_sent = 0 self.connection_attempts = 0 def configure(self, config): self.tty = '/dev/tty' + config['dev'][-2:] self.tcp_port = int(config['tcp_port']) self.mode = config['mode'] self.timeout_msec = config['p_timeout_msec'] if self.mode == 'vcp': if self._up_segment_ops.count(self._add_vcp_header) == 0: self._up_segment_ops.append(self._add_vcp_header) if self._down_segment_ops.count(self._remove_vcp_header) == 0: self._down_segment_ops.append(self._remove_vcp_header) self.is_server = int(config['is_server']) if self.is_server == 0: self.host = config['host'] # who we're connecting to. if self.is_active: # tunnel is being reconfigured "in flight". self._needs_reconfig = 1 self._send_cmd('reconfig') if self._is_in_accept(): self._clear_accept() def run(self): self._needs_reconfig = 0 if self.is_active: # we've restarted due to a configuration change self.start_tunnel() else: if not self._cmd_pipe: # set up the command pipe and begin to build the poll obj. self._cmd_pipe = os.pipe() self._poll_obj = select.poll() self._poll_obj.register(self._cmd_pipe[READ], select.POLLIN | select.POLLERR | select.POLLHUP) while 1: # no poll timeout, wait here until kicked to start. evt = self._poll_obj.poll(-1) if evt[0][0] == self._cmd_pipe[READ]: if evt[0][1] == select.POLLIN: cmd = os.read(self._cmd_pipe[READ], 32) if cmd.find('start') >= 0: self.start_tunnel() # cmd pipe poll err, critical, hard restart self._cmd_pipe = None self._poll_obj = None raise ERestart() 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() def stop_tunnel(self): self.is_active = 0 if self is not currentThread(): self._send_cmd('stop') if self._is_in_accept(): self._clear_accept() else: self._op_lock.acquire() try: self._tear_down_fds() finally: self._op_lock.release() #raise ERestart() def is_connected(self): self._op_lock.acquire() result = self._is_connected self._op_lock.release() return result def _create_socket(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) return s def _close_socket(self): self._is_connected = 0 self._sock_fd.close() def _send_cmd(self, cmd): self._lock.acquire() try: os.write(self._cmd_pipe[WRITE], cmd) finally: self._lock.release() def _do_connect(self): while self.is_active: self._sock_fd = self._create_socket() while not self._is_connected: self.connection_attempts += 1 try: self._sock_fd.connect((self.host, self.tcp_port)) self._is_connected = 1 except socket.gaierror, e: # host related error, ie. hostname not resolving - possibly transient self.connection_attempts += 1 msglog.log('VCP', WARN, 'Error resolving hostname %s.' % self.host) time.sleep(60) raise EConnectionError except socket.error, e: # connection error, possibly transient - sleep for a bit and retry self.connection_attempts += 1 time.sleep(30) if self._needs_reconfig: self._is_connected = 0 self._tear_down_fds() raise ERestart() # loop in _do_tunnel until the tcp connection or the framework # based consumer (ie. protocol) "goes away". self._do_tunnel() self._is_connected = 0
def __init__(self, host): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, SERVICE_PORT)) self.port = Port(sock)
def createSplunkContainer(self): port = Port() newPort = port.getNewPort() sp.getoutput( "sudo docker run -dit -p {}:8000 splunk:v4 spl".format(newPort)) return newPort
def create_port_list(self, start_port): port = Port() port_list = port.create_port_list(start_port, self.devices_list) return port_list
def __init__(self): super().__init__() self.port = Port() # draw UI self.initUI()
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)
class MainAPP(QWidget): def __init__(self): super().__init__() self.port = Port() # draw UI self.initUI() def initUI(self): # size and location # self.setGeometry(500, 500, 500, 500) self.resize(500, 400) self.center() self.setWindowTitle("UART") self.setWindowIcon(QIcon("./icon/title.ico")) self.button() self.show() def center(self): window = self.frameGeometry() # 获取中心点 centerPoint = QDesktopWidget().availableGeometry().center() window.moveCenter(centerPoint) # self.move(window.topLeft()) def button(self): self.spectrum = QPushButton("Spectrum") self.spectrum.clicked.connect(self.spectrumAction) # self.spectrum.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) self.colorMap = QPushButton("ColorMap") self.colorMap.clicked.connect(self.colorMapAction) # self.colorMap.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) self.adc = QPushButton("ADC") self.adc.clicked.connect(self.adcAction) self.statusBox = QLabel() self.statusBox.setText(self.statusText()) self.statusBox.setAlignment(QtCore.Qt.AlignCenter) self.connection = QPushButton('连接串口') self.connection.clicked.connect(self.connect) self.setting = QPushButton('串口设置') self.setting.clicked.connect(self.settingAction) vbox = QVBoxLayout() vbox.addWidget(self.adc) vbox.addWidget(self.spectrum) vbox.addWidget(self.colorMap) hbox = QHBoxLayout() # hbox.addStretch(1) hbox.addLayout(vbox) vbox2 = QVBoxLayout() vbox2.addStretch(1) vbox2.addWidget(self.statusBox) vbox2.addStretch(1) vbox2.addWidget(self.connection) vbox2.addWidget(self.setting) vbox2.addStretch(1) hbox.addLayout(vbox2) # hbox.addStretch(1) self.setLayout(hbox) def statusText(self): status = '当前配置\n波特率 ' + \ str(self.port.bandradte) + '\n停止位 1\nADC数据接收类型 uint8\nADC采样精度 8bit' return status def spectrumAction(self): if self.spectrum.isEnabled(): # print("yes") self.port.spectrum_one_figure() # self.spectrum.setEnabled(False) def colorMapAction(self): if self.spectrum.isEnabled(): self.port.colormap() def adcAction(self): self.ADC_Window = adcWindow(self.port) self.ADC_Window.show() # QtWidgets.QFileDialog.getExistingDirectory(self, "@2", "./") def connect(self): if (self.port.ser is None or self.port.ser.isOpen() is False): self.port.openPort() if (self.port.ser.isOpen()): QMessageBox.information(self, '提示', '连接成功', QMessageBox.Ok) def settingAction(self): # QMessageBox.information(self, '提示', '正在建设', QMessageBox.Ok) self.settings = Settings(self.port) self.settings.show() @staticmethod def refresh(): QApplication.processEvents()
def _finish_init_(self): for p in self._obj.ports: self._children.append(Port(p, self, self._outbox))
cv2.putText(frame, s, (width+30,50), cv2.FONT_HERSHEY_PLAIN, 1, BLACK, 2) cv2.imshow("output", frame) def getMiddle(x, y): return ((x[0] + y[0]) / 2, (x[1] + y[1]) / 2) mx = [] my = [] if __name__ == '__main__': cv2.namedWindow('output') cv2.setMouseCallback('output', clickHandler) port = Port() port.init() lasttimeSent = None prevRobot = [None] * N prevWhite = [None] * N vc = cv2.VideoCapture(1) balls = None rval, frame = vc.read() while rval: rval, frame = vc.read() robots = [None] * N whites = [None] * N