ubuntu开机自动以普通用户启用一个程序

要在 Ubuntu 22.04 启动时自动以普通用户启动一个 Shell,你可以使用以下步骤:

### 方法 1: 使用 `.bashrc` 或 `.profile`
1. **编辑 `.bashrc` 或 `.profile` 文件**  
   如果你希望在用户登录终端后自动启动一个自定义的 shell 或命令,可以在用户的主目录下编辑 `.bashrc` 或 `.profile` 文件。
   
   ```bash
   nano ~/.bashrc
   ```
   或者:
   ```bash
   nano ~/.profile
   ```

2. **添加命令**  
   在文件的末尾,添加你希望自动执行的 Shell 命令。例如,启动一个特定的 Shell(如 zsh)或执行脚本:

   ```bash
   /bin/zsh
   ```

   或执行某个脚本:

   ```bash
   /path/to/your/script.sh
   ```

3. **保存并退出**  
   按 `Ctrl + O` 保存文件,`Ctrl + X` 退出编辑器。

4. **重启终端**  
   重新打开终端,新的 Shell 或命令就会自动运行。

### 方法 2: 使用 `systemd` 用户服务
1. **创建 systemd 用户服务**  
   你可以通过 systemd 创建一个用户级别的服务,自动执行 Shell。

   创建一个新的 systemd 服务文件:

   ```bash
   nano ~/.config/systemd/user/start-shell.service
   ```

2. **添加服务配置**  
   在文件中添加以下内容,将 `UserShellCommand` 替换为你要启动的 shell 或脚本路径:

   ```ini
   [Unit]
   Description=Start a shell on login

   [Service]
   ExecStart=/bin/bash -c "UserShellCommand"
   StandardInput=tty-fail

   [Install]
   WantedBy=default.target
   ```

3. **启用并启动服务**  
   保存文件后,启用并启动服务:

   ```bash
   systemctl --user enable start-shell.service
   systemctl --user start start-shell.service
   ```

4. **检查状态**  
   确认服务是否已启动:

   ```bash
   systemctl --user status start-shell.service
   ```

这样,在每次用户登录时,systemd 将自动启动指定的 Shell 或脚本。

### 方法 3: 在 `/etc/rc.local` 中添加命令
1. **创建或编辑 `/etc/rc.local` 文件**  
   该文件可以用于在系统启动时执行脚本或命令。

   ```bash
   sudo nano /etc/rc.local
   ```

2. **添加命令**  
   在文件中,添加你要执行的 Shell 或脚本路径,确保在文件末尾添加 `exit 0`:

   ```bash
   su - username -c "/bin/bash"
   exit 0
   ```

3. **设置可执行权限**  
   确保文件具有可执行权限:

   ```bash
   sudo chmod +x /etc/rc.local
   ```

4. **重启系统**  
   重启系统后,Shell 或脚本将自动以普通用户启动。

这几种方法可以根据你的需求选择适合的方式。

猜你喜欢

转载自blog.csdn.net/qqk808/article/details/143279544