Laravel Eloquent 左联时进行筛选

在 laravel Eloquent ORM 中我们经常用到 with 这一方法来关联表。普通的使用场景也很简单,例如

class Talent{
    public function account()
    {
        return $this->belongsTo('App\Models\Account', 'account_uuid');
    }
}

使用 Talent::with(‘account’) 就可以获取到关联数据。如果希望左联查询,可以在行内使用如下语句实现:

$yesterdayCreateTalent = Talent::with(['account' => function ($q) {
  $q->yesterday();
}])->get();

也可以拆分方法进行使用。

// Talent
public function test()
{
   return $this->belongsTo('App\Models\Account', 'account_uuid')->yesterday();
   // or
   // return $this->account()->yesterday();
}

Laravel Eloquent 使用 groupBy 获取每个group的数据和

最近写到相关的代码,直接上代码做个记录。

public function scopeUserSum($query)
{
    return $query->groupBy('username')->selectRaw('sum(data) as sum, username')->orderBy('sum', 'desc');
}

如果只是纯粹求一列的和,在builder上直接用sum即可。

参考资料


Shell 拉起进程后获得 pid,$0,$?,$!等用法

起因是在前一篇《Linux 网络监控与统计实例》(/tech/2017/04/13/linux-network-monitor-and-stats-example.html)中杀死 tcpdump 的代码在流量监控项目中是有bug的,源码如下:

#tcpdump监听网络
tcpdump -v -i $eth -tnn > /tmp/tcpdump_temp 2>&1 &
sleep 10
clear
kill `ps aux | grep tcpdump | grep -v grep | awk '{print $2}'`

这个代码中最后一句 kill 的结果实质上是杀死正在运行中的 tcpdump。然而如果系统中原先已存在tcpdump,就会造成不可预期的结果。

比较适当的做法是记录运行 tcpdump 时的 pid,最后再 kill 掉。相关的代码其实非常简单:

$! # Shell最后运行的后台Process的PID

所以代码调整后的结果就是

# tcpdump监听网络
tcpdump -v -i $eth -tnn > $tmpfile1 2>&1 &
local pid=$!
sleep 60
kill $pid

除了 $!, Shell 还有下面这些特殊的用法:

变量 说明
$$ Shell本身的PID(ProcessID)
$! Shell最后运行的后台Process的PID
$? 最后运行的命令的结束代码(返回值)
$- 使用Set命令设定的Flag一览
$* 所有参数列表。如”$*“用「”」括起来的情况、以”$1 $2 … $n”的形式输出所有参数。
$@ 所有参数列表。如”$@”用「”」括起来的情况、以”$1” “$2” … “$n” 的形式输出所有参数。
$# 添加到Shell的参数个数
$0 Shell本身的文件名
$1~$n 添加到Shell的各参数值。$1是第1参数、$2是第2参数…。
!! 上一个运行的命令
n! history中第n个运行的命令

参考资料


supervisor 安装与配置

Supervisor是一个进程控制系统,由python编写。可以很方便的用来启动、重启、关闭进程(不仅仅是 Python 进程)。 它有以下一些特点

  • 可以配置同时启动的进程数,而不需要一个个启动
  • 可以根据程序的退出码来判断是否需要自动重启
  • 可以配置进程初始化的环境,包括目录,用户,umask,关闭进程所需要的信号等等
  • 有web界面进行管理

下面简单介绍一下 supervisor 的安装使用过程。更复杂的 group 等设置可以参考我文末的参考资料。

安装

使用python包管理工具pip进行安装:

pip install supervisor

配置

安装完 supervisor 之后,运行echo_supervisord_conf 命令输出默认的配置项,重定向到一个配置文件里:

echo_supervisord_conf > /etc/supervisord.conf

下面是我经过简化过的配置:

[unix_http_server]
file=/tmp/supervisor.sock   ; (the path to the socket file)

[supervisord]
logfile=/var/local/log/supervisor/supervisord.log ; (main log file;default $CWD/supervisord.log)
logfile_maxbytes=50MB        ; (max main logfile bytes b4 rotation;default 50MB)
logfile_backups=10           ; (num of main logfile rotation backups;default 10)
loglevel=info                ; (log level;default info; others: debug,warn,trace)
pidfile=/tmp/supervisord.pid ; (supervisord pidfile;default supervisord.pid)
nodaemon=false               ; (start in foreground if true;default false)
minfds=1024                  ; (min. avail startup file descriptors;default 1024)
minprocs=200                 ; (min. avail process descriptors;default 200)

[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl]
serverurl=unix:///tmp/supervisor.sock ; use a unix:// URL  for a unix socket

[include]
files = /etc/supervisor/*.conf

然后新建文件夹来存放各种进程的配置文件:

mkdir /etc/supervisor

目前我是用来管理 laravel 的进程,在 /etc/supervisor/ 里添加文件 laravel-wechat.conf

[program:wechat]
directory = /var/local/fpm-pools/wechat/www ; 程序的启动目录
command = php /var/local/fpm-pools/wechat/www/artisan queue:work --sleep=3 --daemon --tries=3
process_name=%(program_name)s_%(process_num)02d
autostart = true     ; 在 supervisord 启动的时候也自动启动
;startsecs = 5        ; 启动 5 秒后没有异常退出,就当作已经正常启动了
autorestart = true   ; 程序异常退出后自动重启
startretries = 3     ; 启动失败自动重试次数,默认是 3
user = www-data          ; 用哪个用户启动
redirect_stderr = true  ; 把 stderr 重定向到 stdout,默认 false
numprocs = 8
stdout_logfile_maxbytes = 20MB  ; stdout 日志文件大小,默认 50MB
stdout_logfile_backups = 20     ; stdout 日志文件备份数
; stdout 日志文件,需要注意当指定目录不存在时无法正常启动,所以需要手动创建目录(supervisord 会自动创建日志文件)
stdout_logfile = /var/local/log/wechat/wechat.queue.log

; 可以通过 environment 来添加需要的环境变量,一种常见的用法是修改 PYTHONPATH
; environment=PYTHONPATH=$PYTHONPATH:/path/to/somewhere

启动后命令行界面输入 supervisorctl 进入控制界面,如下则说明 supervisor 启动成功、laravel 进程配置成功

启动 supervisord

# 使用默认的配置文件 /etc/supervisord.conf
supervisord
# 明确指定配置文件
supervisord -c /etc/supervisord.conf
# 使用 user 用户启动 supervisord
supervisord -u user

supervisorctl 命令介绍

# 停止某一个进程,program_name 为 [program:x] 里的 x
supervisorctl stop program_name
# 启动某个进程
supervisorctl start program_name
# 重启某个进程
supervisorctl restart program_name
# 结束所有属于名为 groupworker 这个分组的进程 (start,restart 同理)
supervisorctl stop groupworker:
# 结束 groupworker:name1 这个进程 (start,restart 同理)
supervisorctl stop groupworker:name1
# 停止全部进程,注:start、restart、stop 都不会载入最新的配置文件
supervisorctl stop all
# 载入最新的配置文件,停止原有进程并按新的配置启动、管理所有进程
supervisorctl reload
# 根据最新的配置文件,启动新配置或有改动的进程,配置没有改动的进程不会受影响而重启
supervisorctl update

注意:显示用 stop 停止掉的进程,用 reload 或者 update 都不会自动重启。

开机自动启动 Supervisord

Supervisord 默认情况下并没有被安装成服务,它本身也是一个进程。

# 下载脚本
sudo su - root -c "sudo curl https://gist.githubusercontent.com/howthebodyworks/176149/raw/d60b505a585dda836fadecca8f6b03884153196b/supervisord.sh > /etc/init.d/supervisord"
# 设置该脚本为可以执行
sudo chmod +x /etc/init.d/supervisord
# 设置为开机自动运行
sudo update-rc.d supervisord defaults
# 试一下,是否工作正常
service supervisord stop
service supervisord start 

参考资料


Linux 网络监控与统计实例

最近写到相关的代码,做个记录。

知识补充

首先补充本文用到的 Shell/Linux 的一些知识。

  • 数组
  • grep
  • awk
  • sed
  • ss
  • tcpdump

数组

ArrayName=("element 1" "element 2" "element 3") ## 定义数组
${distro[0]}        ## 访问数组
${#distro[@]}       ## 数组长度

grep

实例:

ifconfig | grep -E -o "^[a-z0-9]+" | grep -v "lo"
ifconfig | grep -A 1 eth0

手册:

grep [OPTIONS] PATTERN [FILE...]
grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]

Matcher Selection
   -E, --extended-regexp 正则
General Output Control
    -o, --only-matching 仅匹配非空格
    -v, --invert-match 非匹配
Context Line Control
    -A NUM, --after-context=NUM 打印匹配行之后第几行

awk

以前写过一篇Linux命令之awk,详细内容可以进去查看。这里只涉及需要用到的。

实例:

cat xxx | awk -F'[: ]+' '$0~/inet addr:/{printf $4"|"}
awk -v eth=$eth -F'[: ]+' '{if ($0 ~eth){print $3,$11}}

手册:

awk '/search pattern1/ {Actions}    
     /search pattern2/ {Actions}' file    
     
* search pattern是正则表达式
* Actions 输出的语法
* 在Awk 中可以存在多个正则表达式和多个输出定义
* file 输入文件名
* 单引号的作用是包裹起来防止shell截断

背景概念:

awk默认是以行为单位处理文本的 awk中的两个术语:

    记录(默认就是文本的每一行)
    字段 (默认就是每个记录中由空格或TAB分隔的字符串)

$0就表示一个记录,$1表示记录中的第一个字段。

解释:

-F'[: ]+' 以:或者空格作为分隔符
$0表示一个记录(行)
~ 表示模式开始。/ /中是模式。
/inet addr:/这就是一个正则表达式的匹配
{printf $4"|"} 打印按照分隔符分割所成数组的第四个字段

-v 是将 Shell 变量 $eth 的值传给 awk 变量。

sed

sed在处理文本文件的时候,会在内存上创建一个模式空间,然后把这个文件的每一行调入模式空间用相应的命令处理,处理完输出;接着处理下一行,直到最后。

cat xxx | sed -e 's/|$//' 
cat xxx | sed  -n '1,3p' ## 打印1~3行

手册:

sed [选项]  [定址commands] [inputfile]

关于定址:
定址可以是0个、1个、2个;通知sed去处理文件的哪几行。
0个:没有定址,处理文件的所有行
1个:行号,处理行号所在位置的行
2个:行号、正则表达式,处理被行号或正则表达式包起来的行

/proc/net/dev

Inter-|   Receive                                                |  Transmit
 face |bytes    packets errs drop fifo frame compressed multicast|bytes    packets errs drop fifo colls carrier compressed
  ppp1: 2007461   25873    0    0    0     0          0         0 33320940   30484    0    0    0     0       0          0
    lo: 443577110 1042128    0    0    0     0          0         0 443577110 1042128    0    0    0     0       0          0
  ppp0: 5894011   36473    0    0    0     0          0         0 72146111   64491    0    0    0     0       0          0
docker0:       0       0    0    0    0     0          0         0        0       0    0    0    0     0       0          0
  eth0: 59705148255 56461407    0    0    0     0          0         0 49418615742 41712001    0    0    0     0       0          0

ss

ss命令可以用来获取socket统计信息,它可以显示和netstat类似的内容。

tcpdump

tcpdump可以将网络中传送的数据包的“头”完全截获下来提供分析。它支持针对网络层、协议、主机、网络或端口的过滤。

基本上tcpdump总的的输出格式为:系统时间 来源主机.端口 > 目标主机.端口 数据包参数

-i eth0  # 监视指定网络接口的数据包 

例子

代码如下:下载地址

#!/bin/bash
 
#write by zhumaohai(admin#centos.bz)
#author blog: www.centos.bz
 
 
#显示菜单(单选)
display_menu(){
local soft=$1
local prompt="which ${soft} you'd select: "
eval local arr=(\${${soft}_arr[@]})
while true
do
    echo -e "#################### ${soft} setting ####################\n\n"
    for ((i=1;i<=${#arr[@]};i++ )); do echo -e "$i) ${arr[$i-1]}"; done
    echo
    read -p "${prompt}" $soft
    eval local select=\$$soft
    if [ "$select" == "" ] || [ "${arr[$soft-1]}" == ""  ];then
        prompt="input errors,please input a number: "
    else
        eval $soft=${arr[$soft-1]}
        eval echo "your selection: \$$soft"             
        break
    fi
done
}
 
#把带宽bit单位转换为人类可读单位
bit_to_human_readable(){
    #input bit value
    local trafficValue=$1
 
    if [[ ${trafficValue%.*} -gt 922 ]];then
        #conv to Kb
        trafficValue=`awk -v value=$trafficValue 'BEGIN{printf "%0.1f",value/1024}'`
        if [[ ${trafficValue%.*} -gt 922 ]];then
            #conv to Mb
            trafficValue=`awk -v value=$trafficValue 'BEGIN{printf "%0.1f",value/1024}'`
            echo "${trafficValue}Mb"
        else
            echo "${trafficValue}Kb"
        fi
    else
        echo "${trafficValue}b"
    fi
}
 
#判断包管理工具
check_package_manager(){
    local manager=$1
    local systemPackage=''
    if cat /etc/issue | grep -q -E -i "ubuntu|debian";then
        systemPackage='apt'
    elif cat /etc/issue | grep -q -E -i "centos|red hat|redhat";then
        systemPackage='yum'
    elif cat /proc/version | grep -q -E -i "ubuntu|debian";then
        systemPackage='apt'
    elif cat /proc/version | grep -q -E -i "centos|red hat|redhat";then
        systemPackage='yum'
    else
        echo "unkonw"
    fi
 
    if [ "$manager" == "$systemPackage" ];then
        return 0
    else
        return 1
    fi   
}
 
 
#实时流量
realTimeTraffic(){
    local eth=""
    local nic_arr=(`ifconfig | grep -E -o "^[a-z0-9]+" | grep -v "lo" | uniq`)
    local nicLen=${#nic_arr[@]}
    if [[ $nicLen -eq 0 ]]; then
        echo "sorry,I can not detect any network device,please report this issue to author."
        exit 1
    elif [[ $nicLen -eq 1 ]]; then
        eth=$nic_arr
    else
        display_menu nic
        eth=$nic
    fi   
 
    local clear=true
    local eth_in_peak=0
    local eth_out_peak=0
    local eth_in=0
    local eth_out=0
 
    while true;do
        #移动光标到0:0位置
        printf "\033[0;0H"
        #清屏并打印Now Peak
        [[ $clear == true ]] && printf "\033[2J" && echo "$eth--------Now--------Peak-----------"
        traffic_be=(`awk -v eth=$eth -F'[: ]+' '{if ($0 ~eth){print $3,$11}}' /proc/net/dev`)
        sleep 2
        traffic_af=(`awk -v eth=$eth -F'[: ]+' '{if ($0 ~eth){print $3,$11}}' /proc/net/dev`)
        #计算速率
        eth_in=$(( (${traffic_af[0]}-${traffic_be[0]})*8/2 ))
        eth_out=$(( (${traffic_af[1]}-${traffic_be[1]})*8/2 ))
        #计算流量峰值
        [[ $eth_in -gt $eth_in_peak ]] && eth_in_peak=$eth_in
        [[ $eth_out -gt $eth_out_peak ]] && eth_out_peak=$eth_out
        #移动光标到2:1
        printf "\033[2;1H"
        #清除当前行
        printf "\033[K"   
        printf "%-20s %-20s\n" "Receive:  $(bit_to_human_readable $eth_in)" "$(bit_to_human_readable $eth_in_peak)"
        #清除当前行
        printf "\033[K"
        printf "%-20s %-20s\n" "Transmit: $(bit_to_human_readable $eth_out)" "$(bit_to_human_readable $eth_out_peak)"
        [[ $clear == true ]] && clear=false
    done
}
 
#流量和连接概览
trafficAndConnectionOverview(){
    if ! which tcpdump > /dev/null;then
        echo "tcpdump not found,going to install it."
        if check_package_manager apt;then
            apt-get -y install tcpdump
        elif check_package_manager yum;then
            yum -y install tcpdump
        fi
    fi
 
    local reg=""
    local eth=""
    local nic_arr=(`ifconfig | grep -E -o "^[a-z0-9]+" | grep -v "lo" | uniq`)
    local nicLen=${#nic_arr[@]}
    if [[ $nicLen -eq 0 ]]; then
        echo "sorry,I can not detect any network device,please report this issue to author."
        exit 1
    elif [[ $nicLen -eq 1 ]]; then
        eth=$nic_arr
    else
        display_menu nic
        eth=$nic
    fi
 
    echo "please wait for 10s to generate network data..."
    echo
    #当前流量值
    local traffic_be=(`awk -v eth=$eth -F'[: ]+' '{if ($0 ~eth){print $3,$11}}' /proc/net/dev`)
    #tcpdump监听网络
    tcpdump -v -i $eth -tnn > /tmp/tcpdump_temp 2>&1 &
    sleep 10
    clear
    kill `ps aux | grep tcpdump | grep -v grep | awk '{print $2}'`

    #10s后流量值
    local traffic_af=(`awk -v eth=$eth -F'[: ]+' '{if ($0 ~eth){print $3,$11}}' /proc/net/dev`)
    #打印10s平均速率
    local eth_in=$(( (${traffic_af[0]}-${traffic_be[0]})*8/10 ))
    local eth_out=$(( (${traffic_af[1]}-${traffic_be[1]})*8/10 ))
    echo -e "\033[32mnetwork device $eth average traffic in 10s: \033[0m"
    echo "$eth Receive: $(bit_to_human_readable $eth_in)/s"
    echo "$eth Transmit: $(bit_to_human_readable $eth_out)/s"
    echo

    local regTcpdump=$(ifconfig | grep -A 1 $eth | awk -F'[: ]+' '$0~/inet addr:/{printf $4"|"}' | sed -e 's/|$//' -e 's/^/(/' -e 's/$/)\\\\\.[0-9]+:/')
  
    #新旧版本tcpdump输出格式不一样,分别处理
    if awk '/^IP/{print;exit}' /tmp/tcpdump_temp | grep -q ")$";then
        #处理tcpdump文件
        awk '/^IP/{print;getline;print}' /tmp/tcpdump_temp > /tmp/tcpdump_temp2
    else
        #处理tcpdump文件
        awk '/^IP/{print}' /tmp/tcpdump_temp > /tmp/tcpdump_temp2
        sed -i -r 's#(.*: [0-9]+\))(.*)#\1\n    \2#' /tmp/tcpdump_temp2
    fi
    
    awk '{len=$NF;sub(/\)/,"",len);getline;print $0,len}' /tmp/tcpdump_temp2 > /tmp/tcpdump

    #统计每个端口在10s内的平均流量
    echo -e "\033[32maverage traffic in 10s base on server port: \033[0m"
    awk -F'[ .:]+' -v regTcpdump=$regTcpdump '{if ($0 ~ regTcpdump){line="clients > "$8"."$9"."$10"."$11":"$12}else{line=$2"."$3"."$4"."$5":"$6" > clients"};sum[line]+=$NF*8/10}END{for (line in sum){printf "%s %d\n",line,sum[line]}}' /tmp/tcpdump | \
    sort -k 4 -nr | head -n 10 | while read a b c d;do
        echo "$a $b $c $(bit_to_human_readable $d)/s"
    done
    echo -ne "\033[11A"
    echo -ne "\033[50C"
    echo -e "\033[32maverage traffic in 10s base on client port: \033[0m"
    awk -F'[ .:]+' -v regTcpdump=$regTcpdump '{if ($0 ~ regTcpdump){line=$2"."$3"."$4"."$5":"$6" > server"}else{line="server > "$8"."$9"."$10"."$11":"$12};sum[line]+=$NF*8/10}END{for (line in sum){printf "%s %d\n",line,sum[line]}}' /tmp/tcpdump | \
    sort -k 4 -nr | head -n 10 | while read a b c d;do
            echo -ne "\033[50C"
            echo "$a $b $c $(bit_to_human_readable $d)/s"
    done   
        
    echo

    #统计在10s内占用带宽最大的前10个ip
    echo -e "\033[32mtop 10 ip average traffic in 10s base on server: \033[0m"
    awk -F'[ .:]+' -v regTcpdump=$regTcpdump '{if ($0 ~ regTcpdump){line=$2"."$3"."$4"."$5" > "$8"."$9"."$10"."$11":"$12}else{line=$2"."$3"."$4"."$5":"$6" > "$8"."$9"."$10"."$11};sum[line]+=$NF*8/10}END{for (line in sum){printf "%s %d\n",line,sum[line]}}' /tmp/tcpdump | \
    sort -k 4 -nr | head -n 10 | while read a b c d;do
        echo "$a $b $c $(bit_to_human_readable $d)/s"
    done
    echo -ne "\033[11A"
    echo -ne "\033[50C"
    echo -e "\033[32mtop 10 ip average traffic in 10s base on client: \033[0m"
    awk -F'[ .:]+' -v regTcpdump=$regTcpdump '{if ($0 ~ regTcpdump){line=$2"."$3"."$4"."$5":"$6" > "$8"."$9"."$10"."$11}else{line=$2"."$3"."$4"."$5" > "$8"."$9"."$10"."$11":"$12};sum[line]+=$NF*8/10}END{for (line in sum){printf "%s %d\n",line,sum[line]}}' /tmp/tcpdump | \
    sort -k 4 -nr | head -n 10 | while read a b c d;do
        echo -ne "\033[50C"
        echo "$a $b $c $(bit_to_human_readable $d)/s"
    done 

    echo
    #统计连接状态
    local regSS=$(ifconfig | grep -A 1 $eth | awk -F'[: ]+' '$0~/inet addr:/{printf $4"|"}' | sed -e 's/|$//')
    ss -an | grep -v -E "LISTEN|UNCONN" | grep -E "$regSS" > /tmp/ss
    echo -e "\033[32mconnection state count: \033[0m"
    awk 'NR>1{sum[$(NF-4)]+=1}END{for (state in sum){print state,sum[state]}}' /tmp/ss | sort -k 2 -nr
    echo
    #统计各端口连接状态
    echo -e "\033[32mconnection state count by port base on server: \033[0m"
    awk 'NR>1{sum[$(NF-4),$(NF-1)]+=1}END{for (key in sum){split(key,subkey,SUBSEP);print subkey[1],subkey[2],sum[subkey[1],subkey[2]]}}' /tmp/ss | sort -k 3 -nr | head -n 10   
    echo -ne "\033[11A"
    echo -ne "\033[50C"
    echo -e "\033[32mconnection state count by port base on client: \033[0m"
    awk 'NR>1{sum[$(NF-4),$(NF)]+=1}END{for (key in sum){split(key,subkey,SUBSEP);print subkey[1],subkey[2],sum[subkey[1],subkey[2]]}}' /tmp/ss | sort -k 3 -nr | head -n 10 | awk '{print "\033[50C"$0}'   
    echo   
    #统计端口为80且状态为ESTAB连接数最多的前10个IP
    echo -e "\033[32mtop 10 ip ESTAB state count at port 80: \033[0m"
    cat /tmp/ss | grep ESTAB | awk -F'[: ]+' '{sum[$(NF-2)]+=1}END{for (ip in sum){print ip,sum[ip]}}' | sort -k 2 -nr | head -n 10
    echo
    #统计端口为80且状态为SYN-RECV连接数最多的前10个IP
    echo -e "\033[32mtop 10 ip SYN-RECV state count at port 80: \033[0m"
    cat /tmp/ss | grep -E "$regSS" | grep SYN-RECV | awk -F'[: ]+' '{sum[$(NF-2)]+=1}END{for (ip in sum){print ip,sum[ip]}}' | sort -k 2 -nr | head -n 10
}
 
main(){
    while true; do
        echo -e "1) real time traffic.\n2) traffic and connection overview.\n"
        read -p "please input your select(ie 1): " select
        case  $select in
            1) realTimeTraffic;break;;
            2) trafficAndConnectionOverview;break;;
            *) echo "input error,please input a number.";;
        esac
    done   
}
 
main

获得本机 ip

ifconfig | grep -A 1 $eth | awk -F'[: ]+' '$0~/inet addr:/{printf $4"|"}' | sed -e 's/|$//' -e 's/^/(/' -e 's/$/)\\\\\.[0-9]+:/'

结果:

(103.29.71.237)\\.[0-9]+:#

接口流量/proc/net/dev

awk -F'[: ]+' '{if ($0 ~eth0){print $3,$11}}' /proc/net/dev

tcpdump监听网络

tcpdump -v -i eth0 -tnn > /tmp/tcpdump_temp 2>&1 &

杀死进程

kill `ps aux | grep tcpdump | grep -v grep | awk '{print $2}'`

统计10s内速率

awk -F'[ .:]+' -v regTcpdump=$regTcpdump '{if ($0 ~ regTcpdump){line="clients > "$8"."$9"."$10"."$11":"$12}else{line=$2"."$3"."$4"."$5":"$6" > clients"};sum[line]+=$NF*8/10}END{for (line in sum){printf "%s %d\n",line,sum[line]}}' /tmp/tcpdump | \
sort -k 4 -nr | head -n 10 | while read a b c d;do
    echo "$a $b $c $(bit_to_human_readable $d)/s"
done

这一段太复杂了,看不懂Orz

参考资料


python3 的安装与 virtualenv 建立虚拟环境

就目前来说,所有 Linux 发行版自带的python都是python2,由于python3与2不兼容,所以python3的推进一直不顺利。然而我也不想直接踢掉系统的python2环境,哪天需要的时候不还得搞一遍回来么?好在python官方提供了virtualenv环境,可以无缝使用不同版本间的Python。

最近开始部署 python 应用了。于是记录一下配置 python3 环境的步骤。

编译安装Python3.6

直接选择了最新的python版本: 官网下载

cd /tmp
wget https://www.python.org/ftp/python/3.6.1/Python-3.6.1.tgz
tar -xzvf Python-3.6.1.tgz
cd Python-3.6.1
mkdir /usr/local/python3.6
./configure --prefix=/usr/local/python3.6
make
make install

然后 python3 就安装好了。这次安装会将pip也一并安装了。

安装 Python2 的 pip

两种方式,一种是源码安装:

cd /tmp
wget https://bootstrap.pypa.io/get-pip.py
python get-pip.py

另一种是 apt 安装(Debian系)。

安装virtualenv

pip install virtualenv

使用virtualenv

创建虚拟环境

cd /var/local
virtualenv -p /usr/local/python3.6/bin/python3.6 xx

指定使用python3.6创建一个项目虚拟环境.

激活虚拟环境

cd xx                    # 切换至项目目录
source ./bin/activate

退出虚拟环境

deactivate      # 退出项目的 virtualenv 虚拟环境.

问题定位

参考资料