项目地址

码云:git@gitee.com:fourforward/proxy_ip__pmip.git

github:git@github.com:FourForward/pmip.git

华为云镜像:sudo docker pull registry.cn-hangzhou.aliyuncs.com/mth666/pmip:0.1

项目简介

这是一个 代理IP 的小demo,当前为0.1版本,可以做到在任意一台服务器上一键部署,一键启动,使该服务器为你提供代理IP服务。

该demo今后的发展方向是在内网机器上部署,通过统一的服务器集群来转发请求,可以做到在服务器数量有限的情况下,获得大量的代理IP。

当前环境为:

代理IP服务器环境:ubuntupythondjangorequestsuwsginginx# 没有列出版本号,默认为最新版本

启动项目

启动项目的前提是,首先你的服务器上要有 Docker

因为这里上传的是dockerfile文件和docker镜像

① 通过dockerfile生成一个镜像

如果是直接拉取的镜像可以省去这一步

进入项目文件夹,执行以下指令

docker build -t [镜像名字]:[版本号] .# 示例docker build -t pmip:0.1 .

②通过镜像创建容器并运行

docker run -d -p [服务器端口]:80 [镜像名字]:[版本号]# 示例docker run -d -p 8888:80 pmip:0.1

到这里就已经实现了代理IP的功能

使用方法

data = requests.post(url='http://[代理服务器IP]:[暴露的端口]',data={'username':'mth','password':'123456','data':[目标爬虫语句]})

其中 usernamepassword的值是默认的,如果要更改的话,可以进入容器目录:/home/PMIP/PMIP/settings.py 最下方可以更改为你自己的用户名和密码,更改完成之后需要重启uwsgi,指令是

# 查看容器docker ps# 进入容器docker exec -it [容器编号] /bin/bash# 修改django配置文件vim /home/PMIP/PMIP/settings.py# 用户名和密码在最下面# 先关闭uwsgips -ef | grep 'uwsgi' | grep -v grep | awk '{print $2}' | xargs sudo kill -9uwsgi --stop uwsgi.pid# 再启动uwsgi -i /home/PMIP/PMIP/uwsgi.ini# 退出容器并保持运行Ctrl+P+Q

测试

data = requests.post(url='http://127.0.0.1:8888',data={'username':'mth','password':'123456','data':'requests.get(url="http://www.baidu.com")'})

docker运行服务时指定使用外网ip docker 指定ip启动_git设置代理


dockerfile文件详解

FROM ubuntuMAINTAINER tina_han<553630934@qq.com># apt更换阿里源RUN sed -i s@/archive.ubuntu.com/@/mirrors.aliyun.com/@g /etc/apt/sources.listRUN apt-get cleanRUN apt-get updateRUN apt-get install -y vimRUN apt-get install -y python3RUN apt-get install -y python3-pip# pip3更换阿里源RUN pip3 config set global.index-url http://mirrors.aliyun.com/pypi/simpleRUN pip3 config set install.trusted-host mirrors.aliyun.com# 更新pip3RUN pip3 install pip -URUN pip3 install djangoRUN pip3 install requestsRUN pip3 install uwsgi# 设置时区RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtimeRUN echo 'Asia/Shanghai' >/etc/timezoneRUN apt-get install -y nginx# 更换nginx配置文件RUN rm /etc/nginx/sites-enabled/defaultCOPY default /etc/nginx/sites-enabled/# 导入项目文件ADD PMIP.tar.gz /home/# 启动nginx和uwsgi# CMD service nginx start# CMD uwsgi --ini /home/PMIP/PMIP/uwsgi.ini# CMD ["nginx","-g","daemon off;"]# 无论怎么组合都不行,要么服务直接死掉,要么uwsgi起不起来# 最后在网上找到一条将两条命令组合为一条的方法,测试成功CMD ["sh", "-c", "uwsgi -i /home/PMIP/PMIP/uwsgi.ini && nginx -g 'daemon off;'"]

转发实现

from django.http import HttpResponsefrom django.conf import settingsimport requestsdef agency(request):    """    代理IP服务器主程序    转发请求并返回响应    :param request:    :return:    """    data = eval(request.POST.get('data', '')) if request.POST.get('username','') == settings.USERNAME and request.POST.get('password', '') == settings.PASSWORD else ''    return HttpResponse(data)

其实就一行代码,我之前也没用过代理IP,不知道他们的转发逻辑是什么,反正我自己的转发逻辑很简单,就只有一行代码。