一些shell脚本使用案例

# 简述

最近在接手的业务发现依赖于人的地方比较多,但其中并无技术含量,只需要改改参数即可,使用shell可以更高效的完成这些事情。记录下日常使用的比较多的案例

让混乱标准化,让标准系统化,让系统自动化。

# 环境

系统:debian11

# 查询一批订单详细数据

背景:有一批订单号,运营希望知道这批订单都是哪些商品,由于无数据库权限,只能通过接口来进行查询

已有内容:

  • 一批订单号

  • 查询订单接口(Get:https://xxx.com)

  • 接口返回内容

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{
    "tags":[

    ],
    "ext":{
        "orderNo":"400994",
    },
    "errmsg":"",
    "id":"29346273894789234782",
    "name":"霸王洗发水",
} 
  • 安装jq
1
apt install jq -y
  • 详细脚本内容
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
list=$(cat order.txt)

for id in ${list}; do
{
    url="https://xxx.com/getOrderById/${id}"
    res=$(curl -X GET -s  ${url})
    printf "%s\t" ${id}
    printf "%s" ${res} | jq -r ".name" | tr -d "\n"
    printf "\t"
    printf "%s" ${res} | jq -r ".ext.orderNo"
}
done

# 通过日志中心接口做监控报警

背景:系统中存在着一些恶意用户,通过某种方式刷接口,现在需要在日志中发现这些用户,取最高10名,推送至企业微信机器人

  • 已有内容

日志中心接口:https://xxx.com/search/group(POST)

  • 脚本内容
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#获取当前时间
time=`date +%s`

#昨天零点
endTime=$(((${time}+3600*8)/86400*86400-3600*8))
startTime=$((${endTime}-86400))'000'
endTime=${endTime}'000'

#将时间戳格式化标准时间格式
today=$(date -d "1970-01-01 UTC $((${startTime}/1000)) seconds" "+%F")

#日志中心url
req_url="https://xxx.com/search/group"
#机器人推送文字
req_content='{"startTime": '"${startTime}"', "endTime": '"${endTime}"', "groupField": "userid", "orderBy": "desc","page": 1,"limit": 10}'

#header
req_header_1="Content-Type: application/json"
req_header_2="token: kajshdkajsdhrakfhakjsfskfhjs"
req_header_3="dlkklsdflsdfls: asdvcdasd"
req_header_4="wiejkadhjka: 1231313123"

res=$(curl -s "$req_url" -H "$req_header_1" -H "$req_header_2" -H "$req_header_3" -H "$req_header_4" -d "$req_content")

result='**'"${today}"'日疑似恶意用户**\n说明:<font color=\"warning\">数据来源于日志中心, 每天统计一次,前10名最多消息数</font>\n'$(printf "%s" ${res} | jq -r '.data[] | to_entries[] | "[\(.key)]\t\(.value)"')


robot_url="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=asdajkfhkjsdklcnlds"
robot_content='{"msgtype": "markdown","markdown": {"content": "'"${result}"'"}}'
echo ${robot_content}
robot_header="Content-Type: application/json"

robot_res=$(curl -s "$robot_url" -H "$robot_header" -d "$robot_content")
Licensed under CC BY-NC-SA 4.0