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

Ubuntu20.04服务器闲置用户踢出脚本报错求助

问题分析

错误line 16: 9:47: syntax error in expression的核心原因是:w命令输出的闲置时间(如9:47)是时间格式字符串,而非纯数字,原脚本直接将其用于算术运算(idle*60)导致语法错误。此外脚本还存在两个隐性问题:

  • now变量未定义,无法计算活跃时间戳
  • pkill -t "$username"用法错误,-t选项针对的是终端(TTY),而非用户名
修正后的脚本
#!/bin/bash
# 获取当前时间戳(秒)
now=$(date +%s)
# 定义转换闲置时间为秒的函数
convert_idle_to_seconds() {
    local idle="$1"
    local total_seconds=0

    # 处理天+时分格式,如2+10:30
    if [[ "$idle" =~ ^([0-9]+)\+([0-9]+):([0-9]+)$ ]]; then
        local days=${BASH_REMATCH[1]}
        local hours=${BASH_REMATCH[2]}
        local mins=${BASH_REMATCH[3]}
        total_seconds=$(( days*86400 + hours*3600 + mins*60 ))
    # 处理时分格式,如1:45
    elif [[ "$idle" =~ ^([0-9]+):([0-9]+)$ ]]; then
        local hours=${BASH_REMATCH[1]}
        local mins=${BASH_REMATCH[2]}
        total_seconds=$(( hours*3600 + mins*60 ))
    # 处理分钟格式,如30m
    elif [[ "$idle" =~ ^([0-9]+)m$ ]]; then
        local mins=${BASH_REMATCH[1]}
        total_seconds=$(( mins*60 ))
    # 处理活跃状态(.表示当前无闲置)
    elif [[ "$idle" == "." ]]; then
        total_seconds=0
    # 处理纯数字(单位为分钟,部分系统输出)
    elif [[ "$idle" =~ ^[0-9]+$ ]]; then
        total_seconds=$(( idle*60 ))
    fi

    echo "$total_seconds"
}

while read -r username tty from idle jcpu pcpu what; do
    # 转换闲置时间为秒
    idle_seconds=$(convert_idle_to_seconds "$idle")

    # 跳过活跃用户(闲置0秒)
    if [[ "$idle_seconds" -eq 0 ]]; then
        continue
    fi

    # 计算最后活跃时间戳
    last_active=$(( now - idle_seconds ))
    # 1小时前的时间戳
    one_hour_ago=$(( now - 3600 ))

    # 判断是否闲置超过1小时
    if [[ "$idle_seconds" -gt 3600 ]]; then
        echo "Killing idle session for user $username on tty $tty (idle for $idle_seconds seconds)"
        # 通过终端TTY踢会话,而非杀掉用户所有进程
        pkill -kill -t "$tty"
    fi
done < <(w -h)
关键修正点
  • 闲置时间转换:新增convert_idle_to_seconds函数,处理w命令输出的所有常见闲置时间格式(天+时分、时分、分钟、活跃状态),统一转换为秒数
  • 时间戳初始化:用date +%s获取当前时间戳,解决now未定义问题
  • 修正pkill用法:使用终端TTY($tty)作为pkill -t的参数,精准踢掉闲置会话,避免误杀用户其他进程
  • 跳过活跃用户:闲置0秒的用户直接跳过,无需处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 02:20:38