在以用户身份(非 root)登录之前在启动时创建 tmux 会话

在以用户身份(非 root)登录之前在启动时创建 tmux 会话

我在家里为朋友们托管了一个小型 minecraft 服务器,为了让事情变得更容易,我想让它在我打开用作服务器的 PC 时自动启动 minecraft 服务器。问题是我使用 tmux 来管理服务器,以防万一。为此,我有这个脚本:

#!/bin/bash

SESSION="server"
SESSIONEXISTS=$(tmux list-sessions | grep -w "$SESSION")

if [ "$SESSIONEXISTS" = "" ]
then

  tmux new-session -d -s "$SESSION" -d -x "$(tput cols)" -y "$(tput lines)"

  tmux rename-window -t 0 'mc'
  tmux send-keys -t 'mc' 'cd magma-1.18.2-40.2.10 && ./run.sh && sudo shutdown now' C-m
  tmux splitw -v

  tmux send-keys -t 'mc' 'glances' C-m
  tmux select-pane -t 0
  tmux splitw -h

  tmux send-keys -t 'mc' 'ngrok start --all' C-m

  tmux select-pane -t 0

fi

tmux attach-session -t "$SESSION":0

我尝试使用 cron,但没有成功:

@reboot bash /home/fpp/startup.sh

它只是不会启动 tmux 会话。

我也尝试使用 systemd 单元:[Unit]

Description=mcnrelated.service

After=default.target

[Service]

ExecStart=bash /home/fpp/startup.sh

[Install]

WantedBy=default.target

但是在启动时,我看到该服务由于错误而未启动。

作为最后的选择,我尝试使用 rc.local:

#!/bin/bash
sudo su -c "./home/fpp/startup.sh" -s /bin/sh fpp
exit 0

但同样,没有启动 tmux 会话。

该问题是否与 tmux 有关?或者我做错了什么?

编辑:可行的方法是使用 systemd。

在与 ChatGPT 进行了大量交流后,我终于弄清楚了,在我的脚本中,我使用它tput来获取终端行和列。问题是,当它作为服务运行时,它不会返回值,因为它不在终端中运行,这导致脚本失败。因此,我切换到 .tmux.conf 文件,这样我就可以调用,tmux -t .tmux.conf这样我就避免使用tput

另外,根据 ChatGPT 的建议,我现在使用用户级 systemd 单元:

[Unit]
Description=Launch Minecraft Server and Related Services
After=network.target

[Service]
Type=oneshot
ExecStart=/usr/bin/tmux -u -f /home/fpp/tmux-config/tmux.conf
RemainAfterExit=true

[Install]
WantedBy=default.target

现在的问题是 tmux 抱怨没有终端可以打开:

fpp@fpp-server:~$ systemctl --user status mcnrelated.service
× mcnrelated.service - Launch Minecraft Server and Related Services
     Loaded: loaded (/home/fpp/.config/systemd/user/mcnrelated.service; enabled; preset: enabled)
     Active: failed (Result: exit-code) since Thu 2023-09-21 11:42:09 -03; 8min ago
    Process: 1319 ExecStart=/usr/bin/tmux -u -f /home/fpp/.tmux.conf (code=exited, status=1/FAILURE)
   Main PID: 1319 (code=exited, status=1/FAILURE)
        CPU: 37ms

sep 21 11:42:09 fpp-server systemd[550]: Starting mcnrelated.service - Launch Minecraft Server and Related Services...
sep 21 11:42:09 fpp-server tmux[1319]: open terminal failed: not a terminal
sep 21 11:42:09 fpp-server systemd[550]: mcnrelated.service: Main process exited, code=exited, status=1/FAILURE
sep 21 11:42:09 fpp-server systemd[550]: mcnrelated.service: Failed with result 'exit-code'.
sep 21 11:42:09 fpp-server systemd[550]: Failed to start mcnrelated.service - Launch Minecraft Server and Related Services.

这就是我现在的情况。我试过,-u但没有成功。

至少目前来说,这个问题与 tmux 有关。一旦我可以成功启动服务,我将尝试查看它是否在启动时自动启动

相关内容