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

如何通过Crontab每日23:59将登录用户列表追加至日志文件?

解决方案

1. 修正并编写执行脚本

你现有的脚本存在两处问题:shebang(脚本开头的解释器声明)顺序写反了,且脚本内不需要包含crontab的时间表达式。请创建或修改脚本/root/log_users.sh,内容如下:

#!/bin/bash
# 输出指定格式的GMT时间戳
TZ=GMT date "+%a %d %b %T %Z %Y" >> /root/userlogfile.txt
# 添加空行分隔时间戳与用户列表
echo "" >> /root/userlogfile.txt
# 格式化who命令的输出并追加到日志
who | awk '{
    # 将月份缩写转换为两位数字
    month_idx = index("JanFebMarAprMayJunJulAugSepOctNovDec", $4)
    month = sprintf("%02d", (month_idx + 2) / 3)
    # 提取并格式化日期、时间
    year = substr($5, 7, 4)
    day = substr($5, 1, 2)
    time = substr($6, 1, 5)
    # 按期望格式输出,每个用户条目后添加空行
    printf "%-8s %-8s %s-%s-%s %s\n\n", $1, $2, year, month, day, time
}' >> /root/userlogfile.txt

2. 设置脚本可执行权限

运行以下命令赋予脚本执行权限:

chmod +x /root/log_users.sh

3. 配置Crontab定时任务

执行crontab -e编辑定时任务,添加以下一行(测试阶段可替换为18 18 * * *):

59 23 * * * /root/log_users.sh

关键说明

  • 时间戳格式:通过TZ=GMT date "+%a %d %b %T %Z %Y"强制使用GMT时区,输出完全匹配你期望的Fri 09 Dec 23:59:00 GMT 2022格式。
  • 用户列表格式化:使用awk处理who的输出,将默认的月份缩写转为两位数字,日期调整为YYYY-MM-DD格式,时间保留小时和分钟部分,同时通过printf控制列宽,添加空行分隔每个用户条目。
  • 测试验证:你可以直接手动运行/root/log_users.sh,查看/root/userlogfile.txt的内容是否符合预期,无需等待crontab触发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 13:25:33