扭曲 https

发布于 2024-10-20 16:23:54 字数 71 浏览 2 评论 0原文

你好,我有一个运行着twisted的应用程序。我希望它通过 https 而不是 http 运行。我在哪里可以找到一个很好的例子?

Hi I have an app running with twisted. I want it to run over https instead of http. Where can I find a good example for that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

月光色 2024-10-27 16:23:54

您所需要做的就是使用 reactor.listenSSL 而不是 reactor.listenTCPhttp://twistedmatrix.com/documents/current/core/howto/ssl.html 涵盖了 reactor.listenSSL 的基础知识。

All you need to do is use reactor.listenSSL instead of reactor.listenTCP. http://twistedmatrix.com/documents/current/core/howto/ssl.html covers the basics of reactor.listenSSL.

有木有妳兜一样 2024-10-27 16:23:54

以下是在 SSL 上运行并具有基本身份验证的扭曲服务器的示例:

#!/usr/bin/env python

USERS={'admin': 'admin', 
        'user': 'user',
        'test': 'eW91IGFyZSBjcmF6eQo='}

"""
Twisted SSL webserver with basic authentication using plain in-memory passwords. 
The first argument is the path of the directory to serve; if not provided then the current folder is used (".").

INSTALL DEPENDENCIES:
    pip install twisted pyOpenSSL service_identity

GENERATE SSL CERTIFICATES:
    mkdir ~/.ssl && cd ~/.ssl
    openssl genrsa > privkey.pem
    openssl req -new -x509 -key privkey.pem -out cacert.pem -days 9999

USAGE:
    Requires running as root (normal users cannot bind to ports below 1024); 
    login with test_user/test_password

    sudo python twisted-web-ssl.py     # serve the current folder
    sudo python twisted-web-ssl.py /home
"""
import os
import sys

from twisted.web.static import File
from zope.interface import implements
from twisted.python import log
from twisted.internet import reactor, ssl
from twisted.web import server, resource, guard
from twisted.cred.portal import IRealm, Portal
from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
from twisted.python.log import startLogging

startLogging(sys.stdout)
home_dir = os.path.expanduser("~")

sslContext = ssl.DefaultOpenSSLContextFactory(
    os.path.join(home_dir, '.ssl/privkey.pem'),
    os.path.join(home_dir, '.ssl/cacert.pem'),
)

class SimpleRealm(object):
    implements(IRealm)

    def __init__(self, path):
        self.path = path

    def requestAvatar(self, avatarId, mind, *interfaces):

        if resource.IResource in interfaces:
            return resource.IResource, File(self.path), lambda: None

        raise NotImplementedError()


def main(root):
    log.startLogging(sys.stdout)
    # alternative credential storage implementations: https://twistedmatrix.com/documents/current/api/twisted.cred.checkers.ICredentialsChecker.html
    checkers = [InMemoryUsernamePasswordDatabaseDontUse(**USERS)]

    wrapper = guard.HTTPAuthSessionWrapper(
        Portal(SimpleRealm(root), checkers),
        [guard.DigestCredentialFactory('md5', 'whatever.com')])

    reactor.listenSSL(443, server.Site(resource=wrapper),
                      contextFactory=sslContext)
    reactor.run()


if __name__ == '__main__':
    root = sys.argv[1] if len(sys.argv) > 1  else '.'
    main(root)

Here is an example of a twisted server running on SSL with basic authentication:

#!/usr/bin/env python

USERS={'admin': 'admin', 
        'user': 'user',
        'test': 'eW91IGFyZSBjcmF6eQo='}

"""
Twisted SSL webserver with basic authentication using plain in-memory passwords. 
The first argument is the path of the directory to serve; if not provided then the current folder is used (".").

INSTALL DEPENDENCIES:
    pip install twisted pyOpenSSL service_identity

GENERATE SSL CERTIFICATES:
    mkdir ~/.ssl && cd ~/.ssl
    openssl genrsa > privkey.pem
    openssl req -new -x509 -key privkey.pem -out cacert.pem -days 9999

USAGE:
    Requires running as root (normal users cannot bind to ports below 1024); 
    login with test_user/test_password

    sudo python twisted-web-ssl.py     # serve the current folder
    sudo python twisted-web-ssl.py /home
"""
import os
import sys

from twisted.web.static import File
from zope.interface import implements
from twisted.python import log
from twisted.internet import reactor, ssl
from twisted.web import server, resource, guard
from twisted.cred.portal import IRealm, Portal
from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
from twisted.python.log import startLogging

startLogging(sys.stdout)
home_dir = os.path.expanduser("~")

sslContext = ssl.DefaultOpenSSLContextFactory(
    os.path.join(home_dir, '.ssl/privkey.pem'),
    os.path.join(home_dir, '.ssl/cacert.pem'),
)

class SimpleRealm(object):
    implements(IRealm)

    def __init__(self, path):
        self.path = path

    def requestAvatar(self, avatarId, mind, *interfaces):

        if resource.IResource in interfaces:
            return resource.IResource, File(self.path), lambda: None

        raise NotImplementedError()


def main(root):
    log.startLogging(sys.stdout)
    # alternative credential storage implementations: https://twistedmatrix.com/documents/current/api/twisted.cred.checkers.ICredentialsChecker.html
    checkers = [InMemoryUsernamePasswordDatabaseDontUse(**USERS)]

    wrapper = guard.HTTPAuthSessionWrapper(
        Portal(SimpleRealm(root), checkers),
        [guard.DigestCredentialFactory('md5', 'whatever.com')])

    reactor.listenSSL(443, server.Site(resource=wrapper),
                      contextFactory=sslContext)
    reactor.run()


if __name__ == '__main__':
    root = sys.argv[1] if len(sys.argv) > 1  else '.'
    main(root)
旧城空念 2024-10-27 16:23:54

HTTPS 是基于 SSL 的 HTTP。 HTTPS = HTTP + SSL/TLS。请参阅文档 http://twistedmatrix.com/documents/13.0。 0/core/howto/ssl.html#auto1http://twistedmatrix.com/documents/13.0.0/web/howto/using-twistedweb.html#auto2

这是一个简单的示例:

from twisted.internet import reactor, ssl
from twisted.web import server, resource

sslContext = ssl.DefaultOpenSSLContextFactory(
    '/Users/wucao/Desktop/https/2_gw2.vsgames.cn.key',  # Private Key
    '/Users/wucao/Desktop/https/1_gw2.vsgames.cn_bundle.crt',  # Certificate
)

class MainResource(resource.Resource):

    isLeaf = True

    def render_GET(self, request):
        request.responseHeaders.addRawHeader("Content-Type", "text/html; charset=utf-8")
        return "<html><body>Hello World</body></html>"


site = server.Site(MainResource())
reactor.listenSSL(443, site, sslContext)
reactor.run()

HTTPS is HTTP over SSL. HTTPS = HTTP + SSL/TLS. See document http://twistedmatrix.com/documents/13.0.0/core/howto/ssl.html#auto1 and http://twistedmatrix.com/documents/13.0.0/web/howto/using-twistedweb.html#auto2

This is the simple example:

from twisted.internet import reactor, ssl
from twisted.web import server, resource

sslContext = ssl.DefaultOpenSSLContextFactory(
    '/Users/wucao/Desktop/https/2_gw2.vsgames.cn.key',  # Private Key
    '/Users/wucao/Desktop/https/1_gw2.vsgames.cn_bundle.crt',  # Certificate
)

class MainResource(resource.Resource):

    isLeaf = True

    def render_GET(self, request):
        request.responseHeaders.addRawHeader("Content-Type", "text/html; charset=utf-8")
        return "<html><body>Hello World</body></html>"


site = server.Site(MainResource())
reactor.listenSSL(443, site, sslContext)
reactor.run()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文