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

如何通过systemd系统服务运行bash脚本启动tmux内的Discord机器人

问题核心原因
  • 系统服务默认以root身份运行,脚本内的~会被解析为root的家目录,无法定位到flynn用户目录下的Python脚本,命令执行直接失败
  • systemd系统服务上下文缺少普通用户会话的终端环境变量,tmux运行逻辑异常;同时当前配置的Type=simple会将执行完成的bash脚本判定为服务结束,触发自动重启逻辑,反复重建tmux会话
  • 没有配置日志输出,无法直接看到Python脚本的运行报错,排查难度高
最优解决方案(移除冗余tmux,直接用systemd管理进程)

systemd本身已经支持进程生命周期托管、开机自启、自动重启、日志收集等能力,额外引入tmux完全没有必要,直接修改service配置即可:

[Unit]
Description=UbuntuBot
After=network.target

[Install]
WantedBy=multi-user.target

[Service]
# 指定运行服务的用户和用户组,避免权限问题
User=flynn
Group=flynn
# 指定工作目录,和脚本运行路径一致
WorkingDirectory=/home/flynn/Minecraft/CreativeServer/DiscordBot
Type=simple
# 直接用绝对路径启动Python脚本
ExecStart=/usr/bin/python3 /home/flynn/Minecraft/CreativeServer/DiscordBot/Ubuntubot.py
# 异常自动重启配置
Restart=always
RestartSec=5
# 配置日志输出到systemd日志
StandardOutput=journal+console
StandardError=journal+console

配置完成后执行以下命令生效:

# 重新加载systemd配置
sudo systemctl daemon-reload
# 重启服务
sudo systemctl restart ubuntubot.service

需要查看机器人运行日志时执行:

journalctl -u ubuntubot.service -f
保留tmux的修改方案

如果确实需要保留tmux会话方便手动附着调试,按以下方式修改:

修改service配置

[Unit]
Description=UbuntuBot
After=network.target

[Install]
WantedBy=multi-user.target

[Service]
User=flynn
Group=flynn
WorkingDirectory=/home/flynn/Minecraft/CreativeServer/DiscordBot
# 配置为oneshot+RemainAfterExit,告知systemd bash脚本执行完成后服务仍处于正常运行状态
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/bash /home/flynn/Minecraft/CreativeServer/DiscordBot/launchbot.sh
Restart=always
RestartSec=5

修改bash启动脚本

#!/bin/bash
# 先判断会话是否存在,避免重复创建报错
/usr/bin/tmux has-session -t ubuntubot 2>/dev/null
if [ $? != 0 ]; then
    /usr/bin/tmux new-session -d -s ubuntubot
fi
# 使用绝对路径启动Python脚本,避免路径解析错误
/usr/bin/tmux send-keys -t ubuntubot "python3 /home/flynn/Minecraft/CreativeServer/DiscordBot/Ubuntubot.py" Enter

修改完成后同样执行systemctl daemon-reload和systemctl restart ubuntubot.service生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 18:57:03