admin 发布的文章

使用golang开发联通流量机器人

背景

联通某次活动。

代码


package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "net/url"
    "os"
    "strconv"
    "strings"

    "github.com/jasonlvhit/gocron"
    flag "github.com/spf13/pflag"
)

var (
    users  = make(map[string]Login)
    c      = &http.Client{}
    logger *log.Logger

    serialNumber    string
    serialNumberKey string
)

const (
    BOSS = iota
    FRIEND
    STRANGER
    ENEMY

    //serialNumberKey    = "xxxx"
    //serialNumber       = "1860000000"
    indexUrl           = "http://worose.com:11003/GrabFlows/index.html?chl=5&serialNumber=xxxx"
    loginStepOneUrl    = "http://worose.com:11003/GrabFlows/grabflows/login!dologinpre.action"
    loginStepTwoUrl    = "http://worose.com:11003/GrabFlows/grabflows/login!getAccessKey.action"
    loginUrl           = "http://worose.com:11003/GrabFlows/grabflows/login!accessByEncodePwd.action"
    getLastRobTimeUrl  = "http://worose.com:11003/GrabFlows/grabflows/rob!getLastRobTime.action"
    getFriendsListUrl  = "http://worose.com:11003/GrabFlows/grabflows/user!getFriendList.action"
    getStrangerListUrl = "http://worose.com:11003/GrabFlows/grabflows/rob!getStrangerList.action"
    getEnemyListUrl    = "http://worose.com:11003/GrabFlows/grabflows/rob!getEnemyList.action"
    doRobUrl           = "http://worose.com:11003/GrabFlows/grabflows/rob!doRob.action"
    cookieStr          = "serialNumber=%s; currentZl=%d; currentPieceNum=%d; robPieceNum=%d; isFirstLogin=0; JSESSIONIDGrabFlows=%s"
)

type APIResponse struct {
    RetCode string `json:"retCode"`
    RetMsg  string `json:"retMsg"`
}

type RobTime struct {
    APIResponse
    RobStrangerTime      string `json:"rob_stranger_time"`
    OvRobBossCooling     string `json:"ov_rob_boss_cooling"`
    OvRobStrangerCooling string `json:"ov_rob_stranger_cooling"`
    OvRobFriendsCooling  string `json:"ov_rob_friends_cooling"`
    OvRobEnemyCooling    string `json:"ov_rob_enemy_cooling"`
    RobBossTime          string `json:"rob_boss_time"`
    RobFriendsTime       string `json:"rob_friends_time"`
    RobEnemyTime         string `json:"rob_enemy_time"`
    OvSysTime            string `json:"ov_sys_time"`
}

type Stranger struct {
    LastLandTime    string `json:"lastLandTime"`
    RobbedPieceNum  string `json:"robbedPieceNum"`
    Diff            int    `json:"diff,string"`
    SerialNumber    string `json:"serialNumber"`
    HappenTime      string `json:"happenTime"`
    CurrentZl       int    `json:"currentZl,string"`
    CurrentPieceNum string `json:"currentPieceNum"`
    FirstLandTime   string `json:"firstLandTime"`
    Att1            int    `json:"att1,string"`
}

type StrangerList struct {
    APIResponse
    RetData   string `json:"retData"`
    Strangers []Stranger
}

type Enemy struct {
    CurrentPieceNum int    `json:"CURRENT_PIECE_NUM"`
    UserId          string `json:"USER_ID"`
    SerialNumber    string `json:"SERIAL_NUMBER"`
    FirstLandTime   int    `json:"FIRST_LAND_TIME"`
    LastRobbedTime  int    `json:"LAST_ROBBED_TIME"`
    Rn              int    `json:"RN"`
    Diff            int    `json:"DIFF"`
    LastLandTime    int    `json:"LAST_LAND_TIME"`
    CurrentZl       int    `json:"CURRENT_ZL"`
    NetTypeCode     string `json:"NET_TYPE_CODE"`
    HappenTime      string `json:"HAPPENTIME"`
    RobbedPieceNum  int    `json:"ROBBED_PIECE_NUM"`
    RobbedSendSms   int    `json:"ROBBED_SEND_SMS"`
    Att1            int    `json:"ATT1,string"`
}

type EnemyList struct {
    APIResponse
    RetData   string `json:"retData"`
    TotalPage int    `json:"totalPage,string"`
    Enemys    []Enemy
}

type Friend struct {
    SerialNumber       string `json:"SERIAL_NUMBER"`
    MMdiff             int    `json:"MMDIFF"`
    FirstShipTime      int    `json:"FIRST_FRIENDSHIP_TIME"`
    FriendSerialNumber string `json:"FRIEND_SERIAL_NUMBER"`
    LastLandTime       int    `json:"LAST_LAND_TIME"`
    CurrentZl          int    `json:"CURRENT_ZL"`
    Diff               int    `json:"DIFF"`
    Rn                 int    `json:"RN"`
    HappenTime         int    `json:"HAPPENTIME"`
    UserId             string `json:"USERID"`
    Att1               int    `json:"ATT1"`
}

type FriendList struct {
    APIResponse
    TotalCount int    `json:"totalCount,string"`
    TotalPage  int    `json:"tatalPage,string"`
    RetData    string `json:"retData"`
    Friends    []Friend
}

type AccessKey struct {
    APIResponse
    RetSeq string `json:"retSeq"`
    RetDwp string `json:"retdwp"`
}

type Login struct {
    APIResponse
    IsFirstLogin    int `json:"isFirstLogin,string"`
    RobPieceNum     int `json:"robPieceNum,string"`
    CurrentPieceNum int `json:"currentPieceNum,string"`
    CurrentZl       int `json:"currentZl,string"`
    SessionId       string
}

func task() {
    logger.Println("task runing.............")
    rb, err := getLastRobTime()
    if err != nil {
        logger.Println(err)
        return
    }
    if rb.OvRobBossCooling == "0" {
        go doBoss()
    }
    if rb.OvRobFriendsCooling == "0" {
        go doFriend()
    }
    if rb.OvRobStrangerCooling == "0" {
        go doStranger()
    }
    if rb.OvRobEnemyCooling == "0" {
        go doEnemy()
    }
}

func request(serialNumber, url string, values url.Values) ([]byte, error) {
    login := users[serialNumber]
    cookie := fmt.Sprintf(cookieStr, serialNumber, login.CurrentZl, login.CurrentPieceNum, login.RobPieceNum, login.SessionId)
    logger.Println(values.Encode())
    req, _ := http.NewRequest("POST", url, strings.NewReader(values.Encode()))
    req.Header.Add("Accept", "application/json;charset=utf-8, text/javascript, */*; q=0.01")
    req.Header.Add("Accept-Encoding", "gzip, deflate")
    req.Header.Add("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.6")
    req.Header.Add("Connection", "keep-alive")
    req.Header.Add("Host", "worose.com:11003")
    req.Header.Add("Origin", "http://worose.com:11003")
    req.Header.Add("Referer", "http://worose.com:11003/GrabFlows/game.html")
    req.Header.Add("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
    req.Header.Add("User-Agent", "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36")
    req.Header.Add("X-Requested-With", "XMLHttpRequest")
    req.Header.Add("Cookie", cookie)
    resp, err := c.Do(req)
    if err != nil {
        logger.Println(err)
        return nil, err
    }
    defer resp.Body.Close()
    b, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        logger.Println(err)
        return nil, err
    }
    return b, err
}

func login() error {
    resp, err := http.Get(loginStepOneUrl)
    if err != nil {
        logger.Println(err)
        return err
    }
    b, _ := ioutil.ReadAll(resp.Body)
    logger.Println(string(b))
    logger.Println(resp.Cookies())
    defer resp.Body.Close()

    values := url.Values{}
    values.Add("primryKey", serialNumberKey)
    resp1, err := http.PostForm(loginStepTwoUrl, values)
    defer resp1.Body.Close()
    var ak AccessKey
    b, _ = ioutil.ReadAll(resp1.Body)
    json.Unmarshal(b, &ak)
    logger.Println(string(b))
    logger.Println(ak)
    logger.Println(resp1.Cookies())

    values = url.Values{}
    values.Add("seqid", ak.RetSeq)
    values.Add("serialNumber", serialNumber)
    values.Add("encodePwd", ak.RetDwp)
    values.Add("channelId", "5")
    res, err := http.PostForm(loginUrl, values)
    defer res.Body.Close()
    b, _ = ioutil.ReadAll(res.Body)
    logger.Println(string(b))
    logger.Println(res.Cookies())
    var login Login
    json.Unmarshal(b, &login)
    for _, v := range res.Cookies() {
        if v.Name == "JSESSIONIDGrabFlows" {
            login.SessionId = v.Value
            break
        }
    }
    users[serialNumber] = login
    return nil
}

func getLastRobTime() (rt RobTime, err error) {
    values := url.Values{}
    values.Add("serialNumber", serialNumber)
    b, err := request(serialNumber, getLastRobTimeUrl, values)
    if err != nil {
        return RobTime{}, err
    }
    var robTime RobTime
    json.Unmarshal(b, &robTime)
    return robTime, nil
}

func getStrangerList() (s StrangerList, err error) {
    values := url.Values{}
    values.Add("serialNumber", serialNumber)
    resp, err := http.PostForm(getStrangerListUrl, values)
    if err != nil {
        logger.Println(err)
        return StrangerList{}, err
    }
    defer resp.Body.Close()
    b, err := ioutil.ReadAll(resp.Body)
    var sl StrangerList
    err = json.Unmarshal(b, &sl)
    if err != nil {
        logger.Println(err)
        return StrangerList{}, err
    }
    json.Unmarshal([]byte(sl.RetData), &sl.Strangers)
    return sl, nil
}

func getEnemyList() (e EnemyList, err error) {
    values := url.Values{}
    values.Add("serialNumber", serialNumber)
    values.Add("currentPage", "1")
    values.Add("pageSize", "5")
    resp, err := http.PostForm(getEnemyListUrl, values)
    if err != nil {
        return EnemyList{}, err
    }
    defer resp.Body.Close()
    b, err := ioutil.ReadAll(resp.Body)
    var el EnemyList
    err = json.Unmarshal(b, &el)
    if err != nil {
        logger.Println(err)
        return EnemyList{}, err
    }
    json.Unmarshal([]byte(el.RetData), &el.Enemys)
    return el, nil
}

func getFriendsList() (f FriendList, err error) {
    values := url.Values{}
    values.Add("serialNumber", serialNumber)
    values.Add("currentPage", "1")
    values.Add("pageSize", "5")
    resp, err := http.PostForm(getFriendsListUrl, values)
    if err != nil {
        logger.Println(err)
        return FriendList{}, err
    }
    defer resp.Body.Close()
    b, err := ioutil.ReadAll(resp.Body)
    var fl FriendList
    err = json.Unmarshal(b, &fl)
    if err != nil {
        logger.Println(err)
        return FriendList{}, err
    }
    json.Unmarshal([]byte(fl.RetData), &fl.Friends)
    return fl, nil
}

func doRob(serialNumber string, robType int, robSerialNumber string, currentZl, robZl int) error {
    values := url.Values{}
    values.Add("serialNumber", serialNumber)
    values.Add("robType", strconv.Itoa(robType))
    values.Add("robSerialNumber", robSerialNumber)
    if currentZl > 0 {
        values.Add("currentZl", strconv.Itoa(currentZl))
        values.Add("robZl", strconv.Itoa(robZl))
    }
    b, err := request(serialNumber, doRobUrl, values)
    if err != nil {
        logger.Println(err)
        return err
    }
    logger.Println(string(b))
    return err
}

func doStranger() error {
    logger.Println("开始处理陌生人........")
    user := users[serialNumber]
    //获取陌生人列表
    sl, err := getStrangerList()
    if err != nil {
        logger.Println(err)
        return err
    }
    logger.Println(sl)
    var strangerList []Stranger
    for i := 0; i < len(sl.Strangers); i++ {
        if len(strangerList) == 2 {
            break
        }
        robZl := sl.Strangers[i].CurrentZl + sl.Strangers[i].Att1*100
        if sl.Strangers[i].Diff < 0 && robZl < user.CurrentZl {
            strangerList = append(strangerList, sl.Strangers[i])
        }
    }
    logger.Println(strangerList)
    for i := 0; i < len(strangerList); i++ {
        doRob(serialNumber, STRANGER, strangerList[i].SerialNumber, user.CurrentZl, strangerList[i].CurrentZl+strangerList[i].Att1*100)
    }
    return nil
}

func doEnemy() error {
    logger.Println("开始处理敌人........")
    user := users[serialNumber]
    //获取敌人列表
    el, err := getEnemyList()
    if err != nil {
        logger.Println(err)
        return err
    }
    logger.Println(el)
    var enemyList []Enemy
    for i := 0; i < len(el.Enemys); i++ {
        if len(enemyList) == 2 {
            break
        }
        robZl := el.Enemys[i].CurrentZl + el.Enemys[i].Att1*100
        if el.Enemys[i].Diff < 0 && robZl < user.CurrentZl {
            enemyList = append(enemyList, el.Enemys[i])
        }
    }
    logger.Println(enemyList)
    for i := 0; i < len(enemyList); i++ {
        doRob(serialNumber, ENEMY, enemyList[i].SerialNumber, user.CurrentZl, enemyList[i].CurrentZl+enemyList[i].Att1*100)
    }
    return nil
}

func doBoss() {
    logger.Println("处理BOSS...........")
    doRob(serialNumber, BOSS, "BOSS", 0, 0)
}

func doFriend() error {
    logger.Println("开始处理朋友........")
    user := users[serialNumber]
    //获取敌人列表
    el, err := getFriendsList()
    if err != nil {
        logger.Println(err)
        return err
    }
    logger.Println(el)
    var friendsList []Friend
    for i := 0; i < len(el.Friends); i++ {
        if len(friendsList) == 2 {
            break
        }
        robZl := el.Friends[i].CurrentZl + el.Friends[i].Att1*100
        if el.Friends[i].Diff < 0 && robZl < user.CurrentZl {
            friendsList = append(friendsList, el.Friends[i])
        }
    }
    logger.Println(friendsList)
    for i := 0; i < len(friendsList); i++ {
        doRob(serialNumber, FRIEND, friendsList[i].FriendSerialNumber, user.CurrentZl, friendsList[i].CurrentZl+friendsList[i].Att1*100)
    }
    return nil
}

func main() {
    flag.StringVarP(&serialNumber, "serialNumber", "s", "00000000000", "-s serialNumber")
    flag.StringVarP(&serialNumberKey, "serialNumberKey", "k", "0000000000", "-k serialNumberKey")
    flag.Parse()

    if serialNumber == "00000000000" || serialNumberKey == "00000000000" {
        fmt.Println("Usage:worose -s serialNumber -k serialNumberKey")
        os.Exit(1)
    }

    logger = log.New(os.Stderr, "worose: ", log.LstdFlags|log.Lmicroseconds|log.Lshortfile)

    logger.Println("worose running.......")
    logger.Println(serialNumber, serialNumberKey)

    login()

    task()

    gocron.Every(5).Minutes().Do(task)
    <-gocron.Start()
}


系统部署之mongodb安装

系统部署之mongodb安装

安装文件

  • mongodb-linux-x86_64-rhel70-3.4.5.tgz

解压安装

  1. tar -zxf mongodb-linux-x86_64-rhel70-3.4.5.tgz
  2. mv mongodb-linux-x86_64-rhel70-3.4.5 /usr/local/mongodb

创建用户

  1. mkdir /data/mongodb/{log,conf,data}
  2. groupadd mongodb
  3. useradd -g mongodb -s /sbin/nologin mongodb
  4. chown -R mongodb:mongodb /data/mongodb

修改配置

master

#master.conf
dbpath=/data/mongodb/data
logpath=/data/mongodb/log/master.log
pidfilepath=/data/mongodb/log/master.pid
directoryperdb=true
logappend=true
replSet=rs
bind_ip=本机IP
port=27017
oplogSize=10000
fork=true
noprealloc=true
#auth=true
#keyFile=/data/mongodb/mongodb-cluster-key

slave

#slaver.conf
dbpath=/data/mongodb/data
logpath=/data/mongodb/log/slaver.log
pidfilepath=/data/mongodb/log/slaver.pid
directoryperdb=true
logappend=true
replSet=rs
bind_ip=本机IP
port=27017
oplogSize=10000
fork=true
noprealloc=true
#auth=true
#keyFile=/data/mongodb/mongodb-cluster-key

arbiter

#arbiter.conf
dbpath=/data/mongodb/data
logpath=/data/mongodb/log/arbiter.log
pidfilepath=/data/mongodb/log/arbiter.pid
directoryperdb=true
logappend=true
replSet=rs
bind_ip=本机IP
port=27017
oplogSize=10000
fork=true
noprealloc=true
#auth=true
#keyFile=/data/mongodb/mongodb-cluster-key

系统服务

master-service

/lib/systemd/system/mongodb.service 

[Unit]
Description=mongodb
After=network.target

[Service]
Type=forking
User=mongodb
ExecStart=/usr/local/mongodb/bin/mongod --config /data/mongodb/conf/master.conf
Restart=on-failure

[Install]
WantedBy=multi-user.target

其他类似,修改配置文件地址即可

启动3台服务

集群配置

mongo 主IP:27017
use admin
cfg={ _id:"rs", members:[ {_id:0,host:'masterIP:27017',priority:2}, {_id:1,host:'slave ip:27017',priority:1},
{_id:2,host:'arbiter ip:27017',arbiterOnly:true}] };
rs.initiate(cfg) 

认证配置

mongo 主IP:27017
use admin
db.system.users.remove({})
db.system.version.remove({})
db.system.version.insert({ "_id" : "authSchema", "currentVersion" : 3 })
db.createUser({user:"admin",pwd:"admin",roles:[{role:"userAdminAnyDatabase",db:"admin"},{role:"dbAdminAnyDatabase",db:"admin"},{role:"readWriteAnyDatabase",db:"admin"}]})
db.grantRolesToUser('admin',["clusterManager",{role:"clusterManager",db:"admin"}])
use rfid
db.createUser({user:"rfid",pwd:"rfid",roles:[{role:"dbOwner",db:"rfid"},{role:"readWrite",db:"rfid"},{role:"dbAdmin",db:"rfid"}]})

生成集群认证KEY

  1. openssl rand -base64 741 > /data/mongodb/mongodb-cluster-key
  2. chmod 600 /data/mongodb/mongodb-cluster-key
  3. chown mongodb:mongodb /data/mongodb/mongodb-cluster-key

关闭服务,取消配置文件最后2行注释

系统部署之redis集群安装(sentinel)

系统部署之redis集群安装(sentinel)

安装文件

  • redis-3.2.9.tar.gz

编译安装

  1. yum install gcc
  2. make CFLAGS="-march=x86-64"
  3. make install PREFIX=/usr/local/redis
  4. mkdir /usr/local/redis/etc

创建用户

  1. groupadd redis
  2. useradd -g redis -d /var/lib/redis -s /sbin/nologin redis
  3. mkdir -p /var/lib/redis/{logs,data,sentinel_26379}
  4. chown -R redis:redis /var/lib/redis
  5. chown -R redis:redis /usr/local/redis/etc/

创建配置

master配置

/usr/local/redis/etc/redis.conf

daemonize yes
pidfile /var/lib/redis/logs/redis.pid
port 6379
timeout 0
loglevel notice
logfile /var/lib/redis/logs/redis.log
databases 16
save 60 100000
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
dbfilename dump.rdb
dir /var/log/redis/data
slave-serve-stale-data yes
slave-read-only yes
slave-priority 100
appendonly no
appendfsync no
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
lua-time-limit 5000
slowlog-log-slower-than 10000
slowlog-max-len 128
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
list-max-ziplist-entries 512
list-max-ziplist-value 64
set-max-intset-entries 512
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
activerehashing yes
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit slave 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
min-slaves-to-write 1
min-slaves-max-lag 10
masterauth 123456
requirepass 123456
/usr/local/redis/etc/sentinel_26379.conf

port 26379
dir "/var/lib/redis/sentinel_26379"
logfile "/var/log/redis/logs/sentinel_26379.log"
daemonize yes
protected-mode no
sentinel monitor 51master 主IP 主端口 2
sentinel down-after-milliseconds 51master 5000
sentinel failover-timeout 51master 120000
sentinel auth-pass 51master 123456

slave配置

/usr/local/redis/etc/redis.conf

daemonize yes
pidfile /var/lib/redis/logs/redis.pid
port 6379
timeout 0
loglevel notice
logfile /var/lib/redis/logs/redis.log
databases 16
save 60 100000
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
dbfilename dump.rdb
dir /var/lib/redis/data
slave-serve-stale-data yes
slave-read-only yes
slave-priority 100
appendonly no
appendfsync no
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
lua-time-limit 5000
slowlog-log-slower-than 10000
slowlog-max-len 128
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
list-max-ziplist-entries 512
list-max-ziplist-value 64
set-max-intset-entries 512
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
activerehashing yes
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit slave 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
min-slaves-to-write 1
min-slaves-max-lag 10
masterauth 123456
requirepass 123456
slaveof 主IP 端口
/usr/local/redis/etc/sentinel_26379.conf

port 26379
dir "/var/lib/redis/sentinel_26379"
logfile "/var/log/redis/logs/sentinel_26379.log"
daemonize yes
protected-mode no
sentinel monitor 51master 主IP 主端口 2
sentinel down-after-milliseconds 51master 5000
sentinel failover-timeout 51master 120000
sentinel auth-pass 51master 123456

slave2配置

同slave1配置

系统服务(3台相同)

sentinel

/lib/systemd/system/redis_26379.service
 
[Unit]
Description=redis-sentinel
After=network.target,redis.target

[Service]
Type=forking
User=redis
ExecStart=/usr/local/redis/bin/redis-sentinel /usr/local/redis/etc/sentinel_26379.conf
Restart=on-failure

[Install]
WantedBy=multi-user.target

redis

/lib/systemd/system/redis.service

[Unit]
Description=redis
After=network.target

[Service]
Type=forking
User=redis
ExecStart=/usr/local/redis/bin/redis-server /usr/local/redis/etc/redis.conf
Restart=on-failure

[Install]
WantedBy=multi-user.target

系统部署之keepalived安装

系统部署之keepalived安装

安装文件

  • keepalived-1.3.5.tar.gz

编译安装

./configure
make && make install

修改配置

机器1

/etc/keepalived/keepalived.conf 

! Configuration File for keepalived
global_defs {
    notification_email {
        root@localhost
    }
    notification_email_from www@example.com
    smtp_server mail.example.com
    smtp_connect_timeout 30
    router_id LVS_DEVEL
}
vrrp_script chk_nginx {
    script "/etc/keepalived/check_nginx.sh" 
    interval 2 
    weight -5 
    fall 3  
    rise 2 
}
vrrp_instance VI_1 {
    state MASTER
    interface 网卡接口名
    virtual_router_id 51
    priority 101
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        虚拟地址1
    }
    track_script {
       chk_nginx 
    }
}
vrrp_instance VI_2 {
    state BACKUP
    interface 网卡接口名
    virtual_router_id 52
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        虚拟地址2
    }
    track_script {
       chk_nginx
    }
}

机器2

! Configuration File for keepalived
global_defs {
    notification_email {
        root@localhost
    }
    notification_email_from www@example.com
    smtp_server mail.example.com
    smtp_connect_timeout 30
    router_id LVS_DEVEL
}
vrrp_script chk_nginx {
    script "/etc/keepalived/check_nginx.sh" 
    interval 2 
    weight -5 
    fall 3  
    rise 2 
}
vrrp_instance VI_1 {
    state BACKUP
    interface 网卡接口名
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        虚拟地址1
    }
    track_script {
       chk_nginx 
    }
}
vrrp_instance VI_2 {
    state MASTER
    interface 网卡接口名
    virtual_router_id 52
    priority 101
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        虚拟地址2
    }
    track_script {
       chk_nginx
    }
}

nginx检查脚本

check_nginx.sh 

#!/bin/bash
counter=$(ps -C nginx --no-heading|wc -l)
if [ "${counter}" = "0" ]; then
    /usr/local/nginx/sbin/nginx
    sleep 2
    counter=$(ps -C nginx --no-heading|wc -l)
    if [ "${counter}" = "0" ]; then
        service keepalived stop
    fi
fi

系统服务

/lib/systemd/system/keepalived.service

[Unit]
Description=LVS and VRRP High Availability Monitor
After=syslog.target network.target

[Service]
Type=simple
PIDFile=/usr/local/var/run/keepalived.pid
KillMode=process
EnvironmentFile=-/usr/local/etc/sysconfig/keepalived
ExecStart=/usr/local/sbin/keepalived --dont-fork -D
ExecReload=/bin/kill -HUP $MAINPID

[Install]
WantedBy=multi-user.target

测试

尝试关闭一台keepalived服务,查看另一台网络端口情况

注意事项

  • 防火墙启用状态下执行
firewall-cmd --direct --permanent --add-rule ipv4 filter INPUT 0 \
  --in-interface enp0s8 --destination 224.0.0.18 --protocol vrrp -j ACCEPT

firewall-cmd --direct --permanent --add-rule ipv4 filter OUTPUT 0 \
  --out-interface enp0s8 --destination 224.0.0.18 --protocol vrrp -j ACCEPT

firewall-cmd --reload

系统部署之nginx安装

系统部署之nginx安装

安装文件

  • nginx-1.12.0.tar.gz
  • gd-devel-2.0.35-26.el7.x86_64.rpm

安装依赖

yum install gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel libxml2 libxml2-devel libxslt libxslt-devel gd-devel geoip geoip-devel -y

yum install gd fontconfig-devel freetype-devel libX11-devel libXpm-devel libjpeg-devel libpng-devel -y

创建用户

useradd -M -s /sbin/nologin nginx

编译安装

./configure \
 --prefix=/usr/local/nginx \
 --user=nginx \
 --group=nginx \
 --with-pcre \
 --with-http_ssl_module \
 --with-http_v2_module \
 --with-http_realip_module \
 --with-http_addition_module \
 --with-http_sub_module \
 --with-http_dav_module \
 --with-http_flv_module \
 --with-http_mp4_module \
 --with-http_gunzip_module \
 --with-http_gzip_static_module \
 --with-http_random_index_module \
 --with-http_secure_link_module \
 --with-http_stub_status_module \
 --with-http_auth_request_module \
 --with-http_image_filter_module \
 --with-mail \
 --with-mail_ssl_module \
 --with-stream_ssl_module

 make && make install

系统服务

vi /usr/lib/systemd/system/nginx.service

[Unit]
 Description=The nginx HTTP and reverse proxy server
 After=syslog.target network.target remote-fs.target nss-lookup.target

[Service]
 Type=forking
 PIDFile=/usr/local/nginx/logs/nginx.pid
 ExecStartPre=/usr/local/nginx/sbin/nginx -t
 ExecStart=/usr/local/nginx/sbin/nginx
 ExecReload=/bin/kill -s HUP /usr/local/nginx/logs/nginx.pid
 ExecStop=/bin/kill -s QUIT /usr/local/nginx/logs/nginx.pid
 PrivateTmp=true

[Install]
 WantedBy=multi-user.target

配置自启动

配置开机自动启动
systemctl enable nginx

启动服务
systemctl start nginx

停止服务
systemctl stop nginx