Python下的twisted框架入门指引
什么是twisted?
twisted是一个用python语言写的事件驱动的网络框架,他支持很多种协议,包括UDP,TCP,TLS和其他应用层协议,比如HTTP,SMTP,NNTM,IRC,XMPP/Jabber。 非常好的一点是twisted实现和很多应用层的协议,开发人员可以直接只用这些协议的实现。其实要修改Twisted的SSH服务器端实现非常简单。很多时候,开发人员需要实现protocol类。
一个Twisted程序由reactor发起的主循环和一些回调函数组成。当事件发生了,比如一个client连接到了server,这时候服务器端的事件会被触发执行。
用Twisted写一个简单的TCP服务器
下面的代码是一个TCPServer,这个server记录客户端发来的数据信息。
==== code1.py ==== import sys from twisted.internet.protocol import ServerFactory from twisted.protocols.basic import LineReceiver from twisted.python import log from twisted.internet import reactor class CmdProtocol(LineReceiver): delimiter = '\n' def connectionMade(self): self.client_ip = self.transport.getPeer()[1] log.msg("Client connection from %s" % self.client_ip) if len(self.factory.clients) >= self.factory.clients_max: log.msg("Too many connections. bye !") self.client_ip = None self.transport.loseConnection() else: self.factory.clients.append(self.client_ip) def connectionLost(self, reason): log.msg('Lost client connection. Reason: %s' % reason) if self.client_ip: self.factory.clients.remove(self.client_ip) def lineReceived(self, line): log.msg('Cmd received from %s : %s' % (self.client_ip, line)) class MyFactory(ServerFactory): protocol = CmdProtocol def __init__(self, clients_max=10): self.clients_max = clients_max self.clients = [] log.startLogging(sys.stdout) reactor.listenTCP(9999, MyFactory(2)) reactor.run()
下面的代码至关重要:
from twisted.internet import reactor reactor.run()
这两行代码会启动reator的主循环。
在上面的代码中我们创建了"ServerFactory"类,这个工厂类负责返回“CmdProtocol”的实例。 每一个连接都由实例化的“CmdProtocol”实例来做处理。 Twisted的reactor会在TCP连接上后自动创建CmdProtocol的实例。如你所见,protocol类的方法都对应着一种事件处理。
当client连上server之后会触发“connectionMade"方法,在这个方法中你可以做一些鉴权之类的操作,也可以限制客户端的连接总数。每一个protocol的实例都有一个工厂的引用,使用self.factory可以访问所在的工厂实例。
上面实现的”CmdProtocol“是twisted.protocols.basic.LineReceiver的子类,LineReceiver类会将客户端发送的数据按照换行符分隔,每到一个换行符都会触发lineReceived方法。稍后我们可以增强LineReceived来解析命令。
Twisted实现了自己的日志系统,这里我们配置将日志输出到stdout
当执行reactor.listenTCP时我们将工厂绑定到了9999端口开始监听。
user@lab:~/TMP$ python code1.py 2011-08-29 13:32:32+0200 [-] Log opened. 2011-08-29 13:32:32+0200 [-] __main__.MyFactory starting on 9999 2011-08-29 13:32:32+0200 [-] Starting factory <__main__.MyFactory instance at 0x227e320 2011-08-29 13:32:35+0200 [__main__.MyFactory] Client connection from 127.0.0.1 2011-08-29 13:32:38+0200 [CmdProtocol,0,127.0.0.1] Cmd received from 127.0.0.1 : hello server
使用Twisted来调用外部进程
下面我们给前面的server添加一个命令,通过这个命令可以读取/var/log/syslog的内容
import sys import os from twisted.internet.protocol import ServerFactory, ProcessProtocol from twisted.protocols.basic import LineReceiver from twisted.python import log from twisted.internet import reactor class TailProtocol(ProcessProtocol): def __init__(self, write_callback): self.write = write_callback def outReceived(self, data): self.write("Begin lastlog\n") data = [line for line in data.split('\n') if not line.startswith('==')] for d in data: self.write(d + '\n') self.write("End lastlog\n") def processEnded(self, reason): if reason.value.exitCode != 0: log.msg(reason) class CmdProtocol(LineReceiver): delimiter = '\n' def processCmd(self, line): if line.startswith('lastlog'): tailProtocol = TailProtocol(self.transport.write) reactor.spawnProcess(tailProtocol, '/usr/bin/tail', args=['/usr/bin/tail', '-10', '/var/log/syslog']) elif line.startswith('exit'): self.transport.loseConnection() else: self.transport.write('Command not found.\n') def connectionMade(self): self.client_ip = self.transport.getPeer()[1] log.msg("Client connection from %s" % self.client_ip) if len(self.factory.clients) >= self.factory.clients_max: log.msg("Too many connections. bye !") self.client_ip = None self.transport.loseConnection() else: self.factory.clients.append(self.client_ip) def connectionLost(self, reason): log.msg('Lost client connection. Reason: %s' % reason) if self.client_ip: self.factory.clients.remove(self.client_ip) def lineReceived(self, line): log.msg('Cmd received from %s : %s' % (self.client_ip, line)) self.processCmd(line) class MyFactory(ServerFactory): protocol = CmdProtocol def __init__(self, clients_max=10): self.clients_max = clients_max self.clients = [] log.startLogging(sys.stdout) reactor.listenTCP(9999, MyFactory(2)) reactor.run()
在上面的代码中,没从客户端接收到一行内容后会执行processCmd方法,如果收到的一行内容是exit命令,那么服务器端会断开连接,如果收到的是lastlog,我们要吐出一个子进程来执行tail命令,并将tail命令的输出重定向到客户端。这里我们需要实现ProcessProtocol类,需要重写该类的processEnded方法和outReceived方法。在tail命令有输出时会执行outReceived方法,当进程退出时会执行processEnded方法。
如下是执行结果样例:
user@lab:~/TMP$ python code2.py 2011-08-29 15:13:38+0200 [-] Log opened. 2011-08-29 15:13:38+0200 [-] __main__.MyFactory starting on 9999 2011-08-29 15:13:38+0200 [-] Starting factory <__main__.MyFactory instance at 0x1a5a3f8> 2011-08-29 15:13:47+0200 [__main__.MyFactory] Client connection from 127.0.0.1 2011-08-29 15:13:58+0200 [CmdProtocol,0,127.0.0.1] Cmd received from 127.0.0.1 : test 2011-08-29 15:14:02+0200 [CmdProtocol,0,127.0.0.1] Cmd received from 127.0.0.1 : lastlog 2011-08-29 15:14:05+0200 [CmdProtocol,0,127.0.0.1] Cmd received from 127.0.0.1 : exit 2011-08-29 15:14:05+0200 [CmdProtocol,0,127.0.0.1] Lost client connection. Reason: [Failure instance: Traceback (failure with no frames): <class 'twisted.internet.error.ConnectionDone'>: Connection was closed cleanly.
可以使用下面的命令作为客户端发起命令:
user@lab:~$ netcat 127.0.0.1 9999 test Command not found. lastlog Begin lastlog Aug 29 15:02:03 lab sSMTP[5919]: Unable to locate mail Aug 29 15:02:03 lab sSMTP[5919]: Cannot open mail:25 Aug 29 15:02:03 lab CRON[4945]: (CRON) error (grandchild #4947 failed with exit status 1) Aug 29 15:02:03 lab sSMTP[5922]: Unable to locate mail Aug 29 15:02:03 lab sSMTP[5922]: Cannot open mail:25 Aug 29 15:02:03 lab CRON[4945]: (logcheck) MAIL (mailed 1 byte of output; but got status 0x0001, #012) Aug 29 15:05:01 lab CRON[5925]: (root) CMD (command -v debian-sa1 > /dev/null && debian-sa1 1 1) Aug 29 15:10:01 lab CRON[5930]: (root) CMD (test -x /usr/lib/atsar/atsa1 && /usr/lib/atsar/atsa1) Aug 29 15:10:01 lab CRON[5928]: (CRON) error (grandchild #5930 failed with exit status 1) Aug 29 15:13:21 lab pulseaudio[3361]: ratelimit.c: 387 events suppressed End lastlog exit
使用Deferred对象
reactor是一个循环,这个循环在等待事件的发生。 这里的事件可以是数据库操作,也可以是长时间的计算操作。 只要这些操作可以返回一个Deferred对象。Deferred对象可以自动得在事件发生时触发回调函数。reactor会block当前代码的执行。
现在我们要使用Defferred对象来计算SHA1哈希。
import sys import os import hashlib from twisted.internet.protocol import ServerFactory, ProcessProtocol from twisted.protocols.basic import LineReceiver from twisted.python import log from twisted.internet import reactor, threads class TailProtocol(ProcessProtocol): def __init__(self, write_callback): self.write = write_callback def outReceived(self, data): self.write("Begin lastlog\n") data = [line for line in data.split('\n') if not line.startswith('==')] for d in data: self.write(d + '\n') self.write("End lastlog\n") def processEnded(self, reason): if reason.value.exitCode != 0: log.msg(reason) class HashCompute(object): def __init__(self, path, write_callback): self.path = path self.write = write_callback def blockingMethod(self): os.path.isfile(self.path) data = file(self.path).read() # uncomment to add more delay # import time # time.sleep(10) return hashlib.sha1(data).hexdigest() def compute(self): d = threads.deferToThread(self.blockingMethod) d.addCallback(self.ret) d.addErrback(self.err) def ret(self, hdata): self.write("File hash is : %s\n" % hdata) def err(self, failure): self.write("An error occured : %s\n" % failure.getErrorMessage()) class CmdProtocol(LineReceiver): delimiter = '\n' def processCmd(self, line): if line.startswith('lastlog'): tailProtocol = TailProtocol(self.transport.write) reactor.spawnProcess(tailProtocol, '/usr/bin/tail', args=['/usr/bin/tail', '-10', '/var/log/syslog']) elif line.startswith('comphash'): try: useless, path = line.split(' ') except: self.transport.write('Please provide a path.\n') return hc = HashCompute(path, self.transport.write) hc.compute() elif line.startswith('exit'): self.transport.loseConnection() else: self.transport.write('Command not found.\n') def connectionMade(self): self.client_ip = self.transport.getPeer()[1] log.msg("Client connection from %s" % self.client_ip) if len(self.factory.clients) >= self.factory.clients_max: log.msg("Too many connections. bye !") self.client_ip = None self.transport.loseConnection() else: self.factory.clients.append(self.client_ip) def connectionLost(self, reason): log.msg('Lost client connection. Reason: %s' % reason) if self.client_ip: self.factory.clients.remove(self.client_ip) def lineReceived(self, line): log.msg('Cmd received from %s : %s' % (self.client_ip, line)) self.processCmd(line) class MyFactory(ServerFactory): protocol = CmdProtocol def __init__(self, clients_max=10): self.clients_max = clients_max self.clients = [] log.startLogging(sys.stdout) reactor.listenTCP(9999, MyFactory(2)) reactor.run()
blockingMethod从文件系统读取一个文件计算SHA1,这里我们使用twisted的deferToThread方法,这个方法返回一个Deferred对象。这里的Deferred对象是调用后马上就返回了,这样主进程就可以继续执行处理其他的事件。当传给deferToThread的方法执行完毕后会马上触发其回调函数。如果执行中出错,blockingMethod方法会抛出异常。如果成功执行会通过hdata的ret返回计算的结果。
推荐的twisted阅读资料
http://twistedmatrix.com/documents/current/core/howto/defer.html http://twistedmatrix.com/documents/current/core/howto/process.html http://twistedmatrix.com/documents/current/core/howto/servers.html
API文档:
http://twistedmatrix.com/documents/current/api/twisted.html

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











PHP와 Python은 고유 한 장점과 단점이 있으며 선택은 프로젝트 요구와 개인 선호도에 달려 있습니다. 1.PHP는 대규모 웹 애플리케이션의 빠른 개발 및 유지 보수에 적합합니다. 2. Python은 데이터 과학 및 기계 학습 분야를 지배합니다.

CentOS 시스템에서 Pytorch GPU 가속도를 활성화하려면 Cuda, Cudnn 및 GPU 버전의 Pytorch를 설치해야합니다. 다음 단계는 프로세스를 안내합니다. CUDA 및 CUDNN 설치 CUDA 버전 호환성 결정 : NVIDIA-SMI 명령을 사용하여 NVIDIA 그래픽 카드에서 지원하는 CUDA 버전을보십시오. 예를 들어, MX450 그래픽 카드는 CUDA11.1 이상을 지원할 수 있습니다. Cudatoolkit 다운로드 및 설치 : NVIDIACUDATOOLKIT의 공식 웹 사이트를 방문하여 그래픽 카드에서 지원하는 가장 높은 CUDA 버전에 따라 해당 버전을 다운로드하여 설치하십시오. CUDNN 라이브러리 설치 :

Python과 JavaScript는 커뮤니티, 라이브러리 및 리소스 측면에서 고유 한 장점과 단점이 있습니다. 1) Python 커뮤니티는 친절하고 초보자에게 적합하지만 프론트 엔드 개발 리소스는 JavaScript만큼 풍부하지 않습니다. 2) Python은 데이터 과학 및 기계 학습 라이브러리에서 강력하며 JavaScript는 프론트 엔드 개발 라이브러리 및 프레임 워크에서 더 좋습니다. 3) 둘 다 풍부한 학습 리소스를 가지고 있지만 Python은 공식 문서로 시작하는 데 적합하지만 JavaScript는 MDNWebDocs에서 더 좋습니다. 선택은 프로젝트 요구와 개인적인 이익을 기반으로해야합니다.

Docker는 Linux 커널 기능을 사용하여 효율적이고 고립 된 응용 프로그램 실행 환경을 제공합니다. 작동 원리는 다음과 같습니다. 1. 거울은 읽기 전용 템플릿으로 사용되며, 여기에는 응용 프로그램을 실행하는 데 필요한 모든 것을 포함합니다. 2. Union 파일 시스템 (Unionfs)은 여러 파일 시스템을 스택하고 차이점 만 저장하고 공간을 절약하고 속도를 높입니다. 3. 데몬은 거울과 컨테이너를 관리하고 클라이언트는 상호 작용을 위해 사용합니다. 4. 네임 스페이스 및 CGroup은 컨테이너 격리 및 자원 제한을 구현합니다. 5. 다중 네트워크 모드는 컨테이너 상호 연결을 지원합니다. 이러한 핵심 개념을 이해 함으로써만 Docker를 더 잘 활용할 수 있습니다.

Minio Object Storage : Centos System Minio 하의 고성능 배포는 Go Language를 기반으로 개발 한 고성능 분산 객체 저장 시스템입니다. Amazons3과 호환됩니다. Java, Python, JavaScript 및 Go를 포함한 다양한 클라이언트 언어를 지원합니다. 이 기사는 CentOS 시스템에 대한 Minio의 설치 및 호환성을 간단히 소개합니다. CentOS 버전 호환성 Minio는 다음을 포함하되 이에 국한되지 않는 여러 CentOS 버전에서 확인되었습니다. CentOS7.9 : 클러스터 구성, 환경 준비, 구성 파일 설정, 디스크 파티셔닝 및 미니를 다루는 완전한 설치 안내서를 제공합니다.

CentOS 시스템에 대한 Pytorch 분산 교육에는 다음 단계가 필요합니다. Pytorch 설치 : 전제는 Python과 PIP가 CentOS 시스템에 설치된다는 것입니다. CUDA 버전에 따라 Pytorch 공식 웹 사이트에서 적절한 설치 명령을 받으십시오. CPU 전용 교육의 경우 다음 명령을 사용할 수 있습니다. PipinStalltorchtorchvisiontorchaudio GPU 지원이 필요한 경우 CUDA 및 CUDNN의 해당 버전이 설치되어 있는지 확인하고 해당 PyTorch 버전을 설치하려면 설치하십시오. 분산 환경 구성 : 분산 교육에는 일반적으로 여러 기계 또는 단일 기계 다중 GPU가 필요합니다. 장소

CentOS 시스템에 Pytorch를 설치할 때는 적절한 버전을 신중하게 선택하고 다음 주요 요소를 고려해야합니다. 1. 시스템 환경 호환성 : 운영 체제 : CentOS7 이상을 사용하는 것이 좋습니다. Cuda 및 Cudnn : Pytorch 버전 및 Cuda 버전은 밀접하게 관련되어 있습니다. 예를 들어, pytorch1.9.0은 cuda11.1을 필요로하고 Pytorch2.0.1은 cuda11.3을 필요로합니다. CUDNN 버전도 CUDA 버전과 일치해야합니다. Pytorch 버전을 선택하기 전에 호환 CUDA 및 CUDNN 버전이 설치되었는지 확인하십시오. 파이썬 버전 : Pytorch 공식 지점

Centos의 최신 버전으로 Pytorch를 업데이트하면 다음 단계를 수행 할 수 있습니다. 방법 1 : PIP를 사용하여 PIP 업데이트 : 먼저 PIP의 PIP 버전이 최신 버전의 PyTorch를 제대로 설치하지 못할 수 있기 때문에 PIP가 최신 버전인지 확인하십시오. PipinStall-UpgradePip Unin Incalls of Pytorch (설치된 경우) : PipuninStalltorchtorchvisiontorchaudio 설치 최신 정보
