必须设为 /sbin/nologin 而非 /bin/false,因其被 rhel/centos 的 pam 和 login 明确认可,返回清晰提示且兼容 cron、su -c 等机制;而 /bin/false 在部分版本中会导致 cron 任务静默失败。

服务账号无 shell 配置,核心目标是阻止其交互式登录,同时保障系统服务正常运行。这不是简单删掉 shell,而是用合法、可控的方式切断登录入口,又不干扰 cron、systemd 或其他依赖该账户的服务调用。
为什么必须设为 /sbin/nologin 而非 /bin/false?
RHEL/CentOS 系统中,/sbin/nologin 是 PAM 和 login 程序明确认可的“不可登录 shell”,会返回清晰提示(如 This account is currently not available.),且兼容 cron、at、su -c 等机制;而 /bin/false 在部分补丁版本中会导致 cron 任务静默失败——任务被 exec 调用时直接退出,不报错也不执行。
确保 /sbin/nologin 被系统认可
该路径必须写入 /etc/shells,否则 su - username 会报错 Cannot execute /sbin/nologin: No such file or directory(即使文件真实存在)。
- RHEL 8+ 默认已包含;
- RHEL 7 需手动追加:
echo "/sbin/nologin" >> /etc/shells
验证命令:
grep nologin /etc/shells
批量设置服务账号 shell
对所有非交互账户(如 nginx、mysql、redis、daemon 等),统一设为 /sbin/nologin:
# 查看当前使用 /bin/bash 或 /bin/sh 的系统账号 awk -F: '$3 <p><strong>验证是否生效</strong> </p><div class="aritcle_card flexRow artxards"> <div class="artcardd flexRow"> <a class="aritcle_card_img" rel="nofollow" href="/ai/951" title="Felo"><img src="https://img.php.cn/upload/ai_manual/000/000/000/175680005526161.jpg" alt="Felo" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a> <div class="aritcle_card_info flexColumn"> <a rel="nofollow" href="/ai/951" title="Felo" class="overflowclass">Felo</a> <p class="overflowclass">Felo是一款结合 AI 搜索、实时翻译、研究整理和内容生成的多语言智能工具。</p> </div> <a rel="nofollow" href="/ai/951" title="Felo" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a> </div> </div>
- SSH 登录该账号:立即断开,并显示
This account is currently not available. -
su - nginx -c 'whoami':返回This account is currently not available.,不进入 shell -
ps aux | grep nginx:服务进程仍正常运行(说明未影响服务本身)
补充兜底:PAM 层限制(防绕过)
仅改 shell 字段无法拦截 sudo -u nginx /bin/bash 或 SSH 的 command= 强制执行。需配合 PAM:
- 创建禁止执行 shell 的组:
groupadd noexec usermod -aG noexec nginx mysql
- 编辑
/etc/pam.d/system-auth,在auth [default=die]行前插入:auth [success=ok default=bad] pam_succeed_if.so user ingroup noexec auth [default=die] pam_deny.so
此配置让属于
noexec组的用户,任何尝试启动交互式 shell 的行为均被拒绝。
服务账号无 shell 不是“一刀切禁用”,而是精准隔离——让它们只做本职(运行服务),不做任何登录或命令执行。配置到位后,既堵住提权跳板,又不伤业务连续性。










