socket.socket
socket
是 Python 标准库中的模块,用于进行 TCP/UDP 连接。
假设服务器地址是 example.com
,端口是 1234
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import socket
s = socket.socket()
s.connect(("example.com", 1234))
s.sendall(b"Hello\n")
data = s.recv(1024)
print("Received:", data.decode())
s.close()
|
如果服务器会发送非常多的内容,则需要一直循环接收服务器发送的消息:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import socket
s = socket.socket()
s.connect(("example.com", 1234))
data = b""
while True: part = s.recv(1024) if not part: break data += part
lines = data.decode().splitlines() for line in lines: print(line)
s.close()
|
也可以使用time.sleep()
来确保收到完整信息:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import socket import time
s = socket.socket()
s.connect(("example.com", 1234))
s.sendall(b"Hello\n")
time.sleep(0.5)
data = s.recv(1024)
print("Received:", data.decode())
s.close()
|
SSL连接
SSL 连接会比普通的TCP连接(socket.socket())多一步加密的步骤
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import socket import ssl
sock = socket.socket()
s = ssl.wrap_socket(sock)
s.connect(("example.com", 1234))
s.sendall(b"Hello\n")
data = s.recv(1024)
print("Received:", data.decode())
s.close()
|
pwntools 是专门为 Pwn 题目设计的 Python 库,封装了 socket。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| from pwn import *
r = remote("example.com", 1234)
r.sendline(b"Hello")
response = r.recvall()
print("Received:", response.decode())
r.close()
|
比起socket,pwn拥有更高级的功能:
1 2 3 4 5 6 7 8 9 10
| r.recvuntil(b"\n")
r.interactive()
response = r.recvall()
r.sendafter(b"input:", b"1234")
|
remote()
里也可以启用 SSL:
1 2 3 4 5 6 7 8 9 10
| from pwn import *
r = remote("example.com", 1234, ssl=True)
r.sendline(b"Hello")
response = r.recvline() print("Received:", response.decode())
r.close()
|
总的来说,在做CTF题目时,pwn的remote
可以完成所有与服务器的交互。
socket.socket
没有的remote
有,socket.socket
没有的remote
也有。