Linux使用netstat命令查看并发连接数

netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'

解释:

返回结果示例:

LAST_ACK 5 (正在等待处理的请求数)
SYN_RECV 30

ESTABLISHED 1597 (正常数据传输状态)
FIN_WAIT1 51
FIN_WAIT2 504
TIME_WAIT 1057 (处理完毕,等待超时结束的请求数)

状态:描述

CLOSED:无连接是活动的或正在进行

LISTEN:服务器在等待进入呼叫
SYN_RECV:一个连接请求已经到达,等待确认
SYN_SENT:应用已经开始,打开一个连接
ESTABLISHED:正常数据传输状态
FIN_WAIT1:应用说它已经完成
FIN_WAIT2:另一边已同意释放
ITMED_WAIT:等待所有分组死掉
CLOSING:两边同时尝试关闭
TIME_WAIT:另一边已初始化一个释放
LAST_ACK:等待所有分组死掉

如果只是想查看当前并发的连接数,可以使用以下命令:

netstat -nat|grep ESTABLISHED|wc -l

bash递归检查文件中是否包含IP地址

检查项目组提交的代码以及配置文件中,是否包含写死IP地址的情况

#!/bin/bash

regex_ip="(2[0-4][0-9]|25[0-5]|1[0-9][0-9]|[1-9]?[0-9])(\.(2[0-4][0-9]|25[0-5]|1[0-9][0-9]|[1-9]?[0-9])){3}"
if [ ! -n "$1" ] ;then  
    echo "Usage:check_ip.sh [CHECK_PATH]"  
else  
    grep -rE "$regex_ip" $1
fi  

golang实现tcp反代/转发

package main

import (
    "bytes"
    "flag"
    "io"
    "log"
    "net"
    "os"
    "strings"
    "time"
)

type formatter struct {
    w      io.Writer
    offset uint
    prefix string
    tstamp bool
}

func min(a, b int) int {
    if a < b {
        return a
    }

    return b
}

func (f *formatter) Write(p []byte) (int, error) {
    var completedBytes int
    for i := 0; i < len(p); i += 16 {
        m := min(len(p), i+16)
        err := f.format(p[i:m])
        if err != nil {
            return completedBytes, err
        }
        completedBytes += m - i
        f.offset += uint(m - i)
    }
    return len(p), nil
}

var hex = []byte("0123456789abcdef")

func (f *formatter) format(buf []byte) error {

    // prefix addr:_(hex dump)+spaces+space+bar+chars+bar+newline

    // our line is 83 characters of formatting

    plen := len(f.prefix)

    if f.tstamp {
        plen += len(time.Stamp)
    }

    llen := 83 + plen

    ptr := 0

    line := make([]byte, llen)
    if f.tstamp {
        s := time.Now().Format(time.Stamp)
        copy(line, []byte(s))
        ptr += len(time.Stamp)
    }

    copy(line[ptr:], []byte(f.prefix))
    ptr += len(f.prefix)

    offs := f.offset

    ptr += 8

    line[ptr] = ':'
    ptr--

    for offs > 0 {
        line[ptr] = hex[offs&0x0f]
        ptr--
        offs >>= 4
    }

    for ptr >= plen {
        line[ptr] = '0'
        ptr--
    }

    ptr = plen + 9
    line[ptr] = ' '
    ptr++

    for i, b := range buf {
        if i%4 == 0 {
            line[ptr] = ' '
            ptr++
        }

        line[ptr] = hex[b>>4]
        ptr++
        line[ptr] = hex[b&0x0f]
        ptr++
        line[ptr] = ' '
        ptr++

    }

    // fill in rest of line
    for i := len(buf); i < 16; i++ {
        if i%4 == 0 {
            line[ptr] = ' '
            ptr++
        }

        line[ptr] = ' '
        ptr++
        line[ptr] = ' '
        ptr++
        line[ptr] = ' '
        ptr++
    }

    line[ptr] = ' '
    ptr++
    line[ptr] = ' '
    ptr++
    line[ptr] = '|'
    ptr++

    for _, v := range buf {
        if v > 32 && v < 127 {
            line[ptr] = v
        } else {
            line[ptr] = '.'
        }
        ptr++
    }

    line[ptr] = '|'
    ptr++

    line[ptr] = '\n'
    ptr++

    _, err := f.w.Write(line[:ptr])
    return err
}

func copyStream(conn io.WriteCloser, r io.Reader) {
    _, err := io.Copy(conn, r)
    if err != nil {
        log.Printf("error during copy: %v\n", err)
    }
    err = conn.Close()
    if err != nil {
        log.Printf("error during close: %v\n", err)
    }
}

func main() {

    proxy := flag.String("p", "9999:blog.bbzhh.com:80", "proxy line -- <lport>:<rhost>:<rport>")
    tstamps := flag.Bool("t", false, "add time-stamps when proxying")
    debug := flag.Bool("d", false, "print debug information when proxying")

    flag.Parse()

    // provided a proxy line
    if *proxy != "" {
        pieces := strings.Split(*proxy, ":")
        dst := pieces[1] + ":" + pieces[2]

        fprefix := "<= "
        tprefix := "=> "

        if *tstamps {
            fprefix = " <= "
            tprefix = " => "
        }
        var (
            fin  io.Writer
            fout io.Writer
        )
        if *debug {
            fin = &formatter{os.Stdout, 0, fprefix, *tstamps}
            fout = &formatter{os.Stdout, 0, tprefix, *tstamps}
        } else {
            buf := bytes.NewBuffer(make([]byte, 0))
            fin = &formatter{buf, 0, fprefix, *tstamps}
            fout = &formatter{buf, 0, tprefix, *tstamps}
        }

        ln, e := net.Listen("tcp", ":"+pieces[0])
        if e != nil {
            log.Fatal("listen error:", e)
        }

        log.Println("tcp server starting")

        for {
            lconn, err := ln.Accept()
            if err != nil {
                log.Println(err)
                continue
            }

            go func(lconn net.Conn) {
                tl := io.TeeReader(lconn, fout)
                rconn, err := net.Dial("tcp", dst)
                if err != nil {
                    log.Println("error connectiong to", dst, ":", err)
                    err := lconn.Close()
                    if err != nil {
                        log.Printf("error closing connection: %v\n", err)
                    }
                    return
                }
                tr := io.TeeReader(rconn, fin)
                go copyStream(rconn, tl)
                go copyStream(lconn, tr)
            }(lconn)
        }
    }

    if *tstamps {
        log.Println("-t only applies when proxying, ignoring")
    }

    fout := &formatter{os.Stdout, 0, "", false}

    var fin io.Reader

    // process stdin
    if flag.NArg() == 0 {
        fin = os.Stdin
    } else {
        fname := flag.Arg(0)
        var err error
        fin, err = os.Open(fname)
        if err != nil {
            log.Fatal(err)
            return
        }
    }

    _, err := io.Copy(fout, fin)
    if err != nil {
        log.Printf("error during copy: %v\n", err)
    }
}

tornado微信公众号

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

__author__ = 'tan9le'

import os
from wechatpy import parse_message, create_reply
from wechatpy.utils import check_signature
from wechatpy.exceptions import (
    InvalidSignatureException,
)
import schedule
from datetime import timedelta
import tornado.wsgi
from tornado.options import define, options

TOKEN = os.getenv('WECHAT_TOKEN', '填写token')
AES_KEY = os.getenv('WECHAT_AES_KEY', '填写EncodingAESKey(消息加解密密钥)')
APPID = os.getenv('WECHAT_APPID', '填写AppID(应用ID)')

define("port", default=8000, help="run on the given port", type=int)
class WeiXinHandler(tornado.web.RequestHandler):
    #用于微信公众号网页修改基本信息时的验证
    def get(self):
        # 获取微信公众平台发送的验证参数
        signature = self.get_argument('signature', '')
        timestamp = self.get_argument('timestamp', '')
        nonce = self.get_argument('nonce', '')
        echostr = self.get_argument('echostr', '')
        try:
            check_signature(TOKEN, signature, timestamp, nonce)
        except InvalidSignatureException:
            self.set_stauts('403')
            self.write('error,code 403')
        #按照约定,如果正常,则原样返回echostr
        self.write(echostr)
    def post(self):
        # 获取微信公众平台发送的验证参数
        signature = self.get_argument('signature', '')
        timestamp = self.get_argument('timestamp', '')
        nonce = self.get_argument('nonce', '')
        echostr = self.get_argument('echostr', '')
        # 获取所有值并解析
        msg = parse_message(self.request.body)
        if msg.type == 'text':
            content = msg.content.strip()
            
            reply = create_reply(content, msg)
            self.write(reply.render())
        else:
            help_str = "目前仅支持文字输入\n"
            reply = create_reply(help_str, msg)
            self.write(reply.render())




app = tornado.wsgi.WSGIApplication([
    # 这里需要根据修改为自己的URL匹配
    (r"/", WeiXinHandler),

])

if __name__=="__main__":
    # 启动tornado实例
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

然后使用

python main.py --port=8000

就可以启动应用啦
依赖:

tornado
wechatpy