Search port names and numbers.
483845
def run(port, like, use_json, server):
    """"""
    if not port and not server[0]:
        raise click.UsageError("Please specify a port")

    if server[0]:
        app.run(host=server[0], port=server[1])
        return

    ports = get_ports(port, like)
    if not ports:
        sys.stderr.write("No ports found for '{0}'\n".format(port))
        return

    if use_json:
        print(json.dumps(ports, indent=4))
    else:
        table = get_table(ports)
        print(table)
139221
def _translate_port(port):
    '''
    
    '''
    services = _get_services_mapping()
    if port in services and services[port]['port']:
        return services[port]['port'][0]
    return port
1019658
def show_port(self, port, **_params):
        """"""
        return self.get(self.port_path % (port), params=_params)
856894
def _discover_port(self):
        
        # if MAC get list of ports
        if sys.platform.startswith('darwin'):
            locations = glob.glob('/dev/tty.[usb*]*')
            locations = glob.glob('/dev/tty.[wchusb*]*') + locations
            locations.append('end')
        # for everyone else, here is a list of possible ports
        else:
            locations = ['/dev/ttyACM0', '/dev/ttyACM1',
                         '/dev/ttyACM2', '/dev/ttyACM3', '/dev/ttyACM4',
                         '/dev/ttyACM5', '/dev/ttyUSB0', '/dev/ttyUSB1',
                         '/dev/ttyUSB2', '/dev/ttyUSB3', '/dev/ttyUSB4',
                         '/dev/ttyUSB5', '/dev/ttyUSB6', '/dev/ttyUSB7',
                         '/dev/ttyUSB8', '/dev/ttyUSB9',
                         '/dev/ttyUSB10',
                         '/dev/ttyS0', '/dev/ttyS1', '/dev/ttyS2',
                         '/dev/tty.usbserial', '/dev/tty.usbmodem', 'com2',
                         'com3', 'com4', 'com5', 'com6', 'com7', 'com8',
                         'com9', 'com10', 'com11', 'com12', 'com13',
                         'com14', 'com15', 'com16', 'com17', 'com18',
                         'com19', 'com20', 'com21', 'com1', 'end'
                         ]

        detected = None
        for device in locations:
            try:
                serialport = serial.Serial(device, 57600, timeout=0)
                detected = device
                serialport.close()
                break
            except serial.SerialException:
                if device == 'end':
                    if self.log_output:
                        logging.exception(
                            'Unable to find Serial Port, Please plug in '
                            'cable or check cable connections.')
                    else:
                        print('Unable to find Serial Port, Please plug in '
                              'cable or check cable connections.')
                    sys.exit()
        if self.log_output:
            log_string = 'Using COM Port: ' + detected
            logging.info(log_string)
        else:
            print('{}{}\n'.format('Using COM Port:', detected))
        return detected
27302
async def scan_for_units(self, iprange):
        """"""
        units = []
        for ip_address in ipaddress.IPv4Network(iprange):
            sock = socket.socket()
            sock.settimeout(0.02)
            host = str(ip_address)
            try:
                scan_result = sock.connect((host, PORT))
            except socket.error:
                scan_result = 1
            _LOGGER.debug('Checking port connectivity on %s:%s',
                          host, (str(PORT)))
            if scan_result is None:
                ghlocalapi = DeviceInfo(self._loop, self._session, host)
                await ghlocalapi.get_device_info()
                data = ghlocalapi.device_info
                if data is not None:
                    cap = data['device_info']['capabilities']
                    units.append({
                        'host': host,
                        'name': data['name'],
                        'model': data['device_info']['model_name'],
                        'assistant_supported': cap.get('assistant_supported',
                                                       False)
                    })
            sock.close()
        return units
505144
def __find(self, name):
        
        port = None
        if not len(self.__ports):
            raise Exception('No ports defined: %s' % self.__qn)
        if isinstance(name, int):
            qn = '%s[%d]' % (self.__qn, name)
            try:
                port = self.__ports[name]
            except IndexError:
                raise PortNotFound(qn)
        else:
            qn = '.'.join((self.__qn, name))
            for p in self.__ports:
                if name == p.name:
                    port = p
                    break
        if port is None:
            raise PortNotFound(qn)
        qn = '.'.join((self.__qn, port.name))
        return MethodSelector(self.__client, port.methods, qn)
40447
def getPorts(self):
        """"""
        if self.ports: # no need to get ports if ports are al
            return self.ports
        if not self._gotPorts:
            self.ports = [
                portpicker.pick_unused_port(), # game_port
                portpicker.pick_unused_port(), # base_port
                portpicker.pick_unused_port(), # shared_port / init port
            ]
            self._gotPorts = True
        return self.ports
917696
def filter_unbound_ports(query):
    """"""
    # hack for pep8 E711: comparison to None should be
    # 'if cond is not None'
    none = None
    port_model = models_v2.Port
    binding_level_model = ml2_models.PortBindingLevel
    query = (query
             .join_if_necessary(port_model)
             .join_if_necessary(binding_level_model)
             .filter(
                 binding_level_model.host != '',
                 port_model.device_id != none,
                 port_model.network_id != none))
    return query
280806
def detect_port(port):
    ''''''
    socket_test = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    try:
        socket_test.connect(('127.0.0.1', int(port)))
        socket_test.close()
        return True
    except:
        return False
1004534
def _port_scan(self, port):
        """"""
        if int(port['port']) == 0:
            return self._port_scan_icmp(port)
        else:
            return self._port_scan_tcp(port)
1076562
def _do_search(conf):
    '''
    
    '''
    # Build LDAP connection args
    connargs = {}
    for name in ['server', 'port', 'tls', 'binddn', 'bindpw', 'anonymous']:
        connargs[name] = _config(name, conf)
    if connargs['binddn'] and connargs['bindpw']:
        connargs['anonymous'] = False
    # Build search args
    try:
        _filter = conf['filter']
    except KeyError:
        raise SaltInvocationError('missing filter')
    _dn = _config('dn', conf)
    scope = _config('scope', conf)
    _lists = _config('lists', conf) or []
    _attrs = _config('attrs', conf) or []
    _dict_key_attr = _config('dict_key_attr', conf, 'dn')
    attrs = _lists + _attrs + [_dict_key_attr]
    if not attrs:
        attrs = None
    # Perform the search
    try:
        result = __salt__['ldap.search'](_filter, _dn, scope, attrs,
                                         **connargs)['results']
    except IndexError:  # we got no results for this search
        log.debug('LDAP search returned no results for filter %s', _filter)
        result = {}
    except Exception:
        log.critical(
            'Failed to retrieve pillar data from LDAP:\n', exc_info=True
        )
        return {}
    return result
874246
def ports_as_list(port_str):
    
    if not port_str:
        LOGGER.info("Invalid port value")
        return [None, None]

    if ports_str_check_failed(port_str):
        LOGGER.info("{0}: Port list malformed.")
        return [None, None]

    tcp_list = list()
    udp_list = list()
    ports = port_str.replace(' ', '')
    b_tcp = ports.find("T")
    b_udp = ports.find("U")

    if ports[b_tcp - 1] == ',':
        ports = ports[:b_tcp - 1] + ports[b_tcp:]
    if ports[b_udp - 1] == ',':
        ports = ports[:b_udp - 1] + ports[b_udp:]
    ports = port_str_arrange(ports)

    tports = ''
    uports = ''
    # TCP ports listed first, then UDP ports
    if b_udp != -1 and b_tcp != -1:
        tports = ports[ports.index('T:') + 2:ports.index('U:')]
        uports = ports[ports.index('U:') + 2:]
    # Only UDP ports
    elif b_tcp == -1 and b_udp != -1:
        uports = ports[ports.index('U:') + 2:]
    # Only TCP ports
    elif b_udp == -1 and b_tcp != -1:
        tports = ports[ports.index('T:') + 2:]
    else:
        tports = ports

    if tports:
        for port in tports.split(','):
            if '-' in port:
                tcp_list.extend(port_range_expand(port))
            else:
                tcp_list.append(int(port))
        tcp_list.sort()
    if uports:
        for port in uports.split(','):
            if '-' in port:
                udp_list.extend(port_range_expand(port))
            else:
                udp_list.append(int(port))
        udp_list.sort()

    return (tcp_list, udp_list)
505359
def list_devices(names=None, continue_from=None, **kwargs):
    """"""

    if not names:
        names = [device for device, _type in settings.GOLDEN_DEVICES if _type == 'OpenThread']

    if continue_from:
        continue_from = names.index(continue_from)
    else:
        continue_from = 0

    for port in names[continue_from:]:
        try:
            with OpenThreadController(port) as otc:
                print('%s: %s' % (port, otc.version))
        except:
            logger.exception('failed to get version of %s' % port)
643595
def port_number(port):
    
    try:
        port = int(port)
    except ValueError:
        raise ValueError("Bad port number")
    if not 0 <= port < 2 ** 16:
        raise ValueError("Bad port number")
    return port
1191262
def get_tags_of_port(self, port):
        
        return(sorted([tag for tag in self.cluster_tags
                       if port in self.cluster_tags[tag]]))
428936
def scan_results(self, obj):
        """"""

        avail_network_list = pointer(WLAN_AVAILABLE_NETWORK_LIST())
        self._wlan_get_available_network_list(self._handle,
            byref(obj['guid']), byref(avail_network_list))
        networks = cast(avail_network_list.contents.Network,
                     POINTER(WLAN_AVAILABLE_NETWORK))

        self._logger.debug("Scan found %d networks.",
            avail_network_list.contents.dwNumberOfItems)

        network_list = []
        for i in range(avail_network_list.contents.dwNumberOfItems):

            if networks[i].dot11BssType == 1 and networks[i].bNetworkConnectable :

                ssid = ''
                for j in range(networks[i].dot11Ssid.uSSIDLength):

                    if networks[i].dot11Ssid.ucSSID != b'':
                        ssid += "%c" % networks[i].dot11Ssid.ucSSID[j]

                bss_list = pointer(WLAN_BSS_LIST())
                self._wlan_get_network_bss_list(self._handle,
                    byref(obj['guid']), byref(bss_list), networks[i].dot11Ssid, networks[i].bSecurityEnabled)
                bsses = cast(bss_list.contents.wlanBssEntries,
                             POINTER(WLAN_BSS_ENTRY))

                if networks[i].bSecurityEnabled:
                    akm = self._get_akm(networks[i].dot11DefaultCipherAlgorithm)
                    auth_alg = self._get_auth_alg(networks[i].dot11DefaultAuthAlgorithm)
                else:
                    akm = [AKM_TYPE_NONE]
                    auth_alg = [AUTH_ALG_OPEN]

                for j in range(bss_list.contents.dwNumberOfItems):
                    network = Profile()

                    network.ssid = ssid

                    network.bssid = ''
                    for k in range(6):
                        network.bssid += "%02x:" % bsses[j].dot11Bssid[k]

                    network.signal = bsses[j].lRssi
                    network.freq = bsses[j].ulChCenterFrequency
                    network.auth = auth_alg
                    network.akm = akm
                    network_list.append(network)

        return network_list
351003
def get_local_urls(port):
    ''''''
    url_list = []
    for name, info in psutil.net_if_addrs().items():
        for addr in info:
            if AddressFamily.AF_INET == addr.family:
                url_list.append('http://{}:{}'.format(addr.address, port))
    return url_list