##language:zh [[self:解读_PyTwisted|返回目录]] -------------- ''' Twisted服务器开发技巧(2) - 端口与权限的游戏 ''' = Twisted服务器开发技巧(2) - 端口与权限的游戏 = 1024,这个数字在端口中代表着权限。如果你不是root,哪么将不能随便启动这个数字以内的侦听端口。但有时,你却希望用一个非root用户来进行这个服务的处理。当然,除了这些,Twisted还有一些有效的帮助你进行服务运行的功能。 接上次,我们来看以下代码: {{{ #!python from twisted.internet import protocol, reactor, defer, utils from twisted.protocols import basic class FingerProtocol(basic.LineReceiver): def lineReceived(self, user): self.factory.getUser(user ).addErrback(lambda _: "Internal error in server" ).addCallback(lambda m: (self.transport.write(m+"\r\n"), self.transport.loseConnection())) class FingerFactory(protocol.ServerFactory): protocol = FingerProtocol def getUser(self, user): return utils.getProcessOutput("finger", [user]) reactor.listenTCP(1079, FingerFactory()) reactor.run() }}} 我希望让它运行于hd用户whell组的权限下,侦听的端口是79。显然是不好搞的事,但是twisted却是轻松的事: {{{ #!python application = service.Application('finger', uid=1000, gid=0) factory = FingerFactory() internet.TCPServer(79, factory).setServiceParent( service.IServiceCollection(application)) }}} 使用这三行,换了最后的ractor的设置和运行。保存为finger.tac文件。 如果我用python finger.py来运行,在ps命令时得到的就是: {{{ root 95883 3.2 3.8 6044 4836 p1 S+ 11:26下午 0:00.26 python finger.py }}} 但如果我用 {{{ twisted -ny finger.tac }}} 就将看到: {{{ hd 95886 2.5 4.5 6888 5660 p1 S+ 11:27下午 0:00.29 /usr/local/bin/python /usr/local/bin/twistd -ny finger.tac }}} 显然,我们的服务运行在了79端口上,而且是使用了hd用户的身分来运行。 其实,twisted命令还给我们提供了许多有用的参数: {{{ root% twistd -ny finger.tac # just like before root% twistd -y finger.tac # daemonize, keep pid in twistd.pid root% twistd -y finger.tac --pidfile=finger.pid root% twistd -y finger.tac --rundir=/ root% twistd -y finger.tac --chroot=/var root% twistd -y finger.tac -l /var/log/finger.log root% twistd -y finger.tac --syslog # just log to syslog root% twistd -y finger.tac --syslog --prefix=twistedfinger # use given prefix }}} 大家仔细试试罢。我们可以节省大量的时间来写业务逻辑,而不用去考虑这些系统功能的问题了。啊门,感谢佛祖给了我们这么多好东东哟。 --------------- [[self:解读_PyTwisted|返回目录]]