def run(): import optparse parser = optparse.OptionParser( usage='usage: %prog [options] (webirc server)') parser.add_option('-d', '--debug', action="store_true", dest="debug", default=False, help="debug [default: %default]") parser.add_option('-i', '--interface', dest="interface", default="127.0.0.1", help="interface to listen on [default: %default]") parser.add_option('-p', '--port', dest="port", type="int", default=6667, help="port to listen on [default: %default]") options, args = parser.parse_args() if not args: parser.print_usage() else: if options.debug: import sys import twisted.python.log twisted.python.log.startLogging(sys.stdout) f = protocol.ServerFactory() f.protocol = IRCRelay f.host = args[0].rstrip('/') + '/' reactor.listenTCP(options.port, f, interface=options.interface) print "Listening for connections to relay to %s on %s:%i" % ( f.host, options.interface, options.port) reactor.run()
def _runTest(self, clientProto, serverProto, clientIsServer=False): """ Helper method to run TLS tests. @param clientProto: protocol instance attached to the client connection. @param serverProto: protocol instance attached to the server connection. @param clientIsServer: flag indicated if client should initiate startTLS instead of server. @return: a L{defer.Deferred} that will fire when both connections are lost. """ self.clientProto = clientProto cf = self.clientFactory = protocol.ClientFactory() cf.protocol = lambda: clientProto if clientIsServer: cf.server = False else: cf.client = True self.serverProto = serverProto sf = self.serverFactory = protocol.ServerFactory() sf.protocol = lambda: serverProto if clientIsServer: sf.client = False else: sf.server = True port = reactor.listenTCP(0, sf, interface="127.0.0.1") self.addCleanup(port.stopListening) reactor.connectTCP('127.0.0.1', port.getHost().port, cf) return defer.gatherResults( [clientProto.deferred, serverProto.deferred])
def test_loggingFactoryOpensLogfileAutomatically(self): """ When the L{policies.TrafficLoggingFactory} builds a protocol, it automatically opens a unique log file for that protocol and attaches the logfile to the built protocol. """ open_calls = [] open_rvalues = [] def mocked_open(*args, **kwargs): """ Mock for the open call to prevent actually opening a log file. """ open_calls.append((args, kwargs)) io = StringIO() io.name = args[0] open_rvalues.append(io) return io self.patch(builtins, "open", mocked_open) wrappedFactory = protocol.ServerFactory() wrappedFactory.protocol = SimpleProtocol factory = policies.TrafficLoggingFactory(wrappedFactory, "test") first_proto = factory.buildProtocol( address.IPv4Address("TCP", "127.0.0.1", 12345) ) second_proto = factory.buildProtocol( address.IPv4Address("TCP", "127.0.0.1", 12346) ) # We expect open to be called twice, with the files passed to the # protocols. first_call = (("test-1", "w"), {}) second_call = (("test-2", "w"), {}) self.assertEqual([first_call, second_call], open_calls) self.assertEqual([first_proto.logfile, second_proto.logfile], open_rvalues)
def testVolatile(self): if not interfaces.IReactorUNIX(reactor, None): raise unittest.SkipTest, "This reactor does not support UNIX domain sockets" factory = protocol.ServerFactory() factory.protocol = wire.Echo t = internet.UNIXServer('echo.skt', factory) t.startService() self.failIfIdentical(t._port, None) t1 = copy.copy(t) self.assertIdentical(t1._port, None) t.stopService() self.assertIdentical(t._port, None) self.failIf(t.running) factory = protocol.ClientFactory() factory.protocol = wire.Echo t = internet.UNIXClient('echo.skt', factory) t.startService() self.failIfIdentical(t._connection, None) t1 = copy.copy(t) self.assertIdentical(t1._connection, None) t.stopService() self.assertIdentical(t._connection, None) self.failIf(t.running)
def StartServer(log=None): if IMPORT_TWISTED == False: log.EcritLog(_(u"Erreur : Problème d'importation de Twisted")) return try: factory = protocol.ServerFactory() factory.protocol = Echo factory.protocol.log = log reactor.registerWxApp(wx.GetApp()) port = int( UTILS_Config.GetParametre("synchro_serveur_port", defaut=PORT_DEFAUT)) reactor.listenTCP(port, factory) # IP locale #ip_local = socket.gethostbyname(socket.gethostname()) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('jsonip.com', 80)) ip_local = s.getsockname()[0] s.close() log.EcritLog(_(u"IP locale : %s") % ip_local) # IP internet ip_internet = json.loads(urlopen("http://jsonip.com").read())["ip"] log.EcritLog(_(u"IP internet : %s") % ip_internet) # Port log.EcritLog(_(u"Serveur prêt sur le port %d") % port) log.SetImage("on") reactor.run() except Exception, err: print("Erreur lancement serveur nomade :", err) log.EcritLog(_(u"Erreur dans le lancement du serveur Nomadhys :")) log.EcritLog(err)
def test_portforward(self): """ Test port forwarding through Echo protocol. """ realServerFactory = protocol.ServerFactory() realServerFactory.protocol = lambda: self.serverProtocol realServerPort = reactor.listenTCP(0, realServerFactory, interface='127.0.0.1') self.openPorts.append(realServerPort) self.proxyServerFactory = TestableProxyFactory('127.0.0.1', realServerPort.getHost().port) proxyServerPort = reactor.listenTCP(0, self.proxyServerFactory, interface='127.0.0.1') self.openPorts.append(proxyServerPort) nBytes = 1000 received = [] d = defer.Deferred() def testDataReceived(data): received.extend(data) if len(received) >= nBytes: self.assertEquals(''.join(received), 'x' * nBytes) d.callback(None) self.clientProtocol.dataReceived = testDataReceived def testConnectionMade(): self.clientProtocol.transport.write('x' * nBytes) self.clientProtocol.connectionMade = testConnectionMade clientFactory = protocol.ClientFactory() clientFactory.protocol = lambda: self.clientProtocol reactor.connectTCP( '127.0.0.1', proxyServerPort.getHost().port, clientFactory) return d
def connect(self): self.numCorners = 0 win = self.get_parent_window() # SETUP self.flip = False self.real_start_y = 12 self.real_height = -24 self.real_start_x = -20 #self.real_start_x = 0 self.real_width = 20 print self.real_height, self.real_width self._ready = False self._corners = [] self.factory = protocol.ServerFactory() self.factory.protocol = TrackingClient self.factory.clients = [] reactor.listenTCP(1025, self.factory)
def testImmediateDisconnect(self): org = "twisted.test.test_ssl" self.setupServerAndClient((org, org + ", client"), {}, (org, org + ", server"), {}) # Set up a server, connect to it with a client, which should work since our verifiers # allow anything, then disconnect. serverProtocolFactory = protocol.ServerFactory() serverProtocolFactory.protocol = protocol.Protocol self.serverPort = serverPort = reactor.listenSSL( 0, serverProtocolFactory, self.serverCtxFactory) clientProtocolFactory = protocol.ClientFactory() clientProtocolFactory.protocol = ImmediatelyDisconnectingProtocol clientProtocolFactory.connectionDisconnected = defer.Deferred() reactor.connectSSL( "127.0.0.1", serverPort.getHost().port, clientProtocolFactory, self.clientCtxFactory, ) return clientProtocolFactory.connectionDisconnected.addCallback( lambda ignoredResult: self.serverPort.stopListening())
def main(): factory = protocol.ServerFactory() factory.protocol = Echo reactor.listenTCP(8000, factory) reactor.run()
def main(): factory = protocol.ServerFactory() factory.protocol = Echo reactor.listenTCP(3306, factory) reactor.callLater(int(sys.argv[1]), reactor.stop) reactor.run()
def main(): optionParser = OptionParser( description= 'Клиент нарушителя, реализующий эксплуатацию уязвимостей протокола S-3PAKE.\nДоступные атаки: Offline Dictionary Attack, Undetectable Online Dictionary Attack, Man-In-The-Middle.' ) optionParser.add_option('-m', '--mitm', action='store_true', help='Выбор атаки: Man-In-The-Middle') optionParser.add_option('-o', '--offlineDict', action='store_true', help='Выбор атаки: Offline Dictionary Attack') optionParser.add_option( '-u', '--undetectableOnlineDict', action='store_true', help='Выбор атаки: Undetectable Online Dictionary Attack') optionParser.add_option( '-p', '--port', action='store', help= 'Установка значения порта, на котором нарушитель будет ожидать подключения' ) optionParser.add_option( '-e', '--extport', action='store', help= 'Установка дополнительного значения порта, на котором нарушитель будет ожидать подключения' ) optionParser.add_option('-w', '--pw', action='store', help='Установка секретного значения пароля') optionParser.add_option( '-i', '--id', action='store', help='Установка значения числового идентификатора нарушителя') optionParser.add_option('-q', '--q', action='store', help='Установка значения порядка группы') optionParser.add_option( '-g', '--g', action='store', help='Установка значения порождающего элемента группы') optionParser.add_option('-M', '--M', action='store', help='Установка затемняющего значения M') optionParser.add_option('-N', '--N', action='store', help='Установка затемняющего значения N') optionParser.add_option( '-a', '--aid', action='store', help= 'Установка значения числового идентификатора клиента-инициатора в отношении которого проводится атака' ) optionParser.add_option( '-b', '--bid', action='store', help= 'Установка значения числового идентификатора клиента, ожидающего подключения инициатора, в отношении которого проводится атака' ) optionParser.add_option( '--bip', action='store', help= 'Установка значения ip-адреса клиента, ожидающего подключения инициатора, в отношении которого проводится атака' ) optionParser.add_option( '--bport', action='store', help= 'Установка значения порта клиента, ожидающего подключения инициатора, в отношении которого проводится атака' ) optionParser.add_option( '-s', '--sid', action='store', help='Установка значения числового идентификатора доверенного сервера') optionParser.add_option( '--sip', action='store', help='Установка значения ip-адреса доверенного сервера') optionParser.add_option( '--sport', action='store', help='Установка значения порта доверенного сервера') (options, arguments) = optionParser.parse_args() csm = ClientSettingsManager() if not csm.checkSettingsFile(): print("Ошибка [!]: Поврежден файл с настройками клиента") return settingsDict = csm.addSettings(options.__dict__) if settingsDict != {}: csm.setSettings(settingsDict) csm.getSettings() if options.__dict__['mitm']: print("[*]: Демонстрация атаки MITM") printOptions(mitm=True) serverFactory = protocol.ServerFactory() serverFactory.protocol = MITMserver listenerFactory = protocol.ServerFactory() listenerFactory.protocol = MITMlistener try: reactor.listenTCP(settings['port'], listenerFactory) except: print("Ошибка [!]: Ошибка при инициализации порта {0:d}".format( settings['port'])) try: reactor.listenTCP(settings['extport'], serverFactory) except: print("Ошибка [!]: Ошибка при инициализации порта {0:d}".format( settings['extport'])) print("[*]: Инициализация завершена успешно\n") print("[*]: Ожидание подключений...\n") elif options.__dict__['offlineDict']: print("[*]: Демонстрация атаки Offline Dictionary Attack") printOptions(offda=True) initiatorFactory = protocol.ClientFactory() initiatorFactory.protocol = OFFDA try: reactor.connectTCP(settings['sip'], settings['sport'], initiatorFactory) except: print("Ошибка [!]: Ошибка при подключении по адресу {0:s}:{1:d}". format(settings['sip'], settings['sport'])) print("[*]: Инициализация завершена успешно\n") print("[*]: Подключение...\n") elif options.__dict__['undetectableOnlineDict']: print("[*]: Демонстрация атаки Undetectable Online Dictionary Attack") printOptions(uonda=True) listnerFactory = protocol.ServerFactory() listnerFactory.protocol = UONDAlistener try: reactor.listenTCP(settings['port'], listnerFactory) except: print("Ошибка [!]: Ошибка при инициализации порта {0:d}".format( settings['port'])) print("[*]: Инициализация завершена успешно\n") print("[*]: Ожидание подключения...\n") reactor.run()
def __init__(self, port, checker, ssh_hostkey_dir=None): """ @type port: string or int @param port: what port should the Manhole listen on? This is a strports specification string, like 'tcp:12345' or 'tcp:12345:interface=127.0.0.1'. Bare integers are treated as a simple tcp port. @type checker: an object providing the L{twisted.cred.checkers.ICredentialsChecker} interface @param checker: if provided, this checker is used to authenticate the client instead of using the username/password scheme. You must either provide a username/password or a Checker. Some useful values are:: import twisted.cred.checkers as credc import twisted.conch.checkers as conchc c = credc.AllowAnonymousAccess # completely open c = credc.FilePasswordDB(passwd_filename) # file of name:passwd c = conchc.UNIXPasswordDatabase # getpwnam() (probably /etc/passwd) @type ssh_hostkey_dir: str @param ssh_hostkey_dir: directory which contains ssh host keys for this server """ # unfortunately, these don't work unless we're running as root # c = credc.PluggableAuthenticationModulesChecker: PAM # c = conchc.SSHPublicKeyDatabase() # ~/.ssh/authorized_keys # and I can't get UNIXPasswordDatabase to work super().__init__() if isinstance(port, int): port = "tcp:%d" % port self.port = port # for comparison later self.checker = checker # to maybe compare later def makeNamespace(): master = self.master namespace = { 'master': master, 'status': master.getStatus(), 'show': show, } return namespace def makeProtocol(): namespace = makeNamespace() p = insults.ServerProtocol(manhole.ColoredManhole, namespace) return p self.ssh_hostkey_dir = ssh_hostkey_dir if self.ssh_hostkey_dir: self.using_ssh = True if not self.ssh_hostkey_dir: raise ValueError("Most specify a value for ssh_hostkey_dir") r = manhole_ssh.TerminalRealm() r.chainedProtocolFactory = makeProtocol p = portal.Portal(r, [self.checker]) f = manhole_ssh.ConchFactory(p) openSSHFactory = OpenSSHFactory() openSSHFactory.dataRoot = self.ssh_hostkey_dir openSSHFactory.dataModuliRoot = self.ssh_hostkey_dir f.publicKeys = openSSHFactory.getPublicKeys() f.privateKeys = openSSHFactory.getPrivateKeys() else: self.using_ssh = False r = _TelnetRealm(makeNamespace) p = portal.Portal(r, [self.checker]) f = protocol.ServerFactory() f.protocol = makeTelnetProtocol(p) s = strports.service(self.port, f) s.setServiceParent(self)
def main(): f = protocol.ServerFactory() f.protocol = Discard reactor.listenTCP(8000, f) reactor.run()
def main(): factory = protocol.ServerFactory() factory.protocol = Astrium_Chopper reactor.listenTCP(60000, factory) reactor.run()
def main(*args, **kwargs): f = protocol.ServerFactory() f.protocol = lambda: TelnetTransport(TelnetBootstrapProtocol, insults. ServerProtocol, ColoredManhole) reactor.listenTCP(8007, f, interface='localhost')
def startService(self): scp = load_config(instance_config=self.instance_config) validate_config(scp) endpoint = self.endpoint if endpoint is None: if scp.has_option("Application", "endpoint"): endpoint = scp.get("Application", "endpoint") else: endpoint = "tcp:10389" db_url = scp.get("CouchDB", "url") db_user = scp.get("CouchDB", "user") db_passwd = scp.get("CouchDB", "passwd") verify_couchdb = True if scp.has_option("CouchDB", "verify"): verify_couchdb_cert = scp.getboolean("CouchDB", "verify") couchdb_ca_cert = None if scp.has_option("CouchDB", "ca_cert"): couchdb_ca_cert = scp.get("CouchDB", "ca_cert") factory = protocol.ServerFactory() if scp.has_option("LDAP", "proxy_cert"): proxy_cert = scp.get("LDAP", "proxy_cert") with open("ssl/proxy.pem", "r") as f: certData = f.read() cert = ssl.PrivateCertificate.loadPEM(certData) factory.options = cert.options() proxied_endpoints = [] last_proxied_scheme = None for opt in scp.options("LDAP"): if opt.startswith("proxied_endpoint"): proxied_endpoint = scp.get("LDAP", opt) proxied_endpoints.append(proxied_endpoint) if len(proxied_endpoints) == 0: log.msg("[ERROR] No proxied endpoints specified.") sys.exit(1) use_tls = scp.getboolean('LDAP', 'use_starttls') if scp.has_option('Application', 'debug'): debug_app = scp.getboolean('Application', 'debug') else: debug_app = False if scp.has_option('Application', 'debug_cache'): debug_cache = scp.getboolean('Application', 'debug_cache') else: debug_cache = False if scp.has_option('Application', 'search_cache_lifetime'): searchCacheLifetime = scp.getint('Application', 'search_cache_lifetime') else: searchCacheLifetime = 600 if scp.has_option('Application', 'search_cache_size'): searchCacheSize = scp.getint('Application', 'search_cache_size') else: searchCacheSize = 2000 use_cluster = False if scp.has_section("Cluster"): cluster_endpoint = None cluster_peers = [] if not scp.has_option("Cluster", "endpoint"): log.msg( "[ERROR] Section 'Cluster' does not define an 'endpoint' option." ) sys.exit(1) cluster_endpoint = scp.get("Cluster", "endpoint") options = scp.options("Cluster") has_peer = False for option in options: if option.startswith("peer"): has_peer = True cluster_peers.append(scp.get("Cluster", option)) if not has_peer: log.msg( "[ERROR] Section 'Cluster' does not have any 'peerxxx' options." ) sys.exit(1) use_cluster = True clusterClient = LRUClusterClient(cluster_peers) clusterClient.debug = debug_cache def make_protocol(): proto = SynthProxy() proto.debug = debug_app proto.use_tls = use_tls proto.clientConnector = makeClientConnector( reactor, proxied_endpoints) proto.membership_view_url = db_url proto.db_user = db_user proto.db_passwd = db_passwd if not verify_couchdb: httpclient = createNonVerifyingHTTPClient() else: if couchdb_ca_cert is not None: extra_ca_certs = [couchdb_ca_cert] else: extra_ca_certs = None httpclient = createVerifyingHTTPClient( reactor, extra_ca_certs=extra_ca_certs) proto.http_client = httpclient proto.searchResponses = {} return proto factory.protocol = make_protocol factory.dbcache = {} kwds = {} if use_cluster: kwds['cluster_func'] = make_cluster_func('search', clusterClient, debug=debug_cache) factory.searchCache = LRUTimedCache(lifetime=searchCacheLifetime, capacity=searchCacheSize, **kwds) ep = serverFromString(reactor, endpoint) d = ep.listen(factory) d.addCallback(self.set_listening_port) if use_cluster: ep = serverFromString(reactor, cluster_endpoint) cache_map = { 'search': factory.searchCache, } cluster_proto_factory = LRUClusterProtocolFactory(cache_map) cluster_proto_factory.protocol.debug = debug_cache d = ep.listen(cluster_proto_factory) d.addCallback(self.set_cluster_port) d.addErrback(log.err)
def main(cls, port=19000): f = protocol.ServerFactory() f.protocol = cls reactor.listenTCP(port, f) print "Server Started" reactor.run()
def main(): factory = protocol.ServerFactory() #定义基础工厂类 factory.protocol = Echo #socketserver 中handle reactor.listenTCP(9000, factory) reactor.run()
def getFactory(self): f = protocol.ServerFactory() f.protocol = FastAGI f.actionSelect = self.actionSelect return f
def startService(self): scp = load_config(instance_config=self.instance_config) validate_config(scp) endpoint = self.endpoint if endpoint is None: if scp.has_option("Application", "endpoint"): endpoint = scp.get("Application", "endpoint") else: endpoint = "tcp:10389" factory = protocol.ServerFactory() if scp.has_option("LDAP", "proxy_cert"): proxy_cert = scp.get("LDAP", "proxy_cert") with open(proxy_cert, "r") as f: certData = f.read() cert = ssl.PrivateCertificate.loadPEM(certData) factory.options = cert.options() proxied_endpoints = [] last_proxied_scheme = None for opt in scp.options("LDAP"): if opt.startswith("proxied_endpoint"): proxied_endpoint = scp.get("LDAP", opt) proxied_endpoints.append(proxied_endpoint) if len(proxied_endpoints) == 0: log.msg("[ERROR] No proxied endpoints specified.") sys.exit(1) use_tls = scp.getboolean('LDAP', 'use_starttls') if scp.has_option('Application', 'debug'): debug_app = scp.getboolean('Application', 'debug') else: debug_app = False if scp.has_option('Application', 'debug_cache'): debug_cache = scp.getboolean('Application', 'debug_cache') else: debug_cache = False if scp.has_option('Application', 'search_cache_lifetime'): searchCacheLifetime = scp.getint('Application', 'search_cache_lifetime') else: searchCacheLifetime = 600 if scp.has_option('Application', 'search_cache_size'): searchCacheSize = scp.getint('Application', 'search_cache_size') else: searchCacheSize = 2000 if scp.has_option('Application', 'bind_cache_lifetime'): bindCacheLifetime = scp.getint('Application', 'bind_cache_lifetime') else: bindCacheLifetime = 600 if scp.has_option('Application', 'bind_cache_size'): bindCacheSize = scp.getint('Application', 'bind_cache_size') else: bindCacheSize = 2000 use_cluster = False if scp.has_section("Cluster"): cluster_endpoint = None cluster_peers = [] if not scp.has_option("Cluster", "endpoint"): log.msg("[ERROR] Section 'Cluster' does not define an 'endpoint' option.") sys.exit(1) cluster_endpoint = scp.get("Cluster", "endpoint") options = scp.options("Cluster") has_peer = False for option in options: if option.startswith("peer"): has_peer = True cluster_peers.append(scp.get("Cluster", option)) if not has_peer: log.msg("[ERROR] Section 'Cluster' does not have any 'peerxxx' options.") sys.exit(1) use_cluster = True clusterClient = LRUClusterClient(cluster_peers) clusterClient.debug = debug_cache def make_protocol(): proto = BindProxy() proto.debug = debug_app proto.use_tls = use_tls proto.clientConnector = makeClientConnector(reactor, proxied_endpoints) proto.searchResponses = {} return proto factory.protocol = make_protocol kwds = {} if use_cluster: kwds['cluster_func'] = make_cluster_func('bind', clusterClient, debug=debug_cache) factory.lastBindCache = LRUTimedCache(lifetime=bindCacheLifetime, capacity=bindCacheSize, **kwds) kwds = {} if use_cluster: kwds['cluster_func'] = make_cluster_func('search', clusterClient, debug=debug_cache) factory.searchCache = LRUTimedCache(lifetime=searchCacheLifetime, capacity=searchCacheSize, **kwds) ep = serverFromString(reactor, endpoint) d = ep.listen(factory) d.addCallback(self.set_listening_port, port_type='ldap') if use_cluster: ep = serverFromString(reactor, cluster_endpoint) cache_map = { 'bind': factory.lastBindCache, 'search': factory.searchCache,} cluster_proto_factory = LRUClusterProtocolFactory(cache_map) cluster_proto_factory.protocol.debug = debug_cache d = ep.listen(cluster_proto_factory) d.addCallback(self.set_listening_port, port_type='cluster') d.addErrback(log.err) if scp.has_section("WebService") and scp.has_option("WebService", "endpoint"): endpoint = scp.get("WebService", "endpoint") ws_site = make_ws(bindCache=factory.lastBindCache, portal=self.portal) ws_site.displayTracebacks = debug_cache ep = serverFromString(reactor, endpoint) d = ep.listen(ws_site) d.addCallback(self.set_listening_port, port_type='ws')
def main(): factory = protocol.ServerFactory() factory.protocol = ServerProtocol reactor.listenTCP(LISTEN_PORT, factory) reactor.run()
def testTCP(self): p = reactor.listenTCP(0, protocol.ServerFactory()) portNo = p.getHost().port self.assertNotEqual(str(p).find(str(portNo)), -1, "%d not found in %s" % (portNo, p)) return p.stopListening()
def main(): """This runs the protocol on port 8000""" factory = protocol.ServerFactory() factory.protocol = Echo reactor.listenTCP(8000,factory) reactor.run()
def handle_LDAPModifyDNRequest(self, request, controls, reply): raise ldaperrors.LDAPUnwillingToPerform() fail_LDAPModifyRequest = pureldap.LDAPModifyResponse def handle_LDAPModifyRequest(self, request, controls, reply): raise ldaperrors.LDAPUnwillingToPerform() fail_LDAPExtendedRequest = pureldap.LDAPExtendedResponse def handle_LDAPExtendedRequest(self, request, controls, reply): raise ldaperrors.LDAPUnwillingToPerform() if __name__ == '__main__': from twisted.internet import protocol from twisted.python import log import sys log.startLogging(sys.stderr) configs = [ LDAPConfig(serviceLocationOverrides={"": ('localhost', 38942)}), LDAPConfig(serviceLocationOverrides={"": ('localhost', 8080)}) ] use_tls = [True, False] factory = protocol.ServerFactory() factory.protocol = lambda: MergedLDAPServer(configs, use_tls) reactor.listenTCP(10389, factory) reactor.run()
# 3.使用twisted框架创建Web服务器 from twisted.internet import protocol, reactor from twisted.protocols import basic class SimpleLogger(basic.LineReceiver): def connectionMade(self): print('Got connection from', self.transport.client) def connectionLost(self, reason=None): print(self.transport.client, 'disconnected') def lineReceived(self, line): print('data from client are as followings:') print(line) responseData = "Welcome to Twisted World!\r\n".encode('utf-8') self.transport.write(responseData) self.transport.loseConnection() # 终止连接 # 实例化protocol.ServerFactory() ''' protocol.py class ServerFactory(Factory): """Subclass this to indicate that your protocol.Factory is only usable for servers. """ ''' factory = protocol.ServerFactory() # ***0120 protocol.ServerFactory() factory.protocol = SimpleLogger reactor.listenTCP(9999, factory) reactor.run()
def make_manhole(namespace): f = protocol.ServerFactory() f.protocol = lambda: TelnetTransport(TelnetBootstrapProtocol, insults. ServerProtocol, ColoredManhole, namespace) return f
def __init__(self, port, checker, using_ssh=True): """ @type port: string or int @param port: what port should the Manhole listen on? This is a strports specification string, like 'tcp:12345' or 'tcp:12345:interface=127.0.0.1'. Bare integers are treated as a simple tcp port. @type checker: an object providing the L{twisted.cred.checkers.ICredentialsChecker} interface @param checker: if provided, this checker is used to authenticate the client instead of using the username/password scheme. You must either provide a username/password or a Checker. Some useful values are:: import twisted.cred.checkers as credc import twisted.conch.checkers as conchc c = credc.AllowAnonymousAccess # completely open c = credc.FilePasswordDB(passwd_filename) # file of name:passwd c = conchc.UNIXPasswordDatabase # getpwnam() (probably /etc/passwd) @type using_ssh: bool @param using_ssh: If True, accept SSH connections. If False, accept regular unencrypted telnet connections. """ # unfortunately, these don't work unless we're running as root # c = credc.PluggableAuthenticationModulesChecker: PAM # c = conchc.SSHPublicKeyDatabase() # ~/.ssh/authorized_keys # and I can't get UNIXPasswordDatabase to work service.AsyncMultiService.__init__(self) if isinstance(port, int): port = "tcp:%d" % port self.port = port # for comparison later self.checker = checker # to maybe compare later def makeNamespace(): master = self.master namespace = { 'master': master, 'status': master.getStatus(), 'show': show, } return namespace def makeProtocol(): namespace = makeNamespace() p = insults.ServerProtocol(manhole.ColoredManhole, namespace) return p self.using_ssh = using_ssh if using_ssh: r = manhole_ssh.TerminalRealm() r.chainedProtocolFactory = makeProtocol p = portal.Portal(r, [self.checker]) f = manhole_ssh.ConchFactory(p) else: r = _TelnetRealm(makeNamespace) p = portal.Portal(r, [self.checker]) f = protocol.ServerFactory() f.protocol = makeTelnetProtocol(p) s = strports.service(self.port, f) s.setServiceParent(self)
def main(): factory = protocol.ServerFactory() factory.protocol = Server reactor.listenTCP(PORT, factory) reactor.run()
def makeService(options): """ Create a manhole server service. @type options: C{dict} @param options: A mapping describing the configuration of the desired service. Recognized key/value pairs are:: "telnetPort": strports description of the address on which to listen for telnet connections. If None, no telnet service will be started. "sshPort": strports description of the address on which to listen for ssh connections. If None, no ssh service will be started. "namespace": dictionary containing desired initial locals for manhole connections. If None, an empty dictionary will be used. "passwd": Name of a passwd(5)-format username/password file. "sshKeyDir": The folder that the SSH server key will be kept in. "sshKeyName": The filename of the key. "sshKeySize": The size of the key, in bits. Default is 4096. @rtype: L{twisted.application.service.IService} @return: A manhole service. """ svc = service.MultiService() namespace = options['namespace'] if namespace is None: namespace = {} checker = checkers.FilePasswordDB(options['passwd']) if options['telnetPort']: telnetRealm = _StupidRealm(telnet.TelnetBootstrapProtocol, insults.ServerProtocol, manhole.ColoredManhole, namespace) telnetPortal = portal.Portal(telnetRealm, [checker]) telnetFactory = protocol.ServerFactory() telnetFactory.protocol = makeTelnetProtocol(telnetPortal) telnetService = strports.service(options['telnetPort'], telnetFactory) telnetService.setServiceParent(svc) if options['sshPort']: sshRealm = manhole_ssh.TerminalRealm() sshRealm.chainedProtocolFactory = chainedProtocolFactory(namespace) sshPortal = portal.Portal(sshRealm, [checker]) sshFactory = manhole_ssh.ConchFactory(sshPortal) if options['sshKeyDir'] != "<USER DATA DIR>": keyDir = options['sshKeyDir'] else: from twisted.python._appdirs import getDataDirectory keyDir = getDataDirectory() keyLocation = filepath.FilePath(keyDir).child(options['sshKeyName']) sshKey = keys._getPersistentRSAKey(keyLocation, int(options['sshKeySize'])) sshFactory.publicKeys["ssh-rsa"] = sshKey sshFactory.privateKeys["ssh-rsa"] = sshKey sshService = strports.service(options['sshPort'], sshFactory) sshService.setServiceParent(svc) return svc
def getFingerSetterFactory(self): f = protocol.ServerFactory() f.protocol = FingerSetterProtocol f.setUser = self.setUser return f