本文整理汇总了Python中twisted.internet.reactor.listenSSL函数的典型用法代码示例。如果您正苦于以下问题:Python listenSSL函数的具体用法?Python listenSSL怎么用?Python listenSSL使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了listenSSL函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: start
def start(config):
"""Start twisted event loop and the fun should begin..."""
host = config.get('broker', 'host')
port = int(config.get('broker', 'port'))
username = config.get('broker', 'username')
password = config.get('broker', 'password')
fileServerPort = int(config.get('fileserver', 'port'))
fileServerDirectory = config.get('fileserver', 'directory')
# Start File Server
try:
privkey = os.path.abspath( os.path.dirname(__file__) + '/services/privkey.pem')
cacert = os.path.abspath( os.path.dirname(__file__) + '/services/cacert.pem')
logger.info('Using SSL, privkey = %s, cacert = %s' % (privkey, cacert))
reactor.listenSSL(fileServerPort, FileServerFactory(fileServerDirectory),
ssl.DefaultOpenSSLContextFactory(privkey, cacert) )
logger.info('Listening on port %d, serving files from directory: %s' % (fileServerPort, fileServerDirectory))
except:
logger.fatal("Unable to start file server at port: %d, please check." % fileServerPort)
stompProtocolFactory = StompProtocolFactory()
reactor.connectTCP(host, port, stompProtocolFactory)
reactor.run()
return internet.TCPClient(host, port, stompProtocolFactory)
示例2: Start
def Start():
Globals.serverIP = "192.168.1.40"
#MySQL Data
Globals.dbHost = "127.0.0.1"
Globals.dbUser = "user"
Globals.dbPass = "pass"
Globals.dbDatabase = "db"
CheckMySqlConn()
SSLInfo = ssl.DefaultOpenSSLContextFactory('crt/privkey.pem', 'crt/cacert.pem')
factory = Factory()
factory.protocol = GosRedirector.GOSRedirector
reactor.listenSSL(42127, factory, SSLInfo)
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()
示例3: process_nmap_commands
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()
示例4: main
def main():
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)-s: %(message)s')
args = _getArgs()
ippool = IPPool(args.remote)
ippool.register(args.local)
factory = SSTPProtocolFactory(pppd=args.pppd, pppdConfigFile=args.pppd_config,
local=args.local, remotePool=ippool)
if args.no_ssl:
logging.info('Running without SSL.')
reactor.listenTCP(args.listen_port, factory)
else:
certificate = _load_cert(args.pem_cert)
if certificate is None:
logging.critical('Cannot read certificate.')
sys.exit(2)
return
reactor.listenSSL(args.listen_port, factory,
certificate.options(), interface=args.listen)
logging.info('Listening on %s:%s...' % (args.listen, args.listen_port))
reactor.run()
示例5: startagent
def startagent(port = myport):
if agentdaemonize:
print "Daemonizing"
from hqdaemon import daemonize
daemonize('/dev/null','/tmp/daemon.log','/tmp/daemon.log')
if sys.platform.find("win32") != -1:
import win32file
win32file._setmaxstdio(2048)
if use_ssl:
print "Agent is started on port ", myport, " SSL is enabled "
try:
myContextFactory = ssl.DefaultOpenSSLContextFactory(agent_ssl_key, agent_ssl_cert)
ctx = myContextFactory.getContext()
# ctx.set_verify( SSL.VERIFY_PEER, verifyCallback)
# ctx.set_options( SSL.OP_ALL )
# Since we have self-signed certs we have to explicitly
# tell the server to trust them.
ctx.load_verify_locations(agent_ssl_pem)
except Exception, e:
print "Failed to start, SSL keys are specified but do not exist ", e
sys.exit(1)
reactor.listenSSL(myport, ExecuteActionFactory(), myContextFactory)
reactor.run(installSignalHandlers=False)
示例6: build_reactor
def build_reactor(options, **kwargs):
web_socket_instance = FilteredWebSocketFactory(**kwargs)
subscriber = kwargs.pop("subscriber", None)
if options.key and options.cert:
with open(options.key) as keyFile:
with open(options.cert) as certFile:
cert = ssl.PrivateCertificate.loadPEM(keyFile.read() + certFile.read())
reactor.listenSSL(options.port, web_socket_instance, cert.options())
else:
reactor.listenTCP(
options.port,
web_socket_instance
)
if subscriber is not None:
reactor.callInThread(
subscriber.listener,
web_socket_instance
)
reactor.addSystemEventTrigger(
"before",
"shutdown",
subscriber.kill
)
# Start the consumer loop
consumer_loop = LoopingCall(
web_socket_instance.consumer
)
consumer_loop.start(0.001, now=False)
return web_socket_instance
示例7: main
def main():
args = _getArgs()
logging.basicConfig(level=args.log_level,
format='%(asctime)s %(levelname)-s: %(message)s')
logging.addLevelName(5, 'VERBOSE')
ippool = IPPool(args.remote)
ippool.register(args.local)
if args.no_ssl:
logging.info('Running without SSL.')
factory = SSTPProtocolFactory(pppd=args.pppd, pppdConfigFile=args.pppd_config,
local=args.local, remotePool=ippool, certHash=None)
reactor.listenTCP(args.listen_port, factory)
else:
cert = _load_cert(args.pem_cert)
sha1 = cert.digest('sha1').replace(':', '').decode('hex')
sha256 = cert.digest('sha256').replace(':', '').decode('hex')
cert_options = cert.options()
if args.ciphers:
cert_options.getContext().set_cipher_list(args.ciphers)
factory = SSTPProtocolFactory(pppd=args.pppd, pppdConfigFile=args.pppd_config,
local=args.local, remotePool=ippool, certHash=[sha1, sha256])
reactor.listenSSL(args.listen_port, factory,
cert_options, interface=args.listen)
logging.info('Listening on %s:%s...' % (args.listen, args.listen_port))
reactor.run()
示例8: main
def main():
"""This runs the protocol on port 25000"""
factory = protocol.Factory()
factory.protocol = Echo
reactor.listenSSL(25000, factory,
ssl.DefaultOpenSSLContextFactory(KEYFILE, CERTFILE))
reactor.run()
示例9: main
def main():
""" Run the server. """
# setup logger first
initLog()
# Load the client's self-signed certificate.
clientCert = open(CLIENT_CERT_FILE).read()
clientCertObj = ssl.Certificate.loadPEM(clientCert)
# Load the server's key and the server's self-signed certificate.
serverKey = open(SERVER_KEY_FILE).read()
serverCert = open(SERVER_CERT_FILE).read()
serverPEM = serverKey + serverCert
serverCertObj = ssl.PrivateCertificate.loadPEM(serverPEM)
# Create an SSL context factory. Passing the client's certificate along enables client authentication.
sslContextFactory = serverCertObj.options(clientCertObj)
kinectServerFactory = KinectServerFactory()
# Set the Twisted reactor up to listen for connections. For each incoming connection, create a KinectServer
# (using the KinectServerFactory) and create an SSL context (using the sslContextFactory). The SSL context is used
# to verify clients and set up an SSL layer. The KinectServer is used to handle all messages their decrypted state;
# messages are relayed to all other connections.
reactor.listenSSL(PORT, kinectServerFactory, sslContextFactory)
# Run the reactor (which enters Twisted's main loop).
reactor.run()
示例10: main
def main(argv):
(logLevel, sslPort, httpPort,
certFile, keyFile, userName,
groupName, background,
incomingInterface) = parseOptions(argv)
privateKey = initializeKey(keyFile)
database = initializeDatabase()
sslFactory = initializeFactory(database, privateKey)
connectFactory = http.HTTPFactory(timeout=10)
connectFactory.protocol = ConnectChannel
reactor.listenSSL(sslPort, sslFactory, ServerContextFactory(certFile, keyFile),
interface=incomingInterface)
reactor.listenSSL(4242, sslFactory, ServerContextFactory(certFile, keyFile),
interface=incomingInterface)
reactor.listenTCP(port=httpPort, factory=connectFactory,
interface=incomingInterface)
initializeLogging(logLevel)
checkPrivileges(userName, groupName)
if background:
print "\nconvergence " + str(gVersion) + " by Moxie Marlinspike backgrounding..."
convergence.daemonize.createDaemon()
else:
print "\nconvergence " + str(gVersion) + " by Moxie Marlinspike running..."
writePidFile()
dropPrivileges(userName, groupName)
reactor.run()
示例11: runApplication
def runApplication():
opts = Options()
opts.parseOptions()
common.initLogs(opts['logfile'])
common.installReactor(opts['reactor'])
config = common.loadConfig(opts['config'])
#starting services with options from config
if opts['ssl']:
reactor.listenSSL(
config.getint('finger', 'port'),
FingerFactory(),
DefaultOpenSSLContextFactory(
config.get('ssl', 'cert'),
config.get('ssl', 'private')
)
)
reactor.listenSSL(
config.getint('web', 'port'),
server.Site(SomeLeafResource()),
DefaultOpenSSLContextFactory(
config.get('ssl', 'cert'),
config.get('ssl', 'private')
)
)
else:
reactor.listenTCP(config.getint('finger', 'port'), FingerFactory())
reactor.listenTCP(config.getint('web', 'port'), server.Site(SomeLeafResource()))
reactor.run()
示例12: main
def main():
parser = OptionParser()
parser.add_option('-l', '--loglevel', default='info', dest='logLevel', help='This sets the logging level you have these options: debug, info, warning, error, critical \t\tThe standard value is info')
parser.add_option('-p', '--port', default=4443, type='int', dest='port', help='This options lets you use a custom port instead of 443 (use a port > 1024 to run as non root user)')
parser.add_option('--logfile', default=None, dest='logfile', help='Log to a file instead of stdout.')
(options, _) = parser.parse_args()
x = logging.getLogger()
x.setLevel(log_levels[options.logLevel])
if options.logfile != None:
h = logging.FileHandler(options.logfile)
else:
h = logging.StreamHandler()
f = logging.Formatter(u"%(levelname)s %(message)s")
h.setFormatter(f)
x.addHandler(h)
x.info("Starting server on port {0}".format(options.port))
reactor.listenSSL(options.port, SiriFactory(), ssl.DefaultOpenSSLContextFactory('keys/server.key', 'keys/server.crt'))
reactor.run()
x.info("Server shutdown complete")
示例13: start_listening
def start_listening(self):
config = self.get_config()
if not config.no_tls and config.bind_port is not None:
reactor.listenSSL(
config.bind_port,
Site(self.root_resource),
self.tls_context_factory,
interface=config.bind_host
)
logger.info("Synapse now listening on port %d", config.bind_port)
if config.unsecure_port is not None:
reactor.listenTCP(
config.unsecure_port,
Site(self.root_resource),
interface=config.bind_host
)
logger.info("Synapse now listening on port %d", config.unsecure_port)
metrics_resource = self.get_resource_for_metrics()
if metrics_resource and config.metrics_port is not None:
reactor.listenTCP(
config.metrics_port, Site(metrics_resource), interface="127.0.0.1",
)
logger.info("Metrics now running on 127.0.0.1 port %d", config.metrics_port)
示例14: main
def main(argv):
FLAGS(argv)
if not FLAGS.logfile and not FLAGS.daemonize:
# No log file and not daemonized.
log.startLogging(sys.stderr)
elif not FLAGS.logfile and FLAGS.daemonize:
# Daemonized, but no log file.
fd, name = tempfile.mkstemp(prefix='flamongo', suffix='.log')
os.close(fd)
sys.stderr.write('Logging to %s\n' % name)
log.startLogging(open(name, 'a'))
else:
f = open(FLAGS.logfile, 'a')
log.startLogging(f)
# FIXME
mongoengine.connect('flamongo')
# TODO define connection options.
site = server.Site(TopLevel(lambda: Connection()))
reactor.listenTCP(FLAGS.port, site)
try:
from twisted.internet import ssl
ssl_context = ssl.DefaultOpenSSLContextFactory(FLAGS.privatekey,
FLAGS.certificate)
reactor.listenSSL(FLAGS.secureport, site, ssl_context)
except ImportError:
# removes the partial import.
ssl = None
log.err('SSL not enabled. Needs PyOpenSSL.')
except Exception as ex:
log.err(str(ex))
if FLAGS.daemonize:
utils.daemonize()
reactor.run()
示例15: process_nmap_commands
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()