def copyToStdout(endpoint): echoFactory = Factory() echoFactory.protocol = StdoutEcho echoFactory.finished = Deferred() d = endpoint.connect(echoFactory) d.addErrback(echoFactory.finished.errback) return echoFactory.finished
def connect(sdata, command, username, host, port=22, key_file=None, password=None): """ Connect to an SSH host (as it happens, persistently). """ sdata.set_conn_state('connecting') try: keys = [Key.fromFile(key_file)] if key_file else None except exceptions.IOError as e: print('### key load error:', str(e)) push_failure_message(str(e), sdata) return endpoint = SSHCommandClientEndpoint.newConnection( reactor, command, username, host, port=int(port), keys=keys, password=password, ui=None, knownHosts=PermissiveKnownHosts()) factory = Factory() factory.protocol = LineProtocol factory.sdata = sdata d = endpoint.connect(factory) # Very small race condition between here and the replacement # in connectionMade() above, but I've never managed to hit it. def disconnect(): sdata.log('Disconnecting while still attempting to connect, by request') d.cancel() sdata.transport_drop_cb = disconnect d.addErrback(lambda reason: push_failure_message(reason, sdata)) return d
def process_nmap_commands(loggerName): """ Main function. Here we set up the environment, factory, interface, and port """ global nmapCommandsFile global nmapCommand global port global mlog global verboseLevel global clientTimeout observer = log.PythonLoggingObserver(loggerName) observer.start() # Create the factory factory = Factory() factory.protocol = NmapServerProtocol # Create the time based print loop = task.LoopingCall(show_info) loop.start(5.0) # call every second # Create the time based file read loop2 = task.LoopingCall(read_file_and_fill_nmap_variable) loop2.start(30.0) # call every second # To mark idle clients as hold loop3 = task.LoopingCall(timeout_idle_clients) loop3.start(clientTimeout) # call every second # Create the reactor reactor.listenSSL(port, factory, ServerContextFactory(), interface=interface) reactor.run()
def main(reactor, *argv): parameters = ConnectionParameters.fromCommandLine(reactor, argv) endpoint = parameters.endpointForCommand(b"/bin/cat") done = [] factory = Factory() factory.protocol = Protocol d = endpoint.connect(factory) def gotConnection(proto): conn = proto.transport.conn for i in range(50): factory = Factory() factory.protocol = PrinterProtocol factory.done = Deferred() done.append(factory.done) e = SSHCommandClientEndpoint.existingConnection( conn, b"/bin/echo %d" % (i,)) yield e.connect(factory) d.addCallback(gotConnection) d.addCallback(lambda work: cooperate(work).whenDone()) d.addCallback(lambda ignored: gatherResults(done)) return d
def connect(): from twisted.internet.endpoints import TCP4ClientEndpoint from twisted.internet.protocol import Factory endpoint = TCP4ClientEndpoint(reactor, "127.0.0.1", 1235) factory = Factory() factory.protocol = Bot return endpoint.connect(factory)
def setUpClient(self): factory = Factory() factory.protocol = FileReceiver point = TCP4ClientEndpoint(reactor, "localhost", 8007) d = point.connect(factory) d.addCallback(self.registerProtocol) return d
def makeService(self, options): config.load_config(options['config_paths']) factory = Factory() factory.protocol = TacacsProtocol return internet.TCPServer(49, factory)
def main(): config = ConfigParser.ConfigParser() config.read(os.path.expanduser('~/.b07')) api = b07.api.API(reactor, config.get('ingress', 'email'), config.get('ingress', 'password')) http_root = Redirect('https://localhost:{}/'.format(config.get('server', 'https_port'))) http_factory = Site(http_root) http_endpoint = endpoints.serverFromString(reactor, 'tcp:{}'.format(config.get('server', 'http_port'))) http_endpoint.listen(http_factory) https_root = File(os.path.expanduser(config.get('server', 'web_root'))) https_root.indexNames = ['index.html'] https_factory = Site(https_root) https_endpoint = endpoints.serverFromString(reactor, 'ssl:{}:privateKey={}:certKey={}'.format(config.get('server', 'https_port'), os.path.expanduser(config.get('server', 'ssl_key')), os.path.expanduser(config.get('server', 'ssl_cert')))) https_endpoint.listen(https_factory) wsfactory = Factory() wsfactory.protocol = WebSocketProtocol wss_endpoint = endpoints.serverFromString(reactor, 'ssl:{}:privateKey={}:certKey={}'.format(config.get('server', 'wss_port'), os.path.expanduser(config.get('server', 'ssl_key')), os.path.expanduser(config.get('server', 'ssl_cert')))) wss_endpoint.listen(txws.WebSocketFactory(wsfactory)) reactor.run()
def main(reactor): ep = SSHCommandClientEndpoint.newConnection( reactor, b'/bin/cat', details['USER'], details['HOST'], port=details['PORT'], password=details['PASSWORD'], agentEndpoint=None, knownHosts=None) factory = Factory() factory.protocol = MyProtocol d = ep.connect(factory) def gotConnection(proto): # stdio interface stdio_proto = StdinProto(proto.transport.conn) stdio.StandardIO(stdio_proto) # factory = Factory() # factory.protocol = MyProtocol # e = SSHCommandClientEndpoint.existingConnection(conn, b"/bin/echo hey") # return e.connect(factory).addCallback(lambda proto: proto.finished) return stdio_proto.finished return d.addCallback(gotConnection)
def main(reactor, duration): concurrency = 50 interface = '127.0.0.%d' % (int(time()) % 254 + 1,) contextFactory = cert.options() factory = Factory() factory.protocol = CloseConnection serverEndpoint = SSL4ServerEndpoint( reactor, 0, contextFactory, interface=interface) listen = serverEndpoint.listen(factory) def cbListening(port): client = Client( reactor, SSL4ClientEndpoint( reactor, interface, port.getHost().port, contextFactory, bindAddress=(interface, 0))) d = client.run(concurrency, duration) def cleanup(passthrough): d = port.stopListening() d.addCallback(lambda ignored: passthrough) return d d.addCallback(cleanup) return d listen.addCallback(cbListening) return listen
def _request(self): client = Factory() client.protocol = SimpleTransport client.finished = Deferred() client.finished.addCallback(self._continue) client.finished.addErrback(self._stop) self._server.connect(client)
def sign(self, challenge): if "SSH_AUTH_SOCK" not in os.environ: raise Exception("no ssh-agent is running!") factory = Factory() factory.noisy = False factory.protocol = SSHAgentClient endpoint = UNIXClientEndpoint(self._reactor, os.environ["SSH_AUTH_SOCK"]) d = endpoint.connect(factory) @inlineCallbacks def on_connect(agent): # we are now connected to the locally running ssh-agent # that agent might be the openssh-agent, or eg on Ubuntu 14.04 by # default the gnome-keyring / ssh-askpass-gnome application blob = pack(['ssh-ed25519', self.public_key(binary=True)]) # now ask the agent signature_blob = yield agent.signData(blob, challenge) algo, signature = unpack(signature_blob) agent.transport.loseConnection() returnValue(signature) return d.addCallback(on_connect)
def test_passwordAuthenticationFailure(self): """ If the SSH server rejects the password presented during authentication, the L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires with a L{Failure} wrapping L{AuthenticationFailed}. """ endpoint = SSHCommandClientEndpoint.newConnection( self.reactor, b"/bin/ls -l", b"dummy user", self.hostname, self.port, password=b"dummy password", knownHosts=self.knownHosts, ui=FixedResponseUI(False)) factory = Factory() factory.protocol = Protocol connected = endpoint.connect(factory) server, client, pump = self.connectedServerAndClient( self.factory, self.reactor.tcpClients[0][2]) # For security, the server delays password authentication failure # response. Advance the simulation clock so the client sees the # failure. self.reactor.advance(server.service.passwordDelay) # Let the failure response traverse the "network" pump.flush() f = self.failureResultOf(connected) f.trap(AuthenticationFailed) # XXX Should assert something specific about the arguments of the # exception self.assertClientTransportState(client, False)
def test_publicKeyAuthenticationFailure(self): """ If the SSH server rejects the key pair presented during authentication, the L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires with a L{Failure} wrapping L{AuthenticationFailed}. """ badKey = Key.fromString(privateRSA_openssh) self.setupKeyChecker(self.portal, {self.user: privateDSA_openssh}) endpoint = SSHCommandClientEndpoint.newConnection( self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port, keys=[badKey], knownHosts=self.knownHosts, ui=FixedResponseUI(False)) factory = Factory() factory.protocol = Protocol connected = endpoint.connect(factory) server, client, pump = self.connectedServerAndClient( self.factory, self.reactor.tcpClients[0][2]) f = self.failureResultOf(connected) f.trap(AuthenticationFailed) # XXX Should assert something specific about the arguments of the # exception # Nothing useful can be done with the connection at this point, so the # endpoint should close it. self.assertTrue(client.transport.disconnecting)
def test_mismatchedHostKey(self): """ If the SSH public key presented by the SSH server does not match the previously remembered key, as reported by the L{KnownHostsFile} instance use to construct the endpoint, for that server, the L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires with a L{Failure} wrapping L{HostKeyChanged}. """ differentKey = Key.fromString(privateDSA_openssh).public() knownHosts = KnownHostsFile(self.mktemp()) knownHosts.addHostKey(self.serverAddress.host, differentKey) knownHosts.addHostKey(self.hostname, differentKey) # The UI may answer true to any questions asked of it; they should # make no difference, since a *mismatched* key is not even optionally # allowed to complete a connection. ui = FixedResponseUI(True) endpoint = SSHCommandClientEndpoint.newConnection( self.reactor, b"/bin/ls -l", b"dummy user", self.hostname, self.port, password=b"dummy password", knownHosts=knownHosts, ui=ui) factory = Factory() factory.protocol = Protocol connected = endpoint.connect(factory) server, client, pump = self.connectedServerAndClient( self.factory, self.reactor.tcpClients[0][2]) f = self.failureResultOf(connected) f.trap(HostKeyChanged)
def test_connectionCancelledBeforeSecure(self): """ If the connection is cancelled before the SSH transport layer has finished key exchange (ie, gotten to the point where we may attempt to authenticate), the L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires with a L{Failure} wrapping L{CancelledError} and the connection is aborted. """ endpoint = SSHCommandClientEndpoint.newConnection( self.reactor, b"/bin/ls -l", b"dummy user", self.hostname, self.port, knownHosts=self.knownHosts, ui=FixedResponseUI(False)) factory = Factory() factory.protocol = Protocol d = endpoint.connect(factory) transport = AbortableFakeTransport(None, isServer=False) factory = self.reactor.tcpClients[0][2] client = factory.buildProtocol(None) client.makeConnection(transport) d.cancel() self.failureResultOf(d).trap(CancelledError) self.assertTrue(transport.aborted) # Make sure the connection closing doesn't result in unexpected # behavior when due to cancellation: client.connectionLost(Failure(ConnectionDone()))
def test_connectionLost(self): """ When the command closes the channel, the protocol's C{connectionLost} method is called. """ self.realm.channelLookup[b'session'] = WorkingExecSession endpoint = self.create() factory = Factory() factory.protocol = Protocol connected = endpoint.connect(factory) server, client, pump = self.finishConnection() protocol = self.successResultOf(connected) connectionLost = [] protocol.connectionLost = connectionLost.append # Figure out which channel on the connection this protocol is associated # with so the test can do a write on it. channelId = protocol.transport.id server.service.channels[channelId].loseConnection() pump.pump() connectionLost[0].trap(ConnectionDone) self.assertClientTransportState(client, False)
def _exitStatusTest(self, request, requestArg): """ Test handling of non-zero exit statuses or exit signals. """ self.realm.channelLookup[b'session'] = WorkingExecSession endpoint = self.create() factory = Factory() factory.protocol = Protocol connected = endpoint.connect(factory) server, client, pump = self.finishConnection() protocol = self.successResultOf(connected) connectionLost = [] protocol.connectionLost = connectionLost.append # Figure out which channel on the connection this protocol is associated # with so the test can simulate command exit and channel close. channelId = protocol.transport.id channel = server.service.channels[channelId] server.service.sendRequest(channel, request, requestArg) channel.loseConnection() pump.pump() self.assertClientTransportState(client, False) return connectionLost[0]
def test_channelOpenFailure(self): """ If a channel cannot be opened on the authenticated SSH connection, the L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires with a L{Failure} wrapping the reason given by the server. """ endpoint = self.create() factory = Factory() factory.protocol = Protocol connected = endpoint.connect(factory) server, client, pump = self.finishConnection() # The server logs the channel open failure - this is expected. errors = self.flushLoggedErrors(ConchError) self.assertIn( 'unknown channel', (errors[0].value.data, errors[0].value.value)) self.assertEqual(1, len(errors)) # Now deal with the results on the endpoint side. f = self.failureResultOf(connected) f.trap(ConchError) self.assertEqual('unknown channel', f.value.value) self.assertClientTransportState(client, False)
def test_dataReceived(self): """ After establishing the connection, when the command on the SSH server produces output, it is delivered to the protocol's C{dataReceived} method. """ self.realm.channelLookup[b'session'] = WorkingExecSession endpoint = self.create() factory = Factory() factory.protocol = Protocol connected = endpoint.connect(factory) server, client, pump = self.finishConnection() protocol = self.successResultOf(connected) dataReceived = [] protocol.dataReceived = dataReceived.append # Figure out which channel on the connection this protocol is # associated with so the test can do a write on it. channelId = protocol.transport.id server.service.channels[channelId].write(b"hello, world") pump.pump() self.assertEqual(b"hello, world", b"".join(dataReceived))
def test_loseConnection(self): """ The transport connected to the protocol has a C{loseConnection} method which causes the channel in which the command is running to close and the overall connection to be closed. """ self.realm.channelLookup[b'session'] = WorkingExecSession endpoint = self.create() factory = Factory() factory.protocol = Protocol connected = endpoint.connect(factory) server, client, pump = self.finishConnection() protocol = self.successResultOf(connected) closed = self.record(server, protocol, 'closed', noArgs=True) protocol.transport.loseConnection() pump.pump() self.assertEqual([None], closed) # Let the last bit of network traffic flow. This lets the server's # close acknowledgement through, at which point the client can close # the overall SSH connection. pump.pump() # Nothing useful can be done with the connection at this point, so the # endpoint should close it. self.assertTrue(client.transport.disconnecting)
def create(self): """ Create and return a new L{SSHCommandClientEndpoint} using the C{existingConnection} constructor. """ factory = Factory() factory.protocol = Protocol connected = self.endpoint.connect(factory) # Please, let me in. This kinda sucks. channelLookup = self.realm.channelLookup.copy() try: self.realm.channelLookup[b'session'] = WorkingExecSession server, client, pump = self.connectedServerAndClient( self.factory, self.reactor.tcpClients[0][2]) finally: self.realm.channelLookup.clear() self.realm.channelLookup.update(channelLookup) self._server = server self._client = client self._pump = pump protocol = self.successResultOf(connected) connection = protocol.transport.conn return SSHCommandClientEndpoint.existingConnection( connection, b"/bin/ls -l")
def _processRequest(self): """ Process the request by sending it to the relevant server. @return: the HTTP response. @rtype: L{Response} """ ssl, host, port, _ignore_path = self.server.details() path = "/" + config.Servers.ConduitName headers = Headers() headers.setHeader("Host", utf8String(host + ":{}".format(port))) if self.streamType: # For attachments we put the base64-encoded JSON data into a header headers.setHeader("Content-Type", self.streamType) headers.addRawHeader("XPOD", base64.b64encode(self.data)) else: headers.setHeader("Content-Type", MimeType("application", "json", params={"charset": "utf-8", })) headers.setHeader("User-Agent", "CalendarServer/{}".format(version)) headers.addRawHeader(*self.server.secretHeader()) from twisted.internet import reactor f = Factory() f.protocol = HTTPClientProtocol ep = GAIEndpoint(reactor, host, port, _configuredClientContextFactory() if ssl else None) proto = (yield ep.connect(f)) request = ClientRequest("POST", path, headers, self.stream if self.stream is not None else self.data) if accountingEnabledForCategory("xPod"): self.loggedRequest = yield self.logRequest(request) response = (yield proto.submitRequest(request)) returnValue(response)
def start(self): factory = Factory() factory.protocol = WorkerProtocol factory.master = self self.reactor.listenTCP(8005, factory) self.launchClient()
def run(self): # TCP Server Log().add("[+] TwistedTCP Server launched on %s:%d" % (SETTINGS.SERVER_HOST, SETTINGS.SERVER_PORT), "green") reactor.listenTCP(SETTINGS.SERVER_PORT, TwistedTCPFactory(), interface=SETTINGS.SERVER_HOST) # WebSocket HTML5 Server Log().add("[+] WebSocket HTML5 Server launched on %s:%s" % (SETTINGS.SERVER_HOST, SETTINGS.SERVER_WEBSOCKET_PORT), "green") wsfactory = Factory() wsfactory.protocol = ClientWebSocket reactor.listenTCP(SETTINGS.SERVER_WEBSOCKET_PORT, WebSocketFactory(wsfactory), interface=SETTINGS.SERVER_HOST) # HTTP Server Log().add("[+] HTTP Server launched on %s:%d" % (SETTINGS.SERVER_HOST, SETTINGS.SERVER_HTTP_PORT), "green") client = server.Site(ClientHTTP()) reactor.listenTCP(SETTINGS.SERVER_HTTP_PORT, client, interface=SETTINGS.SERVER_HOST) # Running servers reactor.run(installSignalHandlers=0)
def process_nmap_commands(logger_name): """ Main function. Here we set up the environment, factory and port """ global nmap_commands_file global nmap_command global port global mlog global verbose_level global client_timeout observer = log.PythonLoggingObserver(logger_name) observer.start() # Create the factory factory = Factory() factory.protocol = NmapServerProtocol # Create the time based print loop = task.LoopingCall(show_info) loop.start(5) # Create the time based file read loop2 = task.LoopingCall(read_file_and_fill_nmap_variable) loop2.start(1) # To mark idel clients as hold loop3 = task.LoopingCall(timeout_idle_clients) loop3.start(client_timeout) # call every second if not sql_file =="": loop4 = task.LoopingCall(sql_import_loop) loop4.start(5) # Create the reactor reactor.listenSSL(port, factory, ServerContextFactory()) reactor.run()
def setUp(self): if INTERNAL_BUS: os.environ['DBUS_SESSION_BUS_ADDRESS'] = ( 'unix:abstract=/tmp/txdbus-test,guid=5' ) bus_obj = bus.Bus() f = Factory() f.protocol = bus.BusProtocol f.bus = bus_obj point = endpoints.getDBusEnvEndpoints(reactor, False)[0] d = point.listen(f) def got_port(port): self.port = port return self._client_connect() d.addCallback(got_port) return d else: return self._client_connect()
def _listenServer(self, d): from twisted.internet.protocol import Factory from twisted.internet import reactor f = Factory() f.onConnectionLost = d f.protocol = FakeSMTPServer return reactor.listenTCP(SMTP_SERVER_PORT, f)
def start_AMP(self, p_pyhouse_obj): l_endpoint = TCP4ServerEndpoint l_factory = Factory() l_factory.protocol = AMP p_pyhouse_obj.Services.IrControlService = StreamServerEndpointService(l_endpoint, l_factory) p_pyhouse_obj.Services.IrControlService.setName('IrControl') p_pyhouse_obj.Services.IrControlService.setServiceParent(p_pyhouse_obj.Twisted.Application)
def createProxyConnection(self, ip, port): factory = Factory() factory.protocol = Receiver point = TCP4ClientEndpoint(reactor, ip, port) d = point.connect(factory) d.addCallback(self.gotProxy) d.addErrback(self.cantConnect)
pass class Hotplug(Protocol): def connectionMade(self): print "HOTPLUG connection!" self.received = "" def dataReceived(self, data): print "hotplug:", data self.received += data print "complete", self.received def connectionLost(self, reason): print "HOTPLUG connection lost!" data = self.received.split('\0')[:-1] v = {} for x in data: i = x.find('=') var, val = x[:i], x[i+1:] v[var] = val processHotplugData(self, v) factory = Factory() factory.protocol = Hotplug reactor.listenUNIX("/tmp/hotplug.socket", factory) def Plugins(**kwargs): return PluginDescriptor(name = "Hotplug", description = "listens to hotplug events", where = PluginDescriptor.WHERE_AUTOSTART, fnc = autostart)
def makeFactory(self): self.factory = Factory() self.factory.protocol = JSONClient return self.factory
['grep', '-E', '-o', '([0-9]{1,3}[\.]){3}[0-9]{1,3}'], stdin=p2.stdout, stdout=subprocess.PIPE) output = p3.stdout.read() print "Scan ended! Saving nodes to file..." #this part uses nmap to scan for devices nearby that have their ssh port open. The command can be modified fil = open( 'ips.txt', 'w' ) #here we open a file to write the ips we found. You can write a specific ip using the command: fil.write(str(<<ip>>)+'\n') fil.write('83.212.72.204' + '\n') fil.close() fil = open( 'proxies.txt', 'r') #load all proxies in memory. they are used in order repeatedly. for line in fil: proxies.append(line) #print proxies proxynum = len(proxies) logger = open(args.logfile, 'a') if __name__ == '__main__': main() print "Ready..." f = Factory() f.protocol = Echo reactor.listenSSL(int(port), f, ServerContextFactory(), interface=interf) #starts the server reactor.run()
from twisted.internet import reactor from twisted.internet.protocol import Factory from twisted.protocols.basic import LineReceiver from twisted.internet.protocol import Protocol import struct from ByteArray import ByteArray class SimpleLogger(Protocol): def connectionMade(self): print 'Got connection from', self.transport.client def connectionLost(self, reason): print self.transport.client, 'disconnected' #def lineReceived(self, line): # print line def dataReceived(self, data): ba = ByteArray(data) print ba.bytesAvailable() s = ba.readUnsignedInt() print ba.bytesAvailable() print s s = ba.readUTFBytes(ba.bytesAvailable()) print s factory = Factory() factory.protocol = SimpleLogger reactor.listenTCP(8000, factory) reactor.run()
def startService(self): factory = Factory.forProtocol(EndpointForwardingProtocol) factory.service = self self._endpoint = serverFromString(self._reactor, self._endpointDescriptor) self._endpointPort = yield self._endpoint.listen(factory)
def send(self): html = """<!DOCTYPE html><html><body><h1>Foobar</h1></body></html>""" raw = html.encode("utf-8") response = "HTTP/1.1 200 OK\x0d\x0a" response += "Content-Type: text/html; charset=UTF-8\x0d\x0a" response += "Content-Length: %d\x0d\x0a" % len(raw) response += "\x0d\x0a" response += raw self.transport.write(response) if __name__ == "__main__": pool = CreatePool() if True: factory = Factory() factory.protocol = Echo else: root = File(".") factory = Site(root) reactor.listenSSL( 8090, factory, ssl.DefaultOpenSSLContextFactory('server.key', 'server.crt')) reactor.run() class SslEchoService(MultiService): def startService(self): pool = CreatePool()
def datagramReceived(self, data, (host, port)): global lastSIPPER global gi logprint( 'The host at %s (%d/UDP) is trying to initiate a SIP connection...' % (host, port)) if (lastSIPPER != host): lastSIPPER = host thread.start_new_thread(twitter_it, ( 'A host at %s (%s, %s - %s) wants to talk SIP to my honeypot... #netmenaces', lastSIPPER)) logprint('SIP Data from: %s (%d/UDP):\n%s' % (host, port, data)) random.seed() fDump = Factory() fDump.protocol = Dumper fMSSQL = Factory() fMSSQL.protocol = tFakeMSSQL fTS = Factory() fTS.protocol = tFakeTS fVNC = Factory() fVNC.protocol = tFakeVNC fRAdmind = Factory() fRAdmind.protocol = tFakeRAdmind logger = logging.getLogger('Rotating Log') logger.setLevel(logging.INFO) handler = TimedRotatingFileHandler('toms_honeypot.log', when='midnight', interval=1)
def setUp(self): factory = Factory() factory.protocol = DummyProtocol self.proto = factory.buildProtocol(('127.0.0.1', 0)) self.tr = proto_helpers.StringTransport() self.proto.makeConnection(self.tr)
for fclient in self.factory.clients: if fclient.transport.getPeer().host == spl[1]: fclient.transport.write(msg+"^") return def hostIPaddress(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("gmail.com",80)) myhostip = s.getsockname()[0] s.close() return myhostip except: print "Internet disconnected?" return 0 if __name__ == "__main__": myhostip = hostIPaddress() if not myhostip: sys.exit() factory = Factory() factory.protocol = Server factory.clients = [] # clients list factory.host = None PORT = 50000 # port of the server reactor.listenTCP(PORT, factory) print "[ Server info ]\nServer IP : %s\nPort : %d" %(myhostip, PORT) print "Server is now running.\nPress [ Ctrl-c ] to close the server." reactor.run()
# Copyright (c) 2001-2004 Twisted Matrix Laboratories. # See LICENSE for details. from OpenSSL import SSL class ServerContextFactory: def getContext(self): """Create an SSL context. This is a sample implementation that loads a certificate from a file called 'server.pem'.""" ctx = SSL.Context(SSL.SSLv23_METHOD) ctx.use_certificate_file('server.pem') ctx.use_privatekey_file('server.pem') return ctx if __name__ == '__main__': import echoserv, sys from twisted.internet.protocol import Factory from twisted.internet import ssl, reactor from twisted.python import log log.startLogging(sys.stdout) factory = Factory() factory.protocol = echoserv.Echo reactor.listenSSL(8000, factory, ServerContextFactory()) reactor.run()
def handleDisconnect(self, frame): self.transport.loseConnection() def handleSend(self, frame): if frame.body == b'shutdown': self.transport.loseConnection() def handleSubscribe(self, frame): headers = frame.headers replyHeaders = { StompSpec.DESTINATION_HEADER: headers[StompSpec.DESTINATION_HEADER], StompSpec.MESSAGE_ID_HEADER: 4711 } try: replyHeaders[StompSpec.SUBSCRIPTION_HEADER] = headers[ StompSpec.ID_HEADER] except: pass self.transport.write( self.getFrame(StompSpec.MESSAGE, replyHeaders, b'hi')) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) factory = Factory() factory.protocol = ErrorOnConnectStompServer reactor.listenTCP(8007, factory) # @UndefinedVariable reactor.run() # @UndefinedVariable
def buildProtocol(self, addr): if addr.host not in self.only_ip and "0.0.0.0" not in self.only_ip: return return Factory.buildProtocol(self, addr)
from twisted.internet.protocol import Factory from twisted.protocols.basic import LineReceiver class SimpleTwistedServer(LineReceiver): def connectionMade(self): print 'Got connection from', self.transport.client def connectionLost(self, reason): print self.transport.client, 'disconnected' def lineReceived(self, line): print line factory = Factory() factory.protocol = SimpleTwistedServer reactor.listenTCP(1234, factory) reactor.run() # # from twisted.web.resource import Resource # from twisted.web import server # from twisted.web import static # from twisted.internet import reactor # # PORT = 1234 # # class ReStructed( Resource ): # # def __init__( self, filename, *a ):
if len(a) > 1: command = a[0] content = a[1] print "command = ", command print "content = ", content print msg = "" if command == "ID": self.name = content msg = self.name + " Hello! " elif command == "message": msg = self.name + ": " + content #print msg for c in self.factory.clients: c.message(msg) def message(self, message): self.transport.write(message + '\n') factory = Factory() factory.protocol = IphoneChat factory.clients = [] reactor.listenTCP(89, factory) print "Iphone Chat server started" reactor.run()
self._data_cb(data) def _data_cb(self, data): protoc_current_pose = protoc_msg_pb2.CurrentPose() protoc_current_pose.ParseFromString(data) self._car_pose_cb(protoc_current_pose) def _car_pose_cb(self, protoc_current_pose): msg_current_pose = PoseStamped() utils_pb2ros.PoseStamped2Msg(protoc_current_pose.msg, msg_current_pose) vehicle_info = protoc_current_pose.info car_vin = int(vehicle_info.vin) car_id = car_vin % 10000000 car_station = vehicle_info.state topic = "/car" + str(car_id) + "/current_pose" self.pub_car_pose[car_vin].publish(msg_current_pose) def connectionLost(self, reason): print("connection lost") if __name__ == "__main__": rospy.init_node("gataway_server") factory = Factory() factory.protocol = MyServerProtocol print("waiting for connection...") reactor.listenTCP(PORT, factory) reactor.run()
def main(): f = Factory() f.protocol = Echo reactor.listenTCP(45000, f) reactor.run()
def _initFactory(self): self.factory = Factory() self.factory.connections = [] self.factory.server = self
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A simple Quote of the Day server """ from twisted.internet.protocol import Protocol, Factory from twisted.internet import reactor class QOTD(Protocol): def connectionMade(self): self.transport.write('An apple a day keeps the doctor away\r\n') self.transport.loseConnection() # Next lines are magic: factory = Factory() factory.protocol = QOTD # 8007 is the port you want to run under. Choose something >1024 reactor.listenTCP(8007, factory) reactor.run()
def main(): fact = Factory() fact.protocol = reverse_string reactor.listenTCP(8888, fact) print("Twisted TCP server running on PORT#8888") reactor.run()
def telent_server_main(self): _q_s = self class CustomTelnetProtocol(TelnetProtocol): _state = None _user = None _pass = None def connectionMade(self): self._state = None self._user = None self._pass = None self.transport.write('{} \n'.format(choice( _q_s.random_servers))) self.transport.write('PC login: '******'Username': self._user = data self._state = "Password" self.transport.write('Password: '******'Password': self._pass = data if self._user == _q_s.username and self._pass == _q_s.password: _q_s.logs.info([ "servers", { 'server': 'telnet_server', 'action': 'login', 'status': 'success', 'ip': self.transport.getPeer().host, 'port': self.transport.getPeer().port, 'username': _q_s.username, 'password': _q_s.password } ]) else: _q_s.logs.info([ "servers", { 'server': 'telnet_server', 'action': 'login', 'status': 'failed', 'ip': self.transport.getPeer().host, 'port': self.transport.getPeer().port, 'username': self._user, 'password': self._pass } ]) self.transport.loseConnection() else: self.transport.loseConnection() def connectionLost(self, reason): self._state = None self._user = None self._pass = None factory = Factory() factory.protocol = lambda: TelnetTransport(CustomTelnetProtocol) reactor.listenTCP(port=self.port, factory=factory, interface=self.ip) reactor.run()
def buildProtocol(self, addr): protocol = Factory.buildProtocol(self, addr) return protocol
def buildProtocol(self, addr): p = Factory.buildProtocol(self, addr) p.command_cb = self.command_cb return p
def daemon_main(): f = Factory() f.protocol = CmdGate reactor.listenTCP(PORT, f) reactor.run()
#!/usr/bin/python #encoding=utf-8 from twisted.internet import reactor from twisted.internet.protocol import Protocol, Factory from twisted.protocols.basic import LineReceiver class SimpleServer(Protocol): def connectionMade(self): #连接建立的时候 print 'Get connection from', self.transport.client def connectionLost(self, reason):连接断开的时候 print self.transport.client, 'disconnected' def lineReceived(self, line): #当收到一行数据的时候 print line factory = Factory() factory.protocol = SimpleServer port = 1234 reactor.listenTCP(port, factory) reactor.run() #进入循环
self.sendPDU(pdu) class DeliverSMSMSC(HappySMSC): def __init__( self ): HappySMSC.__init__(self) self.responseMap[BindReceiver] = self.sendDeliverSM self.responseMap[BindTransceiver] = self.sendDeliverSM def sendDeliverSM(self, reqPDU): self.sendSuccessResponse(reqPDU) pdu = DeliverSM( source_addr='1234', destination_addr='4567', short_message='test', ) self.sendPDU(pdu) class DeliverSMAndUnbindSMSC(DeliverSMSMSC): def sendDeliverSM(self, reqPDU): DeliverSMSMSC.sendDeliverSM(self, reqPDU) self.sendPDU(Unbind()) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) factory = Factory() factory.protocol = BlackHoleSMSC reactor.listenTCP(8007, factory) reactor.run()
self.BodyText.delete('1.0', END) self.BodyText.config(state=DISABLED) root = Tk() root.title("Oolite - Javascript Debug Console") root.geometry("500x380") root.resizable(0,0) root.protocol("WM_DELETE_WINDOW", reactor.stop) app = Window(root) app.Print ("Type /quit to quit.") app.Print ("Waiting for connection...") # Set up console server protocol factory = Factory() factory.delegateClass = SimpleConsoleDelegate factory.activeCount = 0 factory.protocol = OoliteDebugConsoleProtocol # Set up command line I/O protocol cliHandler = OoliteDebugCLIProtocol() cliHandler.getInputReceiver = getInputReceiver stdio.StandardIO(cliHandler) # Install the Reactor support tksupport.install(root) app.listener=reactor.listenTCP(defaultOoliteConsolePort, factory) reactor.run()
class MultiValve(Machine): protocolFactory = Factory.forProtocol(LineReceiver) name = "Valco Multiposition Valve" def setup(self): # Number of positions self.num_positions = 0 def _set_position(pos): return self.move(pos) # setup variables self.position = Property(title="Position", type=int, setter=_set_position) self.ui = ui(properties=[self.position]) _move_commands = { "c": "CW", "cw": "CW", "clockwise": "CW", "a": "CC", "cc": "CC", "counterclockwise": "CC", "anticlockwise": "CC", "f": "GO", "fastest": "GO" } @defer.inlineCallbacks def _getPosition(self): result = yield self.protocol.write("CP") try: defer.returnValue(int(result.split("=")[1])) except ValueError: return @defer.inlineCallbacks def move(self, position, direction="f"): if direction not in self._move_commands: raise "Invalid direction" command = self._move_commands[direction] # Make sure position is between 1 and NP position = ((int(position) - 1) % self.num_positions) + 1 if position == self.position.value: current_position = yield self._getPosition() if position == current_position: defer.returnValue('OK') yield self.protocol.write("%s%d" % (command, position), expectReply=False) new_position = yield self._getPosition() if new_position is None: # If there was an error in the move command, this will have been received # by the CP command due to the expectReply = False. # Read the current position again new_position = yield self._getPosition() if new_position != position: raise Exception("Move Failed") else: self.position._push(new_position) defer.returnValue("OK") def advance(self, positions): return self.move(int(self.position) + positions) def start(self): # Discover the number of positions def interpretPositions(result): self.num_positions = int(result.split("=")[1]) # Discover the current positions def interpretPosition(result): self.position._push(int(result.split("=")[1])) return defer.gatherResults([ self.protocol.write("NP").addCallback(interpretPositions), self.protocol.write("CP").addCallback(interpretPosition) ]) def reset(self): return defer.gatherResults([self.position.set(1)])
# clients = self.clients_db_cursor.fetchall() # for client in clients: # if client[0] == ip: # return True # return False # # def add_client(self, ip: str, id: str) -> bool: # self.clients_db_cursor.execute("""INSERT INTO clients VALUES(?, ?)""", (ip, id)) # self.clients_db.commit() # return True # # def add_key(self, ip, key): # self.clients_db_cursor.execute("""UPDATE clients SET key=? WHERE ip=?""", (key, ip)) # self.clients_db.commit() # return True # # def get_client(self, ip: str) -> list: # self.clients_db_cursor.execute("""SELECT * FROM clients WHERE ip='%s'""" % (ip)) # client = self.clients_db_cursor.fetchone() # return client if __name__ == '__main__': f = Factory() f.protocol = Server reactor.listenSSL( 30590, f, ssl.DefaultOpenSSLContextFactory('keys/private.key', 'keys/server.crt')) reactor.run()
from twisted.internet import interfaces # noqa: F401 from twisted.internet.protocol import Factory from twisted.protocols.tls import TLSMemoryBIOFactory from twisted.web.http import HTTPChannel from synapse.http.client import BlacklistingReactorWrapper from synapse.http.proxyagent import ProxyAgent from tests.http import TestServerTLSConnectionFactory, get_test_https_policy from tests.server import FakeTransport, ThreadedMemoryReactorClock from tests.unittest import TestCase logger = logging.getLogger(__name__) HTTPFactory = Factory.forProtocol(HTTPChannel) class MatrixFederationAgentTests(TestCase): def setUp(self): self.reactor = ThreadedMemoryReactorClock() def _make_connection(self, client_factory, server_factory, ssl=False, expected_sni=None): """Builds a test server, and completes the outgoing client connection Args: client_factory (interfaces.IProtocolFactory): the the factory that the
Serve up random integers. """ def connectionMade(self): """ Once the connection is made we ask the client how many random integers the producer should return. """ print(f"Connection made from {self.transport.getPeer()}") self.sendLine(b"How many random integers do you want?") def lineReceived(self, line): """ This checks how many random integers the client expects in return and tells the producer to start generating the data. """ count = int(line.strip()) print(f"Client requested {count} random integers!") producer = Producer(self, count) self.transport.registerProducer(producer, True) producer.resumeProducing() def connectionLost(self, reason): print(f"Connection lost from {self.transport.getPeer()}") startLogging(stdout) factory = Factory() factory.protocol = ServeRandom reactor.listenTCP(1234, factory) reactor.run()