How to SSH Directly Into a sudo Shell Without Getting Stuck
How to SSH Directly Into a sudo Shell Without Getting Stuck
When working with Linux servers, it's common to log in with an administrative user (not root) and then elevate privileges with sudo. But sometimes we want to SSH directly into a root-like shell without typing sudo every time.
At first glance, you might think something like this works:
Unfortunately, it doesn’t behave as expected. Instead of dropping you into an interactive shell, the session hangs or immediately exits. Why? Let’s break it down.
Why ssh admin@host "sudo -i" Fails
By default, SSH does not allocate a pseudo-terminal (PTY) when executing a remote command.
-
sudo -i(orsudo su -) launches an interactive login shell. -
Without a PTY,
sudohas nowhere to attach its interactive session. -
Result: you either get stuck waiting for input or the session terminates right away.
If you enable debug output (ssh -v), you might see something like this:
Notice how it falls back to asking for a password even though a key is available. And once authenticated, the session just hangs because there’s no TTY for sudo to run its shell.
The Fix: Use -t to Force a Pseudo-Terminal
The solution is to explicitly request a PTY with SSH’s -t option:
Now SSH creates a terminal on the remote side, allowing sudo to start a full interactive login shell.
You can run commands, navigate the system, and everything behaves just like if you had logged in normally and typed sudo -i.
A Subtle Gotcha: Argument Order & Aliases
In my case, I had defined an alias for SSH in my shell config:
Unfortunately, I forgot to include the -t flag inside this alias. So when I typed:
it was silently expanding into a command without -t. That’s why it still failed even after I thought I was using the correct syntax.
The fix was simple:
-
Update the alias definition to include
-tif needed, or -
Skip the alias and explicitly run:
Also, remember to reload your shell after editing aliases:
Otherwise, you’re still running the old alias definition.
sudo -i vs sudo su -
Both achieve a similar result: starting a root login shell.
-
sudo -ifollows the target user’s login sequence, simulating a fresh login. -
sudo su -switches user and spawns a login shell, but technically usessu.
In practice, both work fine with ssh -t.
Pro Tip: Create a Shortcut
If you find yourself doing this often, define a dedicated alias:
Now you can log in directly as root (via sudo) with a single command:
Conclusion
The key takeaway:
-
Always use
ssh -twhen you want an interactivesudoshell. -
Be careful with shell aliases — they can override or drop required options.
-
Don’t forget to reload your shell after making changes.
With these tweaks, you’ll avoid getting stuck in half-open sessions and can SSH smoothly into elevated shells.
Comments
Post a Comment