Run wireshark on a list of packets
7520
def wireshark(pktlist, *args):
    """"""
    fname = get_temp_file()
    wrpcap(fname, pktlist)
    subprocess.Popen([conf.prog.wireshark, "-r", fname] + list(args))
846488
def _on_open(self, _):
        """"""
        nick = self._format_nick(self._nick, self._pwd)
        data = {"cmd": "join", "channel": self._channel, "nick": nick}
        self._send_packet(data)
        self._thread = True
        threading.Thread(target=self._ping).start()
741039
def run(self, address, port, unix_path):
        
        assert address or unix_path
        if unix_path:
            sock = bind_unix_socket(unix_path)
        else:
            sock = bind_socket(address, port)
        if sock is None:
            return False

        sock.setblocking(False)
        inputs = [sock]
        outputs = []
        try:
            while True:
                readable, _, _ = select.select(
                    inputs, outputs, inputs, SCHEDULER_CHECK_PERIOD)
                for r_socket in readable:
                    if unix_path and r_socket is sock:
                        client_stream, _ = sock.accept()
                        logger.debug("New connection from %s", unix_path)
                        self.handle_client_stream(client_stream, True)
                    else:
                        client_stream = self.new_client_stream(sock)
                        if client_stream is None:
                            continue
                        self.handle_client_stream(client_stream, False)
                    close_client_stream(client_stream, unix_path)
                self.scheduler()
        except KeyboardInterrupt:
            logger.info("Received Ctrl-C shutting-down ...")
        finally:
            sock.shutdown(socket.SHUT_RDWR)
            sock.close()
295942
def pull(self):
        """"""

        # For each packet in the pcap process the contents
        for item in self.input_stream:

            # Print out the timestamp in UTC
            print('Timestamp: %s' % item['timestamp'])

            # Unpack the Ethernet frame (mac src/dst, ethertype)
            print('Ethernet Frame: %s --> %s  (type: %d)' % \
                  (net_utils.mac_to_str(item['eth']['src']), net_utils.mac_to_str(item['eth']['dst']), item['eth']['type']))

            # Print out the Packet info
            packet_type = item['packet']['type']
            print('Packet: %s ' % packet_type, end='')
            packet = item['packet']
            if packet_type in ['IP', 'IP6']:
                print('%s --> %s (len:%d ttl:%d)' % (net_utils.inet_to_str(packet['src']), net_utils.inet_to_str(packet['dst']),
                                                     packet['len'], packet['ttl']), end='')
                if packet_type == 'IP':
                    print('-- Frag(df:%d mf:%d offset:%d)' % (packet['df'], packet['mf'], packet['offset']))
                else:
                    print()
            else:
                print(str(packet))

            # Print out transport and application layers
            if item['transport']:
                transport_info = item['transport']
                print('Transport: %s ' % transport_info['type'], end='')
                for key, value in compat.iteritems(transport_info):
                    if key != 'data':
                        print(key+':'+repr(value), end=' ')

                # Give summary info about data
                data = transport_info['data']
                print('\nData: %d bytes' % len(data), end='')
                if data:
                    print('(%s...)' % repr(data)[:30])
                else:
                    print()

            # Application data
            if item['application']:
                print('Application: %s' % item['application']['type'], end='')
                print(str(item['application']))

            # Is there domain info?
            if 'src_domain' in packet:
                print('Domains: %s --> %s' % (packet['src_domain'], packet['dst_domain']))

            # Tags
            if 'tags' in item:
                print(list(item['tags']))
            print()
369002
function list(req, res) {
  var s = '';
  this.state.connections.forEach(function(conn) {
    s += conn.toString();
  })
  res.send(null, s);
}
193699
def sendline(sock, msg, confidential=False):
    """"""
    log.debug('<- %r', ('<snip>' if confidential else msg))
    sock.sendall(msg + b'\n')
1066063
def _receiving(self):
        
        while self._is_running:
            try:
                rlist, wlist, xlist = select.select(
                    self._listening, [], [],
                    self._select_timeout
                )
            except:
                self.exception("Failed to select socket")
                continue
            for sock in rlist:
                try:
                    self._get_packet(sock)
                except:
                    self.exception("Failed to receive packet")
1141801
def p_portlist_io(self, p):
        ''
        p[0] = Portlist(ports=p[2], lineno=p.lineno(1))
        p.set_lineno(0, p.lineno(1))
15014
def check_whitelist(values):
    """"""
    import os
    import tldextract
    whitelisted = list()
    for name in ['alexa.txt', 'cisco.txt']:
        config_path = os.path.expanduser('~/.config/blockade')
        file_path = os.path.join(config_path, name)
        whitelisted += [x.strip() for x in open(file_path, 'r').readlines()]
    output = list()
    for item in values:
        ext = tldextract.extract(item)
        if ext.registered_domain in whitelisted:
            continue
        output.append(item)
    return output
714310
def execute_with(host_list, options = {}, &block)
      host_list.each { |host| @connections[host] ||= LazyConnection.new(host, @net_ssh_options) }
      args = options[:args] || []
      num_threads = options[:num_threads] || DEFAULT_THREAD_POOL_SIZE
      if options[:serial]
        host_list.each { |host| @connections[host].self_eval args, &block }
      elsif options[:batch_by]
        num_threads = options[:batch_by] if num_threads == :unlimited
        host_list.each_slice(options[:batch_by]) do |batch|
          Weave.with_thread_pool(batch, num_threads) do |host, mutex|
            @connections[host].self_eval args, mutex, &block
          end
        end
      else
        num_threads = host_list.size if num_threads == :unlimited
        Weave.with_thread_pool(host_list, num_threads) do |host, mutex|
          @connections[host].self_eval args, mutex, &block
        end
      end
    end
1214379
def _build_connstr(host, port, bucket):
    
    hostlist = []
    if isinstance(host, (tuple, list)):
        for curhost in host:
            if isinstance(curhost, (list, tuple)):
                hostlist.append(_fmthost(*curhost))
            else:
                hostlist.append(curhost)
    else:
        hostlist.append(_fmthost(host, port))

    return 'http://{0}/{1}'.format(','.join(hostlist), bucket)
890186
async def poll(self):
        """"""
        try:
            packets = [await asyncio.wait_for(self.queue.get(),
                                              self.server.ping_timeout)]
            self.queue.task_done()
        except (asyncio.TimeoutError, asyncio.CancelledError):
            raise exceptions.QueueEmpty()
        if packets == [None]:
            return []
        try:
            packets.append(self.queue.get_nowait())
            self.queue.task_done()
        except asyncio.QueueEmpty:
            pass
        return packets
534249
def parse_raw_list_data(data, proxy_type='http', proxy_userpwd=None):
    """"""
    if not isinstance(data, six.text_type):
        data = data.decode('utf-8')
    for orig_line in data.splitlines():
        line = orig_line.strip().replace(' ', '')
        if line and not line.startswith('#'):
            try:
                host, port, username, password = parse_proxy_line(line)
            except InvalidProxyLine as ex:
                logger.error(ex)
            else:
                if username is None and proxy_userpwd is not None:
                    username, password = proxy_userpwd.split(':')
                yield Proxy(host, port, username, password, proxy_type)
340632
def _send_command_list(self, commands):
        """"""
        output = ""
        for command in commands:
            output += self.device.send_command(
                command, strip_prompt=False, strip_command=False
            )
        return output
1301232
def send(self, out, addr=_MDNS_ADDR, port=_MDNS_PORT):
        """"""
        # This is a quick test to see if we can parse the packets we generate
        #temp = DNSIncoming(out.packet())
        for i in self.intf.values():
            try:
                return i.sendto(out.packet(), 0, (addr, port))
            except:
                traceback.print_exc()
                # Ignore this, it may be a temporary loss of network connection
                return -1
1018316
def (self):
        """"""

        archive_data = {"packets": self.recv_msgs,
                        "dataset": self.dataset_name,
                        "num_packets": len(self.recv_msgs),
                        "created": rnow()}
        self.write_to_file(archive_data,
                           self.archive_file)
1306716
def start_recv(sockfile=None):
    ''''''

    if sockfile is not None:
        SOCKFILE = sockfile
    else:
        # default sockfile
        SOCKFILE = "/tmp/snort_alert"

    if os.path.exists(SOCKFILE):
        os.unlink(SOCKFILE)
    unsock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
    unsock.bind(SOCKFILE)
    logging.warning('Unix socket start listening...')
    while True:
        data = unsock.recv(BUFSIZE)
        parsed_msg = alert.AlertPkt.parser(data)
        if parsed_msg:
            yield parsed_msg