如何在Laravel Forge中以root用户登录?附配方执行用户说明
Yep, Laravel Forge disables direct root SSH access by default for security reasons—so your "Permission denied (publickey)" error makes total sense. Here are a few reliable ways to get root access, depending on what you need:
1. Switch to Root from the Forge User (Recommended)
This is the safest and most straightforward method since it keeps direct root access disabled:
- First, log into your server normally using the forge user:
ssh forge@your-server-ip - Once logged in, switch to the root user with one of these commands:
Forge typically configures the# Option 1: Switch to root with a full environment sudo su - # Option 2: Shortcut to get a root shell (works if Forge set up passwordless sudo for forge) sudo -iforgeuser to have passwordless sudo access, so you might not even need to enter a password here. If you do, use the server password you set up in Forge when creating the server.
2. Enable Direct Root SSH Access (Not Recommended)
Only do this if you absolutely need direct root login, as it increases security risks. Here's how:
- Log in as the forge user first, then edit the SSH daemon config:
sudo nano /etc/ssh/sshd_config - Find the line starting with
PermitRootLoginand change it to:
If you want to use SSH keys instead of a password (safer than password login), set it toPermitRootLogin yesPermitRootLogin prohibit-passwordinstead. - Save the file (Ctrl+O, then Enter in nano) and exit (Ctrl+X).
- Restart the SSH service to apply changes:
sudo systemctl restart sshd - If you're using password login, set a root password:
sudo passwd root - Now you can log in directly with
ssh root@your-server-ip. Remember to revert thePermitRootLoginsetting back tonoonce you're done to keep your server secure.
3. Run Root Commands via Forge Recipes (No Login Needed)
Since you mentioned Forge lets you choose the execution user for recipes, you don't even need to log in as root to run root-level tasks:
- When creating or editing a recipe in Forge, look for the "Run As" dropdown menu and select
rootas the user. - Any commands in that recipe will execute with root privileges automatically, so you can handle tasks that require root access without ever logging into the server as root.
Important Note
Sticking with the first method (switching from forge to root) is always the best practice for security. Direct root SSH access is a common attack vector, so avoid enabling it unless you have a specific, temporary need.
内容的提问来源于stack exchange,提问作者Fredrik

