python實現簡單的TCP代理伺服器

NO IMAGE
1 Star2 Stars3 Stars4 Stars5 Stars 給文章打分!
Loading...

本文例項講述了python實現簡單的TCP代理伺服器的方法,分享給大家供大家參考。

具體實現程式碼如下:


# -*- coding: utf-8 -*-
'''
filename:rtcp.py
@desc:
利用python的socket埠轉發,用於遠端維護
如果連線不到遠端,會sleep 36s,最多嘗試200(即兩小時)
@usage:
./rtcp.py stream1 stream2
stream為:l:port或c:host:port
l:port表示監聽指定的本地埠
c:host:port表示監聽遠端指定的埠
@author: watercloud, zd, knownsec team
@web: www.knownsec.com, blog.knownsec.com
@date: 2009-7
'''
import socket
import sys
import threading
import time
streams = [None, None] # 存放需要進行資料轉發的兩個資料流(都是SocketObj物件)
debug = 1 # 除錯狀態 0 or 1
def _usage():
print 'Usage: ./rtcp.py stream1 stream2\nstream : l:port or c:host:port'
def _get_another_stream(num):
'''
從streams獲取另外一個流物件,如果當前為空,則等待
'''
if num == 0:
num = 1
elif num == 1:
num = 0
else:
raise "ERROR"
while True:
if streams[num] == 'quit':
print("can't connect to the target, quit now!")
sys.exit(1)
if streams[num] != None:
return streams[num]
else:
time.sleep(1)
def _xstream(num, s1, s2):
'''
交換兩個流的資料
num為當前流編號,主要用於除錯目的,區分兩個迴路狀態用。
'''
try:
while True:
#注意,recv函式會阻塞,直到對端完全關閉(close後還需要一定時間才能關閉,最快關閉方法是shutdow)
buff = s1.recv(1024)
if debug > 0:
print num,"recv"
if len(buff) == 0: #對端關閉連線,讀不到資料
print num,"one closed"
break
s2.sendall(buff)
if debug > 0:
print num,"sendall"
except :
print num,"one connect closed."
try:
s1.shutdown(socket.SHUT_RDWR)
s1.close()
except:
pass
try:
s2.shutdown(socket.SHUT_RDWR)
s2.close()
except:
pass
streams[0] = None
streams[1] = None
print num, "CLOSED"
def _server(port, num):
'''
處理服務情況,num為流編號(第0號還是第1號)
'''
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.bind(('0.0.0.0', port))
srv.listen(1)
while True:
conn, addr = srv.accept()
print "connected from:", addr
streams[num] = conn # 放入本端流物件
s2 = _get_another_stream(num) # 獲取另一端流物件
_xstream(num, conn, s2)
def _connect(host, port, num):
''' 處理連線,num為流編號(第0號還是第1號)
@note: 如果連線不到遠端,會sleep 36s,最多嘗試200(即兩小時)
'''
not_connet_time = 0
wait_time = 36
try_cnt = 199
while True:
if not_connet_time > try_cnt:
streams[num] = 'quit'
print('not connected')
return None
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
conn.connect((host, port))
except Exception, e:
print ('can not connect %s:%s!' % (host, port))
not_connet_time  = 1
time.sleep(wait_time)
continue
print "connected to %s:%i" % (host, port)
streams[num] = conn #放入本端流物件
s2 = _get_another_stream(num) #獲取另一端流物件
_xstream(num, conn, s2)
if __name__ == '__main__':
if len(sys.argv) != 3:
_usage()
sys.exit(1)
tlist = [] # 執行緒列表,最終存放兩個執行緒物件
targv = [sys.argv[1], sys.argv[2] ]
for i in [0, 1]:
s = targv[i] # stream描述 c:ip:port 或 l:port
sl = s.split(':')
if len(sl) == 2 and (sl[0] == 'l' or sl[0] == 'L'): # l:port
t = threading.Thread(target=_server, args=(int(sl[1]), i))
tlist.append(t)
elif len(sl) == 3 and (sl[0] == 'c' or sl[0] == 'C'): # c:host:port
t = threading.Thread(target=_connect, args=(sl[1], int(sl[2]), i))
tlist.append(t)
else:
_usage()
sys.exit(1)
for t in tlist:
t.start()
for t in tlist:
t.join()
sys.exit(0)

完整例項程式碼點選此處本站下載

希望本文所述對大家的Python程式設計有所幫助。

您可能感興趣的文章:

Python寫的Socks5協議代理伺服器Python實現簡單的代理伺服器僅用50行Python程式碼實現一個簡單的代理伺服器Python實現TCP協議下的埠對映功能的指令碼程式示例Python實現的FTP通訊客戶端與伺服器端功能示例python快速建立超簡單的web伺服器的實現方法Python搭建FTP伺服器的方法示例嘗試用最短的Python程式碼來實現伺服器和代理伺服器python實現通過代理伺服器訪問遠端url的方法Python簡單實現的代理伺服器埠對映功能示例

相關文章

程式語言 最新文章