-1

I have this command

cat ~/.ssh/id_dsa.pub | ssh root@[my_server] "cat >> ~/.ssh/authorized_keys" 

How can I do the same thing but with sudo -iu user1 before the 2nd cat? That is, I want to change a user after having been logged in.

1
  • 2
    This might help: man ssh-copy-id.
    – Cyrus
    CommentedMay 23, 2022 at 21:09

2 Answers 2

1

If you don't mind getting the key on the screen as well (it is the public key, so this is not much of a security issue), you should be able to use tee to avoid redirection troubles along the lines of

cat ~/.ssh/id_dsa.pub \ | ssh root@server 'sudo -i -u user1 tee -a ~user1/.ssh/authorized_keys' 
2
  • 1
    End the remote tee command with >/dev/null and you don't get the key written to stdoutCommentedMay 24, 2022 at 6:41
  • @roaima ... or the pipeline, if you're ok with transferring the data to the local host just to throw it away. Also, the cat could be replaced by an input redirection.
    – Kusalananda
    CommentedMay 24, 2022 at 6:57
0

Try this:

cat ~/.ssh/id_dsa.pub | ssh root@[my_server] $'sudo -i -u user1 bash -c "cat - >> ~/.ssh/authorized_keys"' 
3
  • 1
    what's the $ for?
    – Johsua
    CommentedMay 23, 2022 at 21:13
  • 1
    @Johsua It would interpret the string following as a "C string" and replace any \n or \t etc. with literal newline or tab characters. However, in this instance, it would make absolutely no difference, so you may remove the $.
    – Kusalananda
    CommentedMay 23, 2022 at 21:28
  • 1
    You could avoid the bash -c by using sudo -u user1 tee -a ~user1/.ssh/authorized_keys >/dev/null. Note that the cat is then also not needed.
    – Kusalananda
    CommentedMay 23, 2022 at 21:30

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.