socketの应用 : Proxy&http-send

2023-05-17 10:35:14 浏览数 (1)

socketの应用 : Proxy&http-send

下面是几个socket的常用方式, 模板都是网上扒拉其他师傅的, 一直都是直接import使用的, 因为是太久之前的事了, 就不找师傅们的原文了, 见谅。

请求转发

不管发过来的请求是什么最终都请求一个文件包数据并返回

代码语言:javascript复制
#!/usr/bin/python2
# coding=utf-8

import time
import socket
import urllib
import random

import urlparse

desc_host = '0.0.0.0'
desc_port = 9999

source_url = "http://127.0.0.1/ctf-temp/"

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while 1:
    try:
        server.bind((desc_host, desc_port))
        break
    except:
        # desc_port=random.randint(1000,10000)
        pass

print "Proxying to %s:%s ..."%(desc_host, desc_port)

while 1:
    server.listen(5)
    conn, addr = server.accept()
    recv=conn.recv(1024)
    print recv
    request = recv.split(" ")[1]
    # page = urllib.urlopen(urlparse.urljoin(source_url, request)).read()
    page = urllib.urlopen(urlparse.urljoin("http://vps:port/hack.so","")).read()
    print addr[0], addr[1], request
    print time.strftime('%Y-%m-%d %H:%M:%S')," [%s:%s] %s"%(addr[0], addr[1], request)
    # print page
    head1 = """HTTP/1.1 200 OK
Date: Mon, 18 Apr 2022 11:25:06 GMT
Server: Apache/2.4.38 (Debian)
Last-Modified: Mon, 18 Apr 2022 10:29:12 GMT
ETag: "3ea0-5dceb3b355267"
Accept-Ranges: bytes
Content-Length: 16032
Keep-Alive: timeout=5, max=100
Connection: Keep-Alivetnn""".encode()
    head2=b"""HTTP/1.1 200 OK
Server: gunicorn
Date: Mon, 18 Apr 2022 13:38:20 GMT
Connection: close
Content-Type: text/plain
Content-Length: 51
Content-Disposition: attachment; filename=hack.sotnn"""
    conn.sendall(head2 page)
    conn.close()

返回输入数据包

代码语言:javascript复制
#!/usr/bin/python3
#codind:utf-8
import random
import socket,sys

#创建一个socket对象
socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host="0.0.0.0"
port = 9999
file=b""
if "-h" in sys.argv:
    host = sys.argv[sys.argv.index("-h")   1]
if "-p" in sys.argv:
    port = int(sys.argv[sys.argv.index("-p")   1])
if "-f" in sys.argv:
    fileName = sys.argv[sys.argv.index("-f")   1]
    f = open(fileName, "rb")
    file = f.read()
#绑定地址
while 1:
    try:
        socket_server.bind((host, port))
        break
    except:
        port=random.randint(1000,10000)
print("Your Server Objects is: ",host)
print("Your Server Port is: ",port)
#设置监听
socket_server.listen(5)
# socket_server.accept()返回一个元组, 元素1为客户端的socket对象, 元素2为客户端的地址(ip地址,端口号)
client_socket, address = socket_server.accept()

#while循环是为了让对话持续
while True:
    #接收客户端的请求
    recvmsg = client_socket.recv(1024)
    #把接收到的数据进行解码
    strData = recvmsg.decode("utf-8")
    #设置退出条件
    if strData == 'exit':
        break
    print("接收: n%s" % strData)
    #输入
    if file:
        client_socket.send(file)
        break
    else:
        msg = input("发送: n")
        #发送数据,需要进行编码
        client_socket.send(msg.encode("utf-8"))
        break
#关闭服务器端
socket_server.close()

socket发送请http请求

代码语言:javascript复制
import socket

def http_sockrt(text):
    global host,port
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((host, port))
    sock.send(text.encode())
    response = b''
    rec = sock.recv(1024)
    while rec:
        response  = rec
        rec = sock.recv(1024)
    return response.decode()
url = 'www.zhangdongshengtech.com'
port = 80

# 创建TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务端
sock.connect((url, port))
# 创建请求消息头
request_url = 'GET /article-types/6/ HTTP/1.1rnHost: www.zhangdongshengtech.comrnConnection: closernrn'
print(request_url)
# 发送请求
sock.send(request_url.encode())
response = b''
# 接收返回的数据
rec = sock.recv(1024)
while rec:
    response  = rec
    rec = sock.recv(1024)
print(response.decode())

一个代码稍多一点的Proxy

代码语言:javascript复制
import socket
import threading
import select
import time

IsNeedAuth=False
Username='admin'
Password='123456'
Port=7456

def prxoy(sock,address): 
    cs = sock  
    DspPort=0
    DspAddr=''    
    try:
        recv= cs.recv(512)
        VER=recv[0:1]
        #MethodNum=ord(recv[1:2])
        #Methods=[]
        #for i in range(0,MethodNum):
           # Methods.append(ord(recv[2 i:3 i]))
        if(IsNeedAuth):          #Need AUTHENICATION
            cs.send(b'x05x02')     #Reply
            recv= cs.recv(1024)
            Ver=recv[0:1]
            UserLen=ord(recv[1:2])
            User=recv[2:2 UserLen]
            PassLen=ord(recv[2 UserLen:3 UserLen])
            Pass=recv[3 UserLen:3 UserLen PassLen]
            if (User==Username and Pass==Password):
                cs.send(Ver 'x00')
            else:
                cs.send(Ver 'xff')
                cs.close()
                return 
        else:
            cs.send(VER 'x00')  #  NO AUTHENICATION REQUEST
        try :
            recv= cs.recv(1024)
        except Exception,ex:
             print 'Client is Closed'
             return
        CMD=ord(recv[1:2])
        ATYP=ord(recv[3:4])
        if(CMD ==0x01):             # CONNECT CMD
            if (ATYP==03):                      # DOMAINNAME
                AddrLen=ord(recv[4:5])
                DspPort=256*ord(recv[5 AddrLen:5 AddrLen 1]) ord(recv[1 5 AddrLen:5 AddrLen 2])
                DspAddr=socket.gethostbyname(recv[5:5 AddrLen])
            elif (ATYP==01):                     #IPV4
                if (recv.count('.')==4):    # Asiic  format  split by  '.'
                    AddrLen=ord(recv[4:5])
                    DspAddr=recv[5:5 AddrLen]
                    DspPort=256*ord(recv[5 AddrLen:5 AddrLen 1]) ord(recv[5 AddrLen 1:5 AddrLen 2])
                else:                                      #four hex number format
                    DspAddr=recv[4:8]
                    DspAddrr=''
                    for i in DspAddr:
                        DspAddrr  =str(ord(i)) '.'
                    DspAddr=DspAddrr[:-1]
                    DspPort=256*ord(recv[4 4:4 4 1]) ord(recv[4 4 1:4 4 2])
            else:
                print "IPV6 is not support"
                return
            cs.send(VER 'x00x00x01x00x00x00x00x00x00')   # REPLY
            forward(cs,DspAddr,DspPort)
        else :
            print "Don't suport  this Cmd",CMD
    except Exception,e:
        print e

def forward(cs,DspAddr,DspPort):
    try:
        #print DspAddr  'n'
        ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

        ss.connect((DspAddr, DspPort))
    except Exception,e:
                print "Connect to ",DspAddr,"Fail"
                return
    socks=[]
    socks.append(cs)
    socks.append(ss)
    while(True):
       try:
        r, w, e = select.select(socks, [], [])
        for s in r:
            if s is cs:
                recv=cs.recv(2048)
                caddr,cport= cs.getpeername()
                if (len(recv) >0):
                    saddr,sport=ss.getpeername()
                    print caddr,':',cport,'<',len(recv),'>',saddr,':',sport
                    ss.send(recv)

                else:
                    for sock in socks:
                        sock.close()
                    return
            elif s is ss:           
                recv=ss.recv(2048)
                saddr,sport= ss.getpeername()                
                if (len(recv) >0):
                    caddr,cport= cs.getpeername()
                    print saddr,':',sport,'<',len(recv),'>',caddr,':',cport
                    cs.send(recv)
                else:
                    for sock in socks:
                        sock.close()
                    return
       except Exception,e:
            print "Translate data error"
            break            

if __name__ == "__main__":
    ls = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ls.bind(('0.0.0.0',Port))
    ls.listen(500)
    while (True):
        clientSock, address = ls.accept()
        thread = threading.Thread(target=prxoy, args=(clientSock,address))
        thread.start()

0 人点赞