Creates a new session.

        :param server_host: IP address of the server
        :param server_port: Server port
        :return: A new `BaitSession` object.
163838
def create_session(self, server_host, server_port, honeypot_id):
        
        protocol = self.__class__.__name__.lower()
        session = BaitSession(protocol, server_host, server_port, honeypot_id)
        self.sessions[session.id] = session
        return session
299468
def server_bind(self):
        
        TCPServer.server_bind(self)
        host, port = self.socket.getsockname()[:2]
        self.server_port = port
        try:
            self.server_name = socket.getfqdn(host)
        except ValueError:
            # Use the local host name in case of error, like CPython does
            self.server_name = socket.gethostname()
245374
def _server_known(cls, host, port):
        
        with PostgreSql._known_servers_lock:
            return (host, port) in PostgreSql._known_servers
1287871
def listen(self, *, host, port, override=False, forever=False, **kwargs):
        
        if override:
            argv = dict(enumerate(sys.argv))
            host = argv.get(1, host)
            port = int(argv.get(2, port))
        server = self.loop.create_server(
            self.__handler.fork, host, port, **kwargs)
        server = self.loop.run_until_complete(server)
        self.log('info',
            'Start listening host="{host}" port="{port}"'.
            format(host=host, port=port))
        if forever:
            try:
                self.loop.run_forever()
            except KeyboardInterrupt:
                pass
        return server
836151
def start(self):
        
        password = self.options['password']
        server_host = self.options['server']
        server_port = self.options['port']
        honeypot_id = self.options['honeypot_id']

        session = self.create_session(server_host, server_port, honeypot_id)
        self.sessions[session.id] = session

        logger.debug(
            'Sending {0} bait session to {1}:{2}. (bait id: {3})'.format('vnc', server_host, server_port, session.id))
        client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            client_socket.connect((server_host, int(server_port)))
            session.source_port = client_socket.getsockname()[1]

        except socket.error as e:
            logger.debug('Caught exception: {0} ({1})'.format(e, str(type(e))))
        else:
            session.did_connect = True
            protocol_version = client_socket.recv(1024)
            client_socket.send(RFB_VERSION)
            supported_auth_methods = client_socket.recv(1024)

            # \x02 implies that VNC authentication method is to be used
            # Refer to http://tools.ietf.org/html/rfc6143#section-7.1.2 for more info.
            if '\x02' in supported_auth_methods:
                client_socket.send(VNC_AUTH)
            challenge = client_socket.recv(1024)

            # password limit for vnc in 8 chars
            aligned_password = (password + '\0' * 8)[:8]
            des = RFBDes(aligned_password)
            response = des.encrypt(challenge)

            client_socket.send(response)
            auth_status = client_socket.recv(1024)
            if auth_status == AUTH_SUCCESSFUL:
                session.add_auth_attempt('des_challenge', True, password=aligned_password)
                session.did_login = True
            else:
                session.add_auth_attempt('des_challenge', False, password=aligned_password)
                session.did_login = False
            session.did_complete = True

        finally:
            session.alldone = True
            session.end_session()
            if client_socket:
                client_socket.close()
690693
def _create_server(host, port):
    

    exc = socket.error("getaddrinfo returns an empty list")
    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
        af, socktype, proto, canonname, sa = res
        sock = None
        try:
            # Create the listening socket
            sock = socket.socket(af, socktype, proto)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.bind(sa)
            sock.listen(1024)
            return sock

        except socket.error as exc:
            # Clean up after ourselves
            if sock is not None:
                sock.close()

    # Couldn't create a listening socket
    raise exc
1288907
def sessions_info(self, hosts):
        
        info_by_id = {}

        for server_endpoint, dump in self.dump_by_server(hosts).items():
            server_ip, server_port = server_endpoint
            for line in dump.split("\n"):
                mat = self.IP_PORT_REGEX.match(line)
                if mat is None:
                    continue
                ip, port, sid = mat.groups()
                info_by_id[sid] = ClientInfo(sid, ip, port, server_ip, server_port)

        return info_by_id
523323
def connect(self, host, port):
        ''''''
        conn = connection.Connection(host, port,
            reconnection_backoff=self._reconnection_backoff,
            auth_secret=self._auth_secret,
            timeout=self._connect_timeout,
            **self._identify_options)
        if conn.alive():
            conn.setblocking(0)
        self.add(conn)
        return conn
498619
async def create_connection(self, address=None, protocol_factory=None,
                                **kwargs):
        
        loop = self._loop
        protocol_factory = protocol_factory or self.create_protocol
        if isinstance(address, tuple):
            kwargs['host'] = address[0]
            kwargs['port'] = address[1]
        _, protocol = await loop.create_connection(protocol_factory, **kwargs)
        event = protocol.event('connection_made')
        if not event.fired():
            await event.waiter()
        return protocol
1059878
def create_tcp_socket (self, host):
        """"""
        port = int(self['TCPSocket'])
        sockinfo = get_sockinfo(host, port=port)
        sock = create_socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            sock.connect(sockinfo[0][4])
        except socket.error:
            sock.close()
            raise
        return sock
530404
def add_server(self, name, ip, port):
        """"""
        new_server = {
            'key': name,  # Zeroconf name with both hostname and port
            'name': name.split(':')[0],  # Short name
            'ip': ip,  # IP address seen by the client
            'port': port,  # TCP port
            'username': 'glances',  # Default username
            'password': '',  # Default password
            'status': 'UNKNOWN',  # Server status: 'UNKNOWN', 'OFFLINE', 'ONLINE', 'PROTECTED'
            'type': 'DYNAMIC'}  # Server type: 'STATIC' or 'DYNAMIC'
        self._server_list.append(new_server)
        logger.debug("Updated servers list (%s servers): %s" %
                     (len(self._server_list), self._server_list))
598537
private MBeanServerConnection createServerConnection(String host, int port) throws IOException {
            jmxServiceURL = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi");
            JMXConnector jmxc = JMXConnectorFactory.connect(jmxServiceURL, null);
            return jmxc.getMBeanServerConnection();            
    }
316577
def create(host, port, result_converter=None, testcase_converter=None, args=None):
    
    return SampleClient(host, port, result_converter, testcase_converter, args)
629174
def serve_service_on_host_and_port(host, port)
      # log information
      logger.info('Running service on ' + (host == '' ? '<any>' : host) + ':' + port.to_s)
      # instantiate the service for host and port
      # if host is empty "" wildcard (all) interfaces are used
      # otherwise it will be bind to single host ip only
      tcp_server = TCPServer.new(host, port)
      # append this server to the list of TCPServers
      @tcp_servers << tcp_server

      # run thread until shutdown
      @tcp_server_threads << Thread.new do
        begin
          # always check for shutdown request
          until shutdown?
            # get new client and start additional thread
            # to handle client process
            client = tcp_server.accept
            Thread.new(client) do |io|
              # add to list of connections
              @connections << Thread.current
              # handle connection
              begin
                # initialize a session storage hash
                Thread.current[:session] = {}
                # process smtp service on io socket
                io = serve_client(Thread.current[:session], io)
                # save returned io value due to maybe
                # established ssl io socket
              rescue SmtpdStopConnectionException
                # ignore this exception due to service shutdown
              rescue StandardError => e
                # log fatal error while handling connection
                logger.fatal(e.backtrace.join("\n"))
              ensure
                begin
                  # always gracefully shutdown connection.
                  # if the io object was overriden by the
                  # result from serve_client() due to ssl
                  # io, the ssl + io socket will be closed
                  io.close
                rescue StandardError
                  # ignore any exception from here
                end
                # remove closed session from connections
                @connections_mutex.synchronize do
                  # drop this thread from connections
                  @connections.delete(Thread.current)
                  # drop this thread from processings
                  @processings.delete(Thread.current)
                  # signal mutex for next waiting thread
                  @connections_cv.signal
                end
              end
            end
          end
        rescue SmtpdStopServiceException
          # ignore this exception due to service shutdown
        rescue StandardError => e
          # log fatal error while starting new thread
          logger.fatal(e.backtrace.join("\n"))
        ensure
          begin
            # drop the service
            tcp_server.close
            # remove from list
            @tcp_servers.delete(tcp_server)
            # reset local var
            tcp_server = nil
          rescue StandardError
            # ignor any error from here
          end
          if shutdown?
            # wait for finishing opened connections
            @connections_mutex.synchronize do
              @connections_cv.wait(@connections_mutex) until @connections.empty?
            end
          else
            # drop any open session immediately
            @connections.each { |c| c.raise SmtpdStopConnectionException }
          end
          # remove this thread from list
          @tcp_server_threads.delete(Thread.current)
        end
      end
    end
435832
def create_session(self, ticket, payload=None, expires=None):
        '''
        
        '''
        assert isinstance(self.session_storage_adapter, CASSessionAdapter)
        logging.debug('[CAS] Creating session for ticket {}'.format(ticket))
        self.session_storage_adapter.create(
            ticket,
            payload=payload,
            expires=expires,
            )
1106976
def connection_from_host(self, host, port=80, scheme='http'):
        
        pool_key = (scheme, host, port)

        # If the scheme, host, or port doesn't match existing open connections,
        # open a new ConnectionPool.
        pool = self.pools.get(pool_key)
        if pool:
            return pool

        # Make a fresh ConnectionPool of the desired type
        pool_cls = pool_classes_by_scheme[scheme]
        pool = pool_cls(host, port, **self.connection_pool_kw)

        self.pools[pool_key] = pool

        return pool
601083
def addServer(self, normalPort, sslPort, f, name):
        
        tcp = internet.TCPServer(normalPort, f)
        tcp.setName(name)
        self.servers.append(tcp)
        if sslPort is not None:
            ssl = internet.SSLServer(sslPort, f, contextFactory=self.sslfac)
            ssl.setName(name+'s')
            self.servers.append(ssl)