1. HTTP (超文本传输协议)
Python (使用 requests
库):
import requests response = requests.get('http://example.com') print(response.status_code) print(response.text)
2. FTP (文件传输协议)
Python (使用 ftplib
库):
from ftplib import FTP ftp = FTP('ftp.example.com') ftp.login(user='username', passwd='password') ftp.retrlines('LIST') ftp.quit()
3. SMTP (简单邮件传输协议)
Python (使用 smtplib
库):
import smtplib from email.mime.text import MIMEText msg = MIMEText('This is the body of the email.') msg['Subject'] = 'Subject' msg['From'] = 'sender@example.com' msg['To'] = 'recipient@example.com' with smtplib.SMTP('smtp.example.com') as server: server.login('username', 'password') server.send_message(msg)
4. DNS (域名系统)
Python (使用 socket
库):
import socket ip_address = socket.gethostbyname('example.com') print(ip_address)
5. Telnet
Python (使用 telnetlib
库):
import telnetlib host = 'example.com' port = 23 tn = telnetlib.Telnet(host, port) tn.write(b'HELP\n') response = tn.read_all().decode('ascii') print(response) tn.close()
6. SNMP (简单网络管理协议)
Python (使用 pysnmp
库):
from pysnmp.hlapi import * iterator = nextCmd( SnmpEngine(), CommunityData('public'), UdpTransportTarget(('example.com', 161)), ContextData(), ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0')) ) for (errorIndication, errorStatus, errorIndex, varBinds) in iterator: if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex)) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind]))
7. ICMP (互联网控制消息协议)
Python (使用 ping3
库):
from ping3 import ping, verbose_ping response_time = ping('example.com') print(f'Response time: {response_time} seconds') # 或者使用详细 ping verbose_ping('example.com')
8. NTP (网络时间协议)
Python (使用 ntplib
库):
import ntplib from time import ctime client = ntplib.NTPClient() response = client.request('pool.ntp.org') print(f'Time: {ctime(response.tx_time)}')
9. LDAP (轻量级目录访问协议)
Python (使用 ldap3
库):
from ldap3 import Server, Connection, ALL server = Server('ldap://example.com', get_info=ALL) conn = Connection(server, 'username', 'password', auto_bind=True) conn.search('dc=example,dc=com', '(objectClass=person)', attributes=['cn']) for entry in conn.entries: print(entry) conn.unbind()
10. MQTT (消息队列遥测传输)
Python (使用 paho-mqtt
库):
import paho.mqtt.client as mqtt def on_connect(client, userdata, flags, rc): print(f'Connected with result code {rc}') client.subscribe('test/topic') def on_message(client, userdata, msg): print(f'{msg.topic} {msg.payload.decode()}') client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect('broker.hivemq.com', 1883, 60) client.loop_forever()
11. WebSocket
Python (使用 websockets
库):
import asyncio import websockets async def hello(): uri = "ws://example.com:8765" async with websockets.connect(uri) as websocket: await websocket.send("Hello, World!") response = await websocket.recv() print(f"Received: {response}") asyncio.get_event_loop().run_until_complete(hello())
12. gRPC (Google 远程过程调用)
Python (使用 grpcio
库):
-
你首先需要定义
.proto
文件:syntax = "proto3"; service Greeter { rpc SayHello (HelloRequest) returns (HelloReply) {} } message HelloRequest { string name = 1; } message HelloReply { string message = 1; }
-
生成 Python 代码并实现服务端和客户端: 服务端 (server.py):
from concurrent import futures import grpc import hello_pb2 import hello_pb2_grpc class Greeter(hello_pb2_grpc.GreeterServicer): def SayHello(self, request, context): return hello_pb2.HelloReply(message='Hello, %s!' % request.name) def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) hello_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) server.add_insecure_port('[::]:50051') server.start() server.wait_for_termination() if __name__ == '__main__': serve()
客户端 (client.py):
import grpc import hello_pb2 import hello_pb2_grpc def run(): with grpc.insecure_channel('localhost:50051') as channel: stub = hello_pb2_grpc.GreeterStub(channel) response = stub.SayHello(hello_pb2.HelloRequest(name='World')) print("Greeter client received: " + response.message) if __name__ == '__main__': run()
13. Redis
Python (使用 redis
库):
import redis r = redis.Redis(host='localhost', port=6379, db=0) r.set('foo', 'bar') value = r.get('foo') print(value.decode('utf-8'))
14. FTP (文件传输协议)
Python (使用 ftplib
库):
from ftplib import FTP ftp = FTP('ftp.example.com') ftp.login('username', 'password') ftp.cwd('/path/to/directory') # 列出目录内容 ftp.retrlines('LIST') # 下载文件 with open('localfile.txt', 'wb') as local_file: ftp.retrbinary('RETR remote_file.txt', local_file.write) # 上传文件 with open('localfile.txt', 'rb') as local_file: ftp.storbinary('STOR remote_file.txt', local_file) ftp.quit()
15. SFTP (安全文件传输协议)
Python (使用 paramiko
库):
import paramiko transport = paramiko.SFTPClient.from_transport(paramiko.Transport(('sftp.example.com', 22))) transport.connect(username='username', password='password') # 列出目录内容 print(transport.listdir('/path/to/directory')) # 下载文件 transport.get('/path/to/remote_file.txt', 'localfile.txt') # 上传文件 transport.put('localfile.txt', '/path/to/remote_file.txt') transport.close()
16. SMTP (简单邮件传输协议)
Python (使用 smtplib
库):
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart msg = MIMEMultipart() msg['From'] = 'your_email@example.com' msg['To'] = 'recipient@example.com' msg['Subject'] = 'Subject Here' body = 'This is the body of the email.' msg.attach(MIMEText(body, 'plain')) server = smtplib.SMTP('smtp.example.com', 587) server.starttls() server.login('your_email@example.com', 'your_password') text = msg.as_string() server.sendmail('your_email@example.com', 'recipient@example.com', text) server.quit()
17. HTTP/2
Python (使用 hyper
库):
from hyper import HTTP20Connection conn = HTTP20Connection('example.com') conn.request('GET', '/') response = conn.get_response() print(response.status) print(response.read().decode('utf-8'))
18. CoAP (约束应用协议)
Python (使用 coapthon
库):
from coapthon.client.helperclient import HelperClient client = HelperClient(server=("coap.example.com", 5683)) response = client.get("path/to/resource") print(response.pretty_print()) client.stop()
19. UPnP (通用即插即用协议)
Python (使用 miniupnpc
库):
import miniupnpc upnp = miniupnpc.UPnP() upnp.discover() upnp.selectigd() # 添加端口映射 upnp.addportmapping(12345, 'TCP', upnp.lanaddr, 12345, 'test', '') # 删除端口映射 upnp.deleteportmapping(12345, 'TCP')
20. ZMQ (ZeroMQ)
Python (使用 pyzmq
库): 服务器 (server.py):
import zmq context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:5555") while True: message = socket.recv() print(f"Received request: {message}") socket.send(b"World")
客户端 (client.py):
import zmq context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect("tcp://localhost:5555") socket.send(b"Hello") message = socket.recv() print(f"Received reply: {message}")
21. AMQP (高级消息队列协议)
Python (使用 pika
库): 生产者 (producer.py):
import pika connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='hello') channel.basic_publish(exchange='', routing_key='hello', body='Hello World!') print(" [x] Sent 'Hello World!'") connection.close()
消费者 (consumer.py):
import pika def callback(ch, method, properties, body): print(f" [x] Received {body}") connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='hello') channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C') channel.start_consuming()