def autostart(reason, **kwargs): if reason == 0: from twisted.internet import reactor try: os.remove("/tmp/hotplug.socket") except OSError: pass factory = Factory() factory.protocol = Hotplug reactor.listenUNIX("/tmp/hotplug.socket", factory)
def start_ping_sim_server(server_address): """Run server simulating ping command output, this is one-shot server""" logger = logging.getLogger('twisted.ping.tcp-server') host, port = server_address factory = Factory() factory.protocol = PingSimTcpServer reactor.listenTCP(port, factory) logger.debug("Ping Sim started at tcp://{}:{}".format(*server_address)) logger.debug("WARNING - I'll be tired too much just after first client!")
def main(reactor, *argv): parameters = ConnectionParameters.fromCommandLine(reactor, argv) endpoint = parameters.endpointForCommand(b"/bin/cat") factory = Factory() factory.protocol = NoiseProtocol d = endpoint.connect(factory) d.addCallback(lambda proto: proto.finished) return d
def autostart(reason, **kwargs): if reason == 0: try: if not os.path.exists("/tmp/hotplug.socket"): return except (IOError, OSError): pass factory = Factory() factory.protocol = Hotplug reactor.listenUNIX("/tmp/hotplug.socket", factory)
def start_webserver(self, response_data): factory = Factory() factory.protocol = FakeHTTP factory.response_data = self._reformat_response_data(response_data) factory.testcase = self webserver = reactor.listenTCP(0, factory, interface='127.0.0.1') self.add_cleanup(webserver.loseConnection) addr = webserver.getHost() webserver.url = "http://%s:%s/" % (addr.host, addr.port) return webserver
def main(): try: logger.set_logger('receiver.log') reactor.listenUDP(Config.data['receiver']['port'], UDP_received()) factory = Factory() factory.protocol = TCP_received reactor.listenTCP(Config.data['receiver']['port'], factory) reactor.run() except Exception as e: logging.exception('Exception doing receiver startup.')
def button1Click(self): #print "button1Click event handler" self.button1["background"] = "yellow" import select import sys import pybonjour name = 'gamepanel' regtype = '_gamepanel._tcp' port = 3333 ##name = sys.argv[1] ##regtype = sys.argv[2] ####port = int(sys.argv[3]) def register_callback(sdRef, flags, errorCode, name, regtype, domain): if errorCode == pybonjour.kDNSServiceErr_NoError: print 'Registered service:' print ' name =', name print ' regtype =', regtype print ' domain =', domain sdRef = pybonjour.DNSServiceRegister(name=name, regtype=regtype, port=port, callBack=register_callback) class IphoneChat(Protocol): def connectionMade(self): self.factory.clients.append(self) #print "clients are ", self.factory.clients def connectionLost(self, reason): self.factory.clients.remove(self) def dataReceived(self, data): a = data #print a if a == data: # import SendKeys SendKeys.SendKeys(a) time.sleep(1) # reactor.run(installSignallHandlers=True) def message(self, message): self.transport.write(message) factory = Factory() factory.protocol = IphoneChat factory.clients = [] reactor.listenTCP(3333, factory) self.button1["background"] = "green"
def setUp(self): fp = FilePath(self.mktemp()) fp.makedirs() from twisted.internet.protocol import Protocol, Factory from twisted.internet import reactor, defer d = defer.Deferred() class JustLetMeMoveOn(Protocol): def connectionMade(self): d.callback(None) self.transport.abortConnection() f = Factory() f.protocol = JustLetMeMoveOn port = reactor.listenTCP(0, f, interface="127.0.0.1") @self.addCleanup def goodbyePort(): return port.stopListening() env = dict(os.environ) env["TESTING_PORT"] = repr(port.getHost().port) self.stdout = fp.child("stdout.txt") self.stderr = fp.child("stderr.txt") self.launchLabel = ("org.calendarserver.UNIT-TESTS." + str(os.getpid()) + "." + self.id()) plist = { "Label": self.launchLabel, "ProgramArguments": [sys.executable, "-m", __name__, self.id()], "EnvironmentVariables": env, "KeepAlive": False, "StandardOutPath": self.stdout.path, "StandardErrorPath": self.stderr.path, "Sockets": { "Awesome": [{"SecureSocketWithKey": "GeneratedSocket"}] }, "RunAtLoad": True, "Debug": True, } self.job = fp.child("job.plist") self.job.setContent(plistlib.writePlistToString(plist)) child = Popen( args=[ "launchctl", "load", self.job.path, ], stdout=PIPE, stderr=PIPE, ) _ignore_output, error = child.communicate() if child.returncode != 0 or error: raise SkipTest("launchctl cannot run on this system") return d
def connectToAgent(self, endpoint): factory = Factory() factory.protocol = SSHAgentClient d = endpoint.connect(factory) def connected(agent): self.agent = agent return agent.getPublicKeys() d.addCallback(connected) return d
def connect(self, protocolFactory): factory = Factory() factory.protocol = _CommandTransport factory.command = self._command factory.commandProtocolFactory = protocolFactory factory.commandConnected = Deferred() d = self._sshServer.connect(factory) d.addErrback(factory.commandConnected.errback) return factory.commandConnected
def new(cls, pubkey=None, reactor=None): """ Create a proxy for a key held in SSH agent. :param pubkey: A string with a public Ed25519 key in SSH format. :type pubkey: unicode """ pubkey = _read_ssh_ed25519_pubkey(pubkey) if not reactor: from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks, returnValue from twisted.internet.protocol import Factory from twisted.internet.endpoints import UNIXClientEndpoint from twisted.conch.ssh.agent import SSHAgentClient 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(reactor, os.environ["SSH_AUTH_SOCK"]) d = endpoint.connect(factory) @inlineCallbacks def on_connect(agent): keys = yield agent.requestIdentities() # if the key is found in ssh-agent, the raw public key (32 bytes), and the # key comment as returned from ssh-agent key_data = None key_comment = None for blob, comment in keys: raw = unpack(blob) algo = raw[0] if algo == u'ssh-ed25519': algo, _pubkey = raw if _pubkey == pubkey: key_data = _pubkey key_comment = comment.decode('utf8') break agent.transport.loseConnection() if key_data: key = signing.VerifyKey(key_data) returnValue(cls(key, key_comment, reactor)) else: raise Exception("Ed25519 key not held in ssh-agent") return d.addCallback(on_connect)
def __init__(self, ip='0.0.0.0', port=TCP_PORT): from twisted.internet import reactor self.ip = ip self.port = port self.reactor = reactor f = Factory() f.protocol = TCP reactor.listenTCP(port, f) super().__init__()
def __init__(self, model, port): """Create an instance of an EmulationServer""" self.factory = Factory() self.factory.protocol = EmulationProtocol self.factory.clients = list() self.factory.app = self self.port = port self.factory.controler = TimeControler(model, real_time = True, rt_factor = 1, until = 100000, step = True) self.factory.controler.add_callback(self.notify_stop, EVENT_FINISH) self.factory.controler.add_callback(self.notify_start, EVENT_START) self.factory.controler.add_callback(self.notify_time, EVENT_TIME)
def main(): server = Server() f = Factory() # f.client_host = f.protocol = WebClient f.clients = [] f.server = server reactor.listenTCP(8080, f) print 'Listening on port', 8080 reactor.run()
def test_agentAuthentication(self): """ If L{SSHCommandClientEndpoint} is initialized with an L{SSHAgentClient}, the agent is used to authenticate with the SSH server. """ key = Key.fromString(privateRSA_openssh) agentServer = SSHAgentServer() agentServer.factory = Factory() agentServer.factory.keys = {key.blob(): (key, "")} self.setupKeyChecker(self.portal, {self.user: privateRSA_openssh}) agentEndpoint = SingleUseMemoryEndpoint(agentServer) endpoint = SSHCommandClientEndpoint.newConnection( self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port, knownHosts=self.knownHosts, ui=FixedResponseUI(False), agentEndpoint=agentEndpoint) self.realm.channelLookup[b'session'] = WorkingExecSession factory = Factory() factory.protocol = Protocol connected = endpoint.connect(factory) server, client, pump = self.connectedServerAndClient( self.factory, self.reactor.tcpClients[0][2]) # Let the agent client talk with the agent server and the ssh client # talk with the ssh server. for i in range(14): agentEndpoint.pump.pump() pump.pump() protocol = self.successResultOf(connected) self.assertNotIdentical(None, protocol.transport)
def test_control(self): eq = EventualQueue(reactor) w1 = wormhole.create(APPID, self.relayurl, reactor, _enable_dilate=True) w2 = wormhole.create(APPID, self.relayurl, reactor, _enable_dilate=True) w1.allocate_code() code = yield w1.get_code() print("code is: {}".format(code)) w2.set_code(code) yield doBoth(w1.get_verifier(), w2.get_verifier()) print("connected") eps1 = w1.dilate() eps2 = w2.dilate() print("w.dilate ready") f1 = Factory() f1.protocol = L f1.d = Deferred() f1.d.addCallback(lambda data: eq.fire_eventually(data)) d1 = eps1.control.connect(f1) f2 = Factory() f2.protocol = L f2.d = Deferred() f2.d.addCallback(lambda data: eq.fire_eventually(data)) d2 = eps2.control.connect(f2) yield d1 yield d2 print("control endpoints connected") # note: I'm making some horrible assumptions about one-to-one writes # and reads across a TCP stack that isn't obligated to maintain such # a relationship, but it's much easier than doing this properly. If # the tests ever start failing, do the extra work, probably by # using a twisted.protocols.basic.LineOnlyReceiver data1 = yield f1.d data2 = yield f2.d self.assertEqual(data1, b"hello\n") self.assertEqual(data2, b"hello\n") yield w1.close() yield w2.close()
def test_200_when_available(self): """When the factory is available a 200 response is generated.""" ctf = gracefulshutdown.ConnTrackingFactoryWrapper(Factory()) r = gracefulshutdown.ServerAvailableResource([ctf]) request = self.make_dummy_http_request() r.render_HEAD(request) self.assertEqual(200, request.code) # GET works too request = self.make_dummy_http_request() body = r.render_GET(request) self.assertEqual(200, request.code) self.assertTrue(body.startswith('Available\n'))
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)
def test_defaultBuildProtocol(self): """ L{Factory.buildProtocol} by default constructs a protocol by calling its C{protocol} attribute, and attaches the factory to the result. """ class SomeProtocol(Protocol): pass f = Factory() f.protocol = SomeProtocol protocol = f.buildProtocol(None) self.assertIsInstance(protocol, SomeProtocol) self.assertIs(protocol.factory, f)
def start(self): """ Start the socks5 server by listening on the specified TCP ports. """ def build_protocol(_): socks5connection = Socks5Connection(self) self.sessions.append(socks5connection) return socks5connection factory = Factory() factory.buildProtocol = build_protocol self.twisted_port = reactor.listenTCP(self.port, factory)
def main(): # Run ROS node rospy.init_node('tablet_server') # Start the server/reactor loop factory = Factory() factory.protocol = RobotComm factory.clients = [] reactor.listenTCP(11411, factory) reactor.run() rospy.spin()
def __init__(self, args): component.Component.__init__(self, "IPCInterface") ipc_dir = deluge.configmanager.get_config_dir("ipc") if not os.path.exists(ipc_dir): os.makedirs(ipc_dir) socket = os.path.join(ipc_dir, "deluge-gtk") if deluge.common.windows_check(): # If we're on windows we need to check the global mutex to see if deluge is # already running. import win32event import win32api import winerror self.mutex = win32event.CreateMutex(None, False, "deluge") if win32api.GetLastError() != winerror.ERROR_ALREADY_EXISTS: # Create listen socket self.factory = Factory() self.factory.protocol = IPCProtocolServer import random port = random.randrange(20000, 65535) reactor.listenTCP(port, self.factory) # Store the port number in the socket file open(socket, "w").write(str(port)) # We need to process any args when starting this process process_args(args) else: # Send to existing deluge process port = int(open(socket, "r").readline()) self.factory = ClientFactory() self.factory.args = args self.factory.protocol = IPCProtocolClient reactor.connectTCP("127.0.0.1", port, self.factory) reactor.run() sys.exit(0) else: # Find and remove any restart tempfiles old_tempfile = glob(os.path.join(ipc_dir, 'tmp*deluge')) for f in old_tempfile: os.remove(f) lockfile = socket + ".lock" log.debug("Checking if lockfile exists: %s", lockfile) if os.path.lexists(lockfile) or os.path.lexists(socket): try: os.kill(int(os.readlink(lockfile)), 0) except OSError: log.debug("Removing lockfile since it's stale.") try: os.remove(lockfile) except OSError, ex: log.error("Failed to delete IPC lockfile file: %s", ex) try: os.remove(socket) except OSError, ex: log.error("Failed to delete IPC socket file: %s", ex)
def test_socks4(host_addr, host_port): factory = Factory() factory.protocol = UrlFetcher endpoint = TCP4SocksClientEndpoint(reactor, '', 1080, host_addr, host_port, timeout=1) endpoint.connect(factory)
def startBlaze(): #Globals.serverIP = "192.168.1.5" Globals.serverIP = "127.0.0.1" #MySQL Data Globals.dbHost = "127.0.0.1" Globals.dbUser = "******" Globals.dbPass = "******" Globals.dbDatabase = "db" CheckMySqlConn() serverPath = os.path.abspath(os.path.dirname(__file__)) privkeyPath = os.path.join(serverPath,'crt','privkey.pem') cacertPath = os.path.join(serverPath,'crt','cacert.pem') # SSLInfo = ssl.DefaultOpenSSLContextFactory(privkeyPath, cacertPath) # ctx = SSLInfo.getContext() # ctx.set_verify((SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT), verifyCallback) factory = Factory() factory.protocol = GosRedirector.GOSRedirector reactor.listenTCP(42127, factory) print("[SSL REACTOR] GOSREDIRECTOR STARTED [42127]") factory = Factory() factory.protocol = BlazeMain_Client.BLAZEHUB reactor.listenTCP(10041, factory) print("[TCP REACTOR] BLAZE CLIENT [10041]") factory = Factory() factory.protocol = BlazeMain_Server.BLAZEHUB reactor.listenTCP(10071, factory) print("[TCP REACTOR] BLAZE SERVER [10071]") # sites = server.Site(Https.Simple()) # reactor.listenSSL(443, sites, SSLInfo) # print("[WEB REACTOR] Https [443]") reactor.run()
def connect(self): tcpEndpoint = TCP4ClientEndpoint(self._reactor, self._hostname, self._port) factory = Factory() factory.server = self factory.protocol = SSHTransport factory.serverConnected = Deferred() factory.serverConnected.addCallback(lambda *i: self) d = tcpEndpoint.connect(factory) d.addErrback(factory.serverConnected.errback) return factory.serverConnected
def main(http_host='127.0.0.1', http_base_dir='e:\\tmp'): if os.name != 'nt': from twisted.internet import epollreactor epollreactor.install() from twisted.internet import reactor server = VmFileServer(http_host=http_host, http_base_dir=http_base_dir) factory = Factory() factory.protocol = lambda: VmFileProtocol(server) reactor.listenTCP(4444, factory) reactor.run()
def test_listenDefaultHost(self): """ L{MemoryReactor.listenTCP}, L{MemoryReactor.listenSSL} and L{MemoryReactor.listenUNIX} will return an L{IListeningPort} whose C{getHost} method returns an L{IAddress}; C{listenTCP} and C{listenSSL} will have a default host of C{'0.0.0.0'}, and a port that reflects the value passed, and C{listenUNIX} will have a name that reflects the path passed. """ memoryReactor = MemoryReactor() for port in [memoryReactor.listenTCP(8242, Factory()), memoryReactor.listenSSL(8242, Factory(), None)]: verifyObject(IListeningPort, port) address = port.getHost() verifyObject(IAddress, address) self.assertEqual(address.host, '0.0.0.0') self.assertEqual(address.port, 8242) port = memoryReactor.listenUNIX(b"/path/to/socket", Factory()) verifyObject(IListeningPort, port) address = port.getHost() verifyObject(IAddress, address) self.assertEqual(address.name, b"/path/to/socket")
def setUp(self): self.factory = Factory() self.factory.protocol = self.protocol self.port = reactor.listenTCP(0, self.factory) self.testPort = self.port.getHost().port args = self.configArgs.copy() args['host'] = self.configArgs.get('host', 'localhost') args['port'] = self.configArgs.get('port', self.testPort) args['username'] = self.configArgs.get('username', '') args['password'] = self.configArgs.get('password', '') self.config = SMPPClientConfig(**args)
def __init__(self): ''' clientID 矿工的ID, SHA256的随机数 rnd 神秘字符串 port 监听端口 ''' global _port self.factory = Factory() self.factory.protocol = RClient reactor.listenTCP(_port, self.factory) #reactor.callInThread(Client.aSillyBlockingMethod, "2 seconds have passed") reactor.run()
def master(options): """ Start of the master process. """ if not options.silence: print "Master started on PID %s" % os.getpid() # start embedded Web server if asked for (this only runs on master) ## if options.port: webdir = File(".") web = Site(webdir) web.log = lambda _: None # disable annoyingly verbose request logging reactor.listenTCP(options.port, web) # we just need some factory like thing .. it won't be used on master anyway # for actual socket accept ## factory = Factory() # create socket, bind and listen .. port = reactor.listenTCP(options.wsport, factory, backlog=options.backlog) # .. but immediately stop reading: we only want to accept on workers, not master port.stopReading() # fire off background workers ## for i in range(options.workers): args = [ executable, "-u", __file__, "--fd", str(port.fileno()), "--cpuid", str(i) ] # pass on cmd line args to worker .. args.extend(sys.argv[1:]) reactor.spawnProcess(None, executable, args, childFDs={ 0: 0, 1: 1, 2: 2, port.fileno(): port.fileno() }, env=os.environ) reactor.run()