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

编写阿里云密码到期提醒Bash脚本遇错,请求排查问题

错误排查与修复方案

错误1:chage: user 'user' does not exist in /etc/passwd

  • 原因:脚本硬编码了固定用户名user,但你的系统中不存在该用户。
  • 解决方法:将chage -l user中的user替换为实际要检查的阿里云服务器用户名(比如root或业务专属账号);若需批量检查所有用户,可改为遍历/etc/passwd中的用户列表。

错误2:syntax error: invalid arithmetic operator (error token is ")

  • 原因:当chage命令执行失败(如用户不存在),expiration_date会为空值,导致date -d "$expiration_date" +%s解析失败,expiration_timestamp变成非数字字符串,后续算术运算无法执行。此外,若用户密码设置为永不过期,expiration_date会返回never,同样会触发date命令解析错误。
  • 解决方法:添加用户存在性校验,同时判断密码过期日期的有效性,避免非数字值进入算术运算逻辑。

修正后的完整脚本

#!/bin/bash
recipient="someone@gmail.com"  # 替换为实际收件人邮箱
subject="阿里云账号密码过期提醒"
target_user="root"  # 替换为你要检查的目标用户名

# 先校验目标用户是否存在
if ! id "$target_user" &>/dev/null; then
    echo "错误:用户 $target_user 不存在"
    exit 1
fi

# 获取密码过期日期,处理密码永不过期的情况
expiration_date=$(chage -l "$target_user" | grep "Password expires" | awk -F ":" '{print $2}' | xargs)
if [ "$expiration_date" = "never" ]; then
    echo "用户 $target_user 的密码永不过期,无需提醒"
    exit 0
fi

# 转换为时间戳并计算剩余天数
expiration_timestamp=$(date -d "$expiration_date" +%s)
current_timestamp=$(date +%s)
difference_in_seconds=$((expiration_timestamp - current_timestamp))
difference_in_days=$((difference_in_seconds / 60 / 60 / 24))

# 若剩余天数≤60且≥0,发送提醒邮件
if [ "$difference_in_days" -le 60 ] && [ "$difference_in_days" -ge 0 ]; then
message="您好,

这是阿里云账号密码过期提醒。定期更新密码是保障账号安全的重要措施。

您的密码将在 $difference_in_days 天后过期,请及时修改。

感谢配合,
产品团队"

    echo "$message" | mail -s "$subject" "$recipient"
fi

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 18:55:16