本文實例講述了Python簡單實現的代理服務器端口映射功能。分享給大家供大家參考,具體如下:
一 代碼
1、模擬服務端代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
import sys import socket import threading #回復消息,原樣返回 def replyMessage(conn): while True : data = conn.recv( 1024 ) conn.send(data) if data.decode().lower() = = 'bye' : break conn.close() def main(): sockScr = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sockScr.bind(('', port)) sockScr.listen( 200 ) while True : try : conn, addr = sockScr.accept() #只允許特定主機訪問本服務器 if addr[ 0 ] ! = onlyYou: conn.close() continue #創建并啟動線程 t = threading.Thread(target = replyMessage, args = (conn,)) t.start() except : print ( 'error' ) if __name__ = = '__main__' : try : #獲取命令行參數 port = int (sys.argv[ 1 ]) onlyYou = sys.argv[ 2 ] main() except : print ( 'Must give me a number as port' ) |
2、模擬代理服務器代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
import sys import socket import threading def middle(conn, addr): #面向服務器的Socket sockDst = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sockDst.connect((ipServer,portServer)) while True : data = conn.recv( 1024 ).decode() print ( '收到客戶端消息:' + data) if data = = '不要發給服務器' : conn.send( '該消息已被代理服務器過濾' .encode()) print ( '該消息已過濾' ) elif data.lower() = = 'bye' : print ( str (addr) + '客戶端關閉連接' ) break else : sockDst.send(data.encode()) print ( '已轉發服務器' ) data_fromServer = sockDst.recv( 1024 ).decode() print ( '收到服務器回復的消息:' + data_fromServer) if data_fromServer = = '不要發給客戶端' : conn.send( '該消息已被代理服務器修改' .encode()) print ( '消息已被篡改' ) else : conn.send(b 'Server reply:' + data_fromServer.encode()) print ( '已轉發服務器消息給客戶端' ) conn.close() sockDst.close() def main(): sockScr = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sockScr.bind(('', portScr)) sockScr.listen( 200 ) print ( '代理已啟動' ) while True : try : conn, addr = sockScr.accept() t = threading.Thread(target = middle, args = (conn, addr)) t.start() print ( '新客戶:' + str (addr)) except : pass if __name__ = = '__main__' : try : #(本機IP地址,portScr)<==>(ipServer,portServer) #代理服務器監聽端口 portScr = int (sys.argv[ 1 ]) #服務器IP地址與端口號 ipServer = sys.argv[ 2 ] portServer = int (sys.argv[ 3 ]) main() except : print ( 'Sth error' ) |
3、模擬客戶端代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import sys import socket def main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip, port)) while True : data = input ( 'What do you want to ask:' ) sock.send(data.encode()) print (sock.recv( 1024 ).decode()) if data.lower() = = 'bye' : break sock.close() if __name__ = = '__main__' : try : #代理服務器的IP地址和端口號 ip = sys.argv[ 1 ] port = int (sys.argv[ 2 ]) main() except : print ( 'Sth error' ) |
二 運行結果
三 運行說明
從結果可以看出,代理服務器代碼能夠對客戶端和服務器之間的內容進行記錄,也能夠修改雙方通信內容,這樣實際存在潛在危險。只要代理服務想這樣做,客戶在網絡上的通信就沒有什么隱私可言了,因此如果涉及金錢交易,最好不要使用代理服務器。
希望本文所述對大家Python程序設計有所幫助。
原文鏈接:https://blog.csdn.net/chengqiuming/article/details/78601163