When I try to sudo ssh ... I get permission denied because ssh looks in /root/.ssh for the keys, not in /home/me/.ssh. But $HOME is still set to /home/me. Why doesn't ssh look in $HOME/.ssh?

  • Why would you sudo the ssh at all?
    – Kusalananda
    Sep 19, 2018 at 15:20
  • I'm actually doing sudo git but it uses ssh.
    – Timmmm
    Sep 19, 2018 at 15:21
  • 1
    There seems to be something odd in your workflow if you require the root user to own a Git repository... There may obviously be something involved that I don't know about, but a Git repository is unlikely to ever require to be owned by root.
    – Kusalananda
    Sep 19, 2018 at 15:50
  • "But $HOME is still set to /home/me" -- are you sure? By default sudo resets all environment variables, except a few like TERM, USER and HOME, which it sets according to the new user.
    – ilkkachu
    Sep 19, 2018 at 16:27
  • It is an unusual thing to do, I agree. It's because I am running a benchmark as root (so I can use cpuset and reduce the runtime variance) and the benchmark script includes downloading and compiling a program. Theoretically I could make that bit run as non-root but it would significantly complicate things.
    – Timmmm
    Sep 19, 2018 at 17:33

2 Answers 2


ssh ignores $HOME, it gets the home directory from the user database based on the real¹ uid (using the pw_dir field of the structure returned by getpwuid()).

Given that ssh could write files in there like the known_hosts one, it's just as well that it does not do is in /home/me/.ssh as you'd end up with a root-owned file there.

You can always use sudo ssh -i ~/.ssh/id_rsa ..., or use an authentication agent and make sure you pass the path of the socket to that authentication agent to root:

sudo --preserve-env=SSH_AUTH_SOCK ssh ...



Also, are you sure you need to run ssh as root? Is it to be able to create tunnels or bind local port-forwards on TCP ports below 1024? If it's just to be able to login as root on the remote host, doing ssh root@host should be enough.

¹ you could actually restore the real uid to our original one while preserving the effective uid of 0:

sudo perl -e '$<=getpwnam($ENV{SUDO_USER}); exec@ARGV' ssh ...

While sudo allows you to "execute a command as another user" (man sudo), if missing, it will use "the default target user (usually root)". That's why it will look for the root account on the remote side.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .