You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求:基于Awk实现多路径文件创建检测的Debian12 Bash脚本

Debian 12 路径可写性检测脚本(适配Telegraf)

实现思路

  • 先做参数校验,确保至少传入1个路径
  • 用Awk批量处理每个路径:先判断目录是否存在,再通过创建临时文件测试可写性,最后清理临时文件
  • 输出Telegraf兼容的JSON格式,方便指标存入数据库

完整脚本

#!/bin/bash

# 校验参数数量,不够就返回错误JSON
if [ $# -lt 1 ]; then
    echo '{"error": "至少需要传入一个路径参数"}'
    exit 1
fi

# 把所有路径传给Awk处理
printf "%s\n" "$@" | awk '
function check_writable(path) {
    # 生成随机临时文件,避免和已有文件冲突
    tmp_file = path "/.write_test_" rand() ".tmp"
    # 尝试写入测试内容,重定向错误到/dev/null
    cmd = "echo \"test\" > " tmp_file " 2>/dev/null"
    exit_code = system(cmd)
    # 不管成功失败都删掉临时文件
    system("rm -f " tmp_file " 2>/dev/null")
    # 返回0表示可写,1表示不可写
    return (exit_code == 0) ? 0 : 1
}

BEGIN {
    print "["
    first_entry = 1
    srand() # 初始化随机数种子
}

{
    target_path = $0
    # 先判断目录是否存在
    dir_check_cmd = "test -d " target_path " 2>/dev/null"
    dir_exists = (system(dir_check_cmd) == 0) ? 1 : 0
    
    writable_status = 0
    if (dir_exists) {
        # 转换为1=可写,0=不可写,符合Telegraf字段习惯
        writable_status = 1 - check_writable(target_path)
    }

    # 输出JSON对象,处理数组逗号分隔
    if (!first_entry) {
        print ","
    }
    printf "{\"tags\": {\"path\": \"%s\"}, \"fields\": {\"directory_exists\": %d, \"writable\": %d}}", target_path, dir_exists, writable_status
    first_entry = 0
}

END {
    print "\n]"
}
'

使用方法

  1. 把脚本存成check_path_writability.sh
  2. 赋予执行权限:chmod +x check_path_writability.sh
  3. 运行时传入任意数量路径:./check_path_writability.sh /tmp /var/log /home/yourname/test_dir

输出格式说明

输出的是JSON数组,每个元素对应一个路径的检测结果,完全适配Telegraf的exec插件:

  • tags.path:被检测的路径(作为标签,方便后续筛选)
  • fields.directory_exists:目录是否存在(1=存在,0=不存在)
  • fields.writable:目录是否可写(1=可写,0=不可写)

Telegraf配置示例(添加到telegraf.conf中):

[[inputs.exec]]
  commands = ["/opt/scripts/check_path_writability.sh /tmp /var/log"]
  data_format = "json"
  tag_keys = ["path"]

内容的提问来源于stack exchange,提问作者teeeeee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 00:19:59