开发学院软件开发Python 使用 Twisted 框架进行网络编程,第 4 部分 阅读

使用 Twisted 框架进行网络编程,第 4 部分

 2008-11-13 13:13:47 来源:WEB开发网   
核心提示: 清单1. ssh-weblog.py#!/usr/bin/env python"""Monitor a remote weblog over SSHUSAGE: ssh-weblog.py user@host logfile"""

清单1. ssh-weblog.py

  #!/usr/bin/env python
"""Monitor a remote weblog over SSH
 USAGE: ssh-weblog.py user@host logfile
"""
from twisted.conch.ssh import transport, userauth, connection, channel
from twisted.conch.ssh.common import NS
from twisted.internet import defer, protocol, reactor
from twisted.python import log
from getpass import getpass
import struct, sys, os
import webloglib as wll
USER,HOST,CMD = None,None,None
class Transport(transport.SSHClientTransport):
  def verifyHostKey(self, hostKey, fingerprint):
    print 'host key fingerprint: %s' % fingerprint
    return defer.succeed(1)
  def connectionSecure(self):
    self.requestService(UserAuth(USER, Connection()))
class UserAuth(userauth.SSHUserAuthClient):
  def getPassword(self):
    return defer.succeed(getpass("password: "))
  def getPublicKey(self):
    return # Empty implementation: always use password auth
class Connection(connection.SSHConnection):
  def serviceStarted(self):
    self.openChannel(Channel(2**16, 2**15, self))
class Channel(channel.SSHChannel):
  name = 'session'  # must use this exact string
  def openFailed(self, reason):
      print '"%s" failed: %s' % (CMD,reason)
  def channelOpen(self, data):
    self.welcome = data  # Might display/process welcome screen
    d = self.conn.sendRequest(self,'exec',NS(CMD),wantReply=1)
  def dataReceived(self, data):
    recs = data.strip().split('n')
    for rec in recs:
      hit = [field.strip('"') for field in wll.log_fields(rec)]
      resource = hit[wll.request].split()[1]
      referrer = hit[wll.referrer]
      if resource=='/kill-weblog-monitor':
        print "Bye bye..."
        self.closed()
        return
      elif hit[wll.status]=='200' and hit[wll.referrer]!='-':
        print referrer, ' -->', resource
  def closed(self):
    self.loseConnection()
    reactor.stop()
if __name__=='__main__':
  if len(sys.argv) < 3:
    sys.stderr.write('__doc__')
    sys.exit()
  USER, HOST = sys.argv[1].split('@')
  CMD = 'tail -f -n 1 '+sys.argv[2]
  protocol.ClientCreator(reactor, Transport).connectTCP(HOST, 22)
  reactor.run()

上一页  1 2 3 4 5 6  下一页

Tags:使用 Twisted 框架

编辑录入:爽爽 [复制链接] [打 印]
[]
  • 好
  • 好的评价 如果觉得好,就请您
      0%(0)
  • 差
  • 差的评价 如果觉得差,就请您
      0%(0)
赞助商链接