搭建使用Socks Server 5 服务器

Published on with 0 views and 0 comments

需求

收到一个这样的需求:要求访问腾讯的一个服务,无论身在哪里,都必须通过制定 ip 访问此服务,因为公司之前的 VPN 是我搭的,领导找我做这个需求,但是 VPN 此事并没有能适配此需求,因为我的那个 VPN 只是针对内网服务才走 VPN 流量,而腾讯的相关服务需要走外网流量,而且出口 ip 这个时候需要被代理成指定 ip。所以此文章针对次任务做个记录。

Socks Server 5 搭建

下载软件

下载地址点这里

安装

*下载解压

yum -y install gcc gcc-c++ automake make pam-devel openldap-devel cyrus-sasl-devel openssl-devel
wget https://jaist.dl.sourceforge.net/project/ss5/ss5/3.8.9-8/ss5-3.8.9-8.tar.gz
tar zxvf ss5-3.8.9-8.tar.gz -C /usr/local/src
cd /usr/local/src/ss5-3.8.9
./configure
make && make install
  • 配置文件(加上认证配置)
[root@cjz ~]# vim /etc/opt/ss5/ss5.conf
...
# ///////////////////////////////////////////////////////////////////////////////////
#       SHost           SPort           Authentication
#
auth    0.0.0.0/0               -               u
...
# /////////////////////////////////////////////////////////////////////////////////////////////////
#      Auth     SHost           SPort   DHost           DPort   Fixup   Group   Band    ExpDate
#
permit u        0.0.0.0/0       -       0.0.0.0/0       -       -       -       -       -
...
  • 添加用户
[root@cjz ~]# vim /etc/opt/ss5/ss5.passwd 

cuijianzhe 5982943132425433
  • 配置代理端口(默认 1080)
[root@cjz ~]# cat /etc/sysconfig/ss5
# Add startup option here
SS5_OPTS=" -u root -b 0.0.0.0:8091"

代理客户端

代理客户端配置

1.添加代理服务器配置
image.png

  1. 添加过滤规则,访问指定域名才能走代理
    image.png

image.png

image.png
3.设置 dns 解析
image.png

image.png

问题:

如果出现下面的错误, 先创建 /var/run/ss5 目录后再启动 ss5 。

Can’t create pid file /var/run/ss5/ss5.pid
Can’t unlink pid file /var/run/ss5/ss5.pid

默认的日志文件路径: /var/log/ss5/ss5.log

测试

  • 百度页面查询 ip:

image.png

  • ip.cn 查询 ip

image.png

同步钉钉接口,定时更新密码文件

#!/usr/bin env python3
import requests
import json
import os
import pypinyin
import subprocess

'''
AppKey:
ding
AppSecret:
dingding
'''
corpId='ding'
corpSecret='dingding'

headers = {'Content-Type': 'application/json;charset=utf-8'}
api_url = "https://oapi.dingtalk.com/gettoken?appkey=%s≈psecret=%s"%(corpId,corpSecret)
def del_conf():
    CMD = "rm  -f /etc/opt/ss5/ss5.passwd" 
    subprocess.getoutput(CMD)
    
def get_token():
    try:
        res = requests.get(api_url,headers=headers)
        if res.status_code == 200:
            str_res = res.text
            token = (json.loads(str_res)).get('access_token')
            return token
    except:
        print('请求失败')

def get_bumenId(token):
    try:
        bumen_url = "https://oapi.dingtalk.com/department/list?access_token=%s&id=1"%(token)
        res_bumen = requests.get(bumen_url,headers=headers)
        str_bumen = res_bumen.text
        json_bumen = json.loads(str_bumen)
        code = json_bumen.get('errcode')
        if code != 0:
            print('接口返回错误,{}'.format(json_bumen.get('errmsg')))
        res = json_bumen.get('department')
        bname_list = []
        for i in res:
            bumen_name = i.get('name')
            bname_list.append(bumen_name)
            if bumen_name == '产品部':
                bumen_id = i.get('id')

        '''
        部门人员: 取出人员姓名和userid,作为login和passwd
        '''
        member_url = "https://oapi.dingtalk.com/user/simplelist?access_token=%s&department_id=%s"%(token,bumen_id)
        res_member = requests.get(member_url, headers=headers)
        json_member = json.loads(res_member.text)
        list_member = json_member.get('userlist')  # 取userlist列表出来
        info = {}   #构造用户名和密码,后面会写到配置文件中
        name_list = []
        passwd_list = []
        for staff_info in list_member:
            '''
            返回结果值格式:{'name': '李四', 'userid': '3008111850842061'}
            '''
            pinyin_name = ''.join(pypinyin.lazy_pinyin(staff_info.get('name')))
            passwd_name = staff_info.get('userid')
            info[pinyin_name] = passwd_name
            name_list.append(pinyin_name)
            passwd_list.append(passwd_name)
        for k, v in info.items():  #将用户名和密码写入文本
            with open('/etc/opt/ss5/ss5.passwd', 'a', encoding='utf-8') as f:
                f.write(k + '\t' + v + '\n')
        '''以下是先判断有没有旧的人员名单文件,有的话转换成列表和新生成的人员列表进行对比,如有增加,发送邮件'''
        newname = []   #生成新入职人员名单
        list_files = os.listdir()
        if "name_old.txt" in list_files:
            with open('name_old.txt','r' ,encoding='utf-8') as old_info:
                all_info = old_info.read()
                list_info = all_info.split(',')
                for add_staff in name_list:
                    if add_staff in list_info:
                        pass
                    else:
                        newname.append(add_staff)
            
        else:
            with open('name_old.txt','w',encoding='utf-8') as name_sync:
                for xingming in name_list:
                    name_sync.write(str(xingming))
                    name_sync.write(',')
        #更新old人员信息
        with open('name_old.txt','w' ,encoding='utf-8') as renew_info:
                for re_name in name_list:
                    renew_info.write(str(re_name))
                    renew_info.write(',')

        return newname,passwd_list
    except Exception as err:
        print('请求失败!','error: {}'.format(err))

def _email(name,password):

    '''发送邮件'''
    for name1 in name:
        import smtplib
        from email.mime.text import MIMEText
        from email.utils import formataddr
        import time
        date = time.strftime('%Y-%m-%d', time.localtime())
        body = """
               欢迎使用代理,
               登录代理的用户名是%s,Password为:%s.
               日期:%s
               """%(name1,password[name.index(name1)],date)
        my_sender = '598941324@qq.com'
        my_pass = 'mypwrqbdccwert'
        my_user = "{}@limikeji.com".format(name1)
        msg = MIMEText(body, 'plain', 'utf-8')
        msg['From'] = formataddr(["北京狸米科技有限公司", my_sender])
        msg['To'] = formataddr(["北京狸米科技有限公司",my_user])
        msg['Subject'] = '信息同步'
        server = smtplib.SMTP_SSL("smtp.qq.com", 465)
        server.login(my_sender, my_pass)
        server.sendmail(my_sender, [my_user], msg.as_string())
        server.quit()

def service_reboot():
    CMD1 = "systemctl restart ss5" 
    subprocess.getoutput(CMD1)


if __name__ == "__main__":
    del_conf()
    key = get_token()
    username,userpasswd = get_bumenId(key)
    _email(username,userpasswd)
    service_reboot()

标题:搭建使用Socks Server 5 服务器
作者:cuijianzhe
地址:https://cuijianzhe.github.io/articles/2020/01/02/1577948274548.html