首页 >> 大全

自己要怎么做一个隧道代理?隧道代理搭建教程

2023-12-16 大全 34 作者:考证青年

首先,你手上得有一批HTTP代理,要么自己去爬免费的资源(不是那么建议,免费的可用率真的非常低),要么就自己去和HTTP厂商购买动态短效代理,要么就从0开始,自己买服务器……总之,你手上得有一批可以使用起来的HTTP代理,搭建起来你的HTTP代理池子。

接下来就是使用Redis的Hash这个数据结构周期性访问url,拉取当前最新可用的HTTP代理。

代码如下:

"""
ProxyManager.py
~~~~~~~~~~~~~~~~~~~~~
简易代理池管理工具,直接从URL中读取所有
最新的代理,并写入Redis。
"""
import yaml
import time
import json
import redis
import datetime
import requestsclass ProxyManager:def __init__(self):self.config = self.read_config()self.redis_config = self.config['redis']self.client = redis.Redis(host=self.redis_config['host'],password=self.redis_config['password'],port=self.redis_config['port'])self.instance_dict = {}def read_config(self):with open('config.yaml') as f:config = yaml.safe_load(f.read())return configdef read_ip(self):resp = requests.get(self.config['proxy']).textif '{' in resp:return []proxy_list = resp.split()return proxy_listdef delete_ip(self, live_ips, pool_ips):ip_to_removed = set(pool_ips) - set(live_ips)if ip_to_removed:print('ip to be removed:', ip_to_removed)self.client.hdel(self.redis_config['key'], *list(ip_to_removed))def add_new_ips(self, live_ips, pool_ips):ip_to_add = set(live_ips) - set(pool_ips)if ip_to_add:print('ip to add:', ip_to_add)ips = {}for ip in ip_to_add:ips[ip] = json.dumps({'private_ip': ip,'ts': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')})self.client.hset(self.redis_config['key'], mapping=ips)def run(self):while True:live_ips = self.read_ip()pool_ips = [x.decode() for x in self.client.hgetall(self.redis_config['key'])]self.delete_ip(live_ips, pool_ips)self.add_new_ips(live_ips, pool_ips)time.sleep(40)if __name__ == '__main__':manager = ProxyManager()manager.run()

​通常,HTTP代理从厂商那购买,是有个存活周期的,我们要在HTTP代理的存货周期内使用,所以更换的周期也要在这时间段内。更换的时候,采用了增量更换的方式。把当前拉取的IP和Redis里面的已有IP进行对比。不在这次拉取的IP全部从Redis移除,然后把新增的IP加到Redis中。

当然,我们需要确保从URL拉下来的代理也进行有效性检查,发现无效的立刻移除,可以进行少量测试:

# python 3.6+import requestsurl = "百度一下,你就知道"ip, port = "39.137.95.73", "8080"proxies = {"http": f"http://{ip}:{port}"}#空白位置为测试HTTP代理和HTTP代理使用端口headers = {"User-Agent": "Mozilla/5.0"}#响应头res = requests.get(url, proxies=proxies, headers=headers)#发起请求print(res.status_code) #返回响应码

只需要更改这里的ip就可以自动判断是否可用。

如果这里的状态码为200就表示这个ip可用,如果是502等其他的状态码就表示这个ip不可用。

2.实现自动转发

隧道代理_隧道代理如何搭建_

我们可以使用实现自动转发。

对应的配置文件如下图所示:

worker_processes  16;        #nginx worker 数量
error_log /usr/local/openresty/nginx/logs/error.log;   #指定错误日志文件路径
events {worker_connections 1024;
}stream {## TCP 代理日志格式定义log_format tcp_proxy '$remote_addr [$time_local] ''$protocol $status $bytes_sent $bytes_received ''$session_time "$upstream_addr" ''"$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"';## TCP 代理日志配置access_log /usr/local/openresty/nginx/logs/access.log tcp_proxy;open_log_file_cache off;## TCP 代理配置upstream backend{server 127.0.0.2:1101;# 爱写啥写啥  反正下面的代码也给你改了balancer_by_lua_block {-- 初始化balancerlocal balancer = require "ngx.balancer"local host = ""local port = 0host = ngx.ctx.proxy_hostport = ngx.ctx.proxy_port-- 设置 balancerlocal ok, err = balancer.set_current_peer(host, port)if not ok thenngx.log(ngx.ERR, "failed to set the peer: ", err)end}}server {preread_by_lua_block{local redis = require("resty.redis")--创建实例local redis_instance = redis:new()--设置超时(毫秒)redis_instance:set_timeout(3000)--建立连接,请在这里配置Redis 的 IP 地址、端口号、密码和用到的 Keylocal rhost = "123.45.67.89"local rport = 6739local rpass = "abcdefg"local rkey = "proxy:pool"local ok, err = redis_instance:connect(rhost, rport)ngx.log(ngx.ERR, "1111111 ", ok, " ", err)-- 如果没有密码,移除下面这一行local res, err = redis_instance:auth(rpass)local res, err = redis_instance:hkeys(rkey)if not res thenngx.log(ngx.ERR,"res num error : ", err)return redis_instance:close()endmath.randomseed(tostring(ngx.now()):reverse():sub(1, 6))local proxy = res[math.random(#res)]local colon_index = string.find(proxy, ":")local proxy_ip = string.sub(proxy, 1, colon_index - 1)local proxy_port = string.sub(proxy, colon_index + 1)ngx.log(ngx.ERR,"redis data = ", proxy_ip, ":", proxy_port);ngx.ctx.proxy_host = proxy_ipngx.ctx.proxy_port = proxy_portredis_instance:close()}#  下面是本机的端口,也就是爬虫固定写死的端口listen 0.0.0.0:9976; #监听本机地址和端口,当使用keeplived的情况下使用keeplived VIPproxy_connect_timeout 3s;proxy_timeout 10s;proxy_pass backend; #这里填写对端的地址}
}

有需要的友友们可以根据配置文件稍作修改。

3.启动

设置好了这些配置以后,使用来启动它:

from openresty/openresty:centoscopy nginx_redis.conf /usr/local/openresty/nginx/conf/nginx.conf

然后,执行命令构建和运行:

docker build --network host -t tunnel_proxy:0.01 .
docker run --name tunnel_proxy --network host -it tunnel_proxy:0.01

隧道代理如何搭建__隧道代理

运行以后,你会看到的命令行似乎卡住了。这是正常请求。因为需要你有了请求,它才会输出内容。

现在,你可以用赶快写一段代码来进行验证:

import requests
import timeproxies = {'http': 'http://13.88.220.207:9976'}
for _ in range(10):resp = requests.get('http://httpbin.org/ip', proxies=proxies).textprint(resp)time.sleep(1)

运行效果如下图所示。

​配置nginx.如果出现问题,要根据具体报错信息来解决。

自己搭建隧道代理,实际工作生活中只能拿来练手,毕竟如果是在公司上班,这个要花费很多时间成本去做开发和维护,过程中如果有遇到问题,也需要及时维护,同时也无法保证自己搭建的隧道代理的稳定性,毕竟要考虑的因素实在太多了,是用什么基础搭建的?免费的HTTP代理的可用率、代理服务器的稳定性……

4.隧道代理厂商

当然,市面上的隧道代理厂商也没有多到让人无法挑的地步,主要还是这么几家:

PS:像青果网络这种,定时更换周期的,通道数居然是10,和其他家有明显的区别,蛮神奇的。

关于我们

最火推荐

小编推荐

联系我们


版权声明:本站内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 88@qq.com 举报,一经查实,本站将立刻删除。备案号:桂ICP备2021009421号
Powered By Z-BlogPHP.
复制成功
微信号:
我知道了