python3 一键部署Haproxy(centos|ubuntu)

#!/usr/bin/env python3
#-*- coding = utf-8 -*-

import os
import sys
import subprocess
try:
    import distro
except Exception:
    os.system('/usr/bin/pip3 install distro')
import distro
from time import sleep


#检测当前是什么操作系统
def checksystem():
    if 'Ubuntu' in distro.linux_distribution():
        release = 'ubuntu'
    elif 'CentOS Linux' in distro.linux_distribution():
        release = 'centos'
    return release

#检测wget
def checkWget():
    release=checksystem()
    if os.system('''ls /usr/bin/wget | grep -Eqi wget''') == 0:
        pass
    else:
        print('\33[32;正在安装 Wget\33[0m')
        if release == 'centos':
            os.system('yum update > /dev/null 2>&1')
            os.system('yum -y install wget > /dev/null 2>&1')
        else:
            os.system('apt-get update > /dev/null 2>&1')
            os.system('apt-get -y install wget > /dev/null 2>&1')

#配置下载源
def check_source():
    #检测wget
    checkWget()
    release = checksystem()
    if release == 'centos':
        lsb_release = distro.linux_distribution()
        if lsb_release[1] >= '8':
            subprocess.run('''mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup''',shell=True)
            subprocess.run('''wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-8.repo''',shell=True)
            subprocess.run('''yum clean all && yum makecache''',shell=True)
            subprocess.run('''yum update -y''',shell=True)
    elif release == 'ubuntu':
        lsb_release = distro.linux_distribution()
        if lsb_release[1] >= '18.04':
            subprocess.run('''cp /etc/apt/sources.list /etc/apt/sources.list.old''',shell=True)
            with open('/etc/apt/sources.list','w',encoding='utf-8') as apts:
                apts.write('''deb http://mirrors.aliyun.com/ubuntu/ bionic main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-security main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-proposed main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-backports main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-security main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-updates main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-proposed main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-backports main restricted universe multiverse''')
            subprocess.run('''sudo apt-get update''',shell=True)
            subprocess.run('''sudo apt-get upgrade''',shell=True)


#安装基础环境
def Basic_environment():
    release = checksystem()
    if release == 'centos':
        os.system('''yum -y install curl wget tar rsyslog  make gcc gcc-c++ glibc glibc-devel pcre pcre-devel openssl openssl-devel systemd-devel zlib-devel libevent-devel ncurses-devel readline-devel libtermcap-devel''')
    elif release == 'ubuntu':
        os.system('''sudo apt install -y curl  tar wget make rsyslog gcc build-essential libssl-dev 
        zlib1g-dev libpcre3 libpcre3-dev libsystemd-dev libreadline-dev''')

    os.system('''mkdir -p /home/tools \
    mkdir -p /usr/local/haproxy \
    mkdir -p /var/lib/haproxy \
    mkdir -p /etc/haproxy \
    mkdir -p /var/log/haproxy
    ''')
    creat_lua()
    creat_haproxy()

#安装lua
def creat_lua():
    os.chdir('/home/tools')
    os.system('''wget http://www.lua.org/ftp/lua-5.4.3.tar.gz''')
    os.system('''tar -xvf lua-5.4.3.tar.gz''')
    os.chdir('lua-5.4.3')
    os.system('''make linux test''')
    os.system('''src/lua -v''')

#安装haproxy
def creat_haproxy():
    os.chdir('/home/tools')
    os.system('''wget https://www.haproxy.org/download/2.3/src/haproxy-2.3.9.tar.gz''')
    os.system('''tar -xvf haproxy-2.3.9.tar.gz''')
    os.chdir('''haproxy-2.3.9''')
    os.system('''make ARCH=x86_64 \
    TARGET=linux-glibc  \
    USE_PCRE=1  \
    USE_OPENSSL=1  \
    USE_ZLIB=1  \
    USE_SYSTEMD=1  \
    USE_CPU_AFFINITY=1  \
    USE_LUA=1  \
    LUA_INC=/home/tools/lua-5.4.3/src/  \
    LUA_LIB=/home/tools/lua-5.4.3/src/ \
    PREFIX=/usr/local/haproxy
    ''')

    os.system('''make install PREFIX=/usr/local/haproxy''')
    os.system('''ln -sv /usr/local/haproxy/sbin/haproxy  /usr/sbin/''')

    #创建管理用户
    os.system('''useradd haproxy -r -s /sbin/nologin''') 

#添加配置文件
def creat_cfg():
    with open('/etc/haproxy/haproxy.cfg','w',encoding='utf-8') as cf:
        cf.write('''#---------------------------------------------------------------------
# 全局配置
#---------------------------------------------------------------------
global
    daemon
    nbproc 1                        #设置进程数量,默认1,根据cpu配置
    cpu-map 1 0                     #绑定haproxy进程至指定CPU
    #cpu-map 2 1
    #cpu-map 3 2
    #cpu-map 4 3
    #cpu-map 5 4
    #cpu-map 6 5
    #cpu-map 7 6
    #cpu-map 8 7
    #nbthread 5                      #指定每个haproxy进程开启的线程数,默认为每个进程一个线程
    maxconn 65535                  #最大连接数
    ulimit-n 655350                 #ulimit的数量限制
    user haproxy
    group haproxy
    chroot /usr/local/haproxy
    log 127.0.0.1 local3 info       #日志输出
    pidfile /var/lib/haproxy/haproxy.pid

#---------------------------------------------------------------------
# 默认配置
#---------------------------------------------------------------------
defaults
    mode http
    log global
    retries 3
    option httplog
    maxconn 65535
    option forwardfor
    option http-keep-alive    #开启会话保持
    option abortonclose       #当服务器负载很高的时候,自动结束掉当前队列处理比较久的链接
    timeout connect 30s       #转发客户端请求到后端server的最长连接时间(TCP之前)
    timeout server 1m         #转发客户端请求到后端服务端的超时超时时长(TCP之后)
    timeout client 1m         #与客户端的最长空闲时间
    timeout check 5s          #心跳检测超时
    #timeout http-keep-alive 120s  #session 会话保持超时时间,范围内会转发到相同的后端服务器

#---------------------------------------------------------------------
# 统计页面配置
#---------------------------------------------------------------------
listen stats
    bind *:9999
    mode http
    log global
    stats enable
    stats uri /stats
    stats refresh 30s
    stats auth admin:admin     #账号密码
    stats hide-version         #隐藏统计页面上HAProxy的版本信息
    stats admin if TRUE        #设置手工启动/禁用,后端服务器(haproxy-1.4.9以后版本)
    stats realm Gong Cloud Haproxy #统计页面密码框上提示文本

#配置代理 ws
# frontend ws_in
#         bind *:8095
#         acl hdr_connection_upgrade hdr(Connection)  -i upgrade
#         acl hdr_upgrade_websocket  hdr(Upgrade)     -i websocket
#         use_backend websockets if hdr_connection_upgrade hdr_upgrade_websocket

# backend websockets
# balance roundrobin
# cookie SERVERID
# server web1 192.168.88.155:81 check inter 2000 rise 3 fall 3 weight 1

#配置代理ws (listen的方法)
# listen ws_lobby
#     bind *:8095
#     acl hdr_connection_upgrade hdr(Connection)  -i upgrade
#     acl hdr_upgrade_websocket  hdr(Upgrade)     -i websocket
#     cookie SERVERID
#     server web1 192.168.88.155:81 check inter 2000 rise 3 fall 3 weight 1
''')
    #设置rsyslog
    release = checksystem()
    if release == 'centos':
        with open('/etc/rsyslog.conf','a',encoding='utf-8') as rs:
            rs.write('''$IncludeConfig                           /etc/rsyslog.d/*.conf''')
    
    with open('/etc/rsyslog.d/haproxy.conf','w',encoding='utf-8') as rs:
        rs.write('''$ModLoad imudp
$UDPServerRun 514
local3.*                                                /var/log/haproxy/haproxy.log
''')
    #授权给创建的目录
    os.system('''chown -R syslog:adm /var/log/haproxy/''')

#systemd 启动管理
def systemd_hpy():
    release = checksystem()
    if release == 'centos':
        with open('/usr/lib/systemd/system/haproxy.service','w',encoding='utf-8') as sy:
            sy.write('''[Unit]
Description=HAProxy Load Balancer
After=syslog.target network.target

[Service]
ExecStartPre=/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -c -q
ExecStart=/usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /var/lib/haproxy/haproxy.pid
ExecReload=/bin/kill -USR2 $MAINPID

[Install]
WantedBy=multi-user.target
''')

    elif release == 'ubuntu':
        with open('/lib/systemd/system/haproxy.service','w',encoding='utf-8') as sy:
            sy.write('''[Unit]
Description=HAProxy Load Balancer
After=syslog.target network.target

[Service]
ExecStartPre=/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -c -q
ExecStart=/usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /var/lib/haproxy/haproxy.pid
ExecReload=/bin/kill -USR2 $MAINPID

[Install]
WantedBy=multi-user.target
''')     

    #启动,并开机自启
    os.system('''systemctl daemon-reload''')
    os.system('''systemctl restart rsyslog.service''')
    os.system('''systemctl start haproxy.service''')
    os.system('''systemctl enable haproxy.service''')


if __name__ == '__main__':
    Basic_environment()
    creat_cfg()
    systemd_hpy()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值