6

I used in my bash script the follwing cli , in order to send the public key to remote machine

sshpass -p $pass scp  /root/.ssh/authorized_keys root@$remote_host:~/.ssh/authorized_keys

but since we want to append the public keyes from other host then I am searching the approach top append

in bash I know that the option is to use ">>" but how to use the append with my approach ?

or maybe other solution ?

39

You can also use ssh-copy-id, which is a tool to do exactly what you want: add one or more keys to the authorized_keys of a remote system.

4
  • 2
    Usually a good idea (and should be preferred!), but in this case it won't work without additional effort as the source is another authorized_keys file.
    – pLumo
    Nov 3 '20 at 15:15
  • 2
    @pLumo Additional effort just being that ssh-copy-id requires the key filename to end with .pub: ln -s authorized_keys ~/.ssh/authorized_keys.pub; ssh-copy-id -i ~/.ssh/authorized_keys.pub $remote_host
    – JoL
    Nov 3 '20 at 23:26
  • @JoL Is a file with several keys in it a valid pub file? Nov 5 '20 at 23:14
  • @AndrewSavinykh I tested it. It works and the manual ssh-copy-id(1) says (emphasis mine) "-i identity_file Use only the key(s) contained in identify_file...", so acceptance of multiple keys in a single file seems intentional.
    – JoL
    Nov 6 '20 at 0:00
12

Use ssh together with tee -a file:

< /root/.ssh/authorized_keys sshpass -p "$pass" ssh root@"$remote_host" "tee -a ~/.ssh/authorized_keys"

or ssh with cat >> file if you prefer:

< /root/.ssh/authorized_keys sshpass -p "$pass" ssh root@"$remote_host" "cat >> ~/.ssh/authorized_keys"

Both tee and cat will read from stdin, which is sent to ssh with < file.
The difference is, that tee, unlike >> will print what it appends.

Note: The double quotes are needed, otherwise the >> or ~ will be interpreted by your shell before sending it to ssh command.

8
  • not clearly how yo append the file - authorized_keys , if you only doing sshpass -p "$pass" ssh root@"$remote_host" "tee -a ~/.ssh/authorized_keys"
    – user436442
    Nov 3 '20 at 15:19
  • sshpass -p "$pass" ssh root@"$remote_host" "tee -a ~/.ssh/authorized_keys" , this isnt works , still not understand from where its take the source /root/.ssh/authorized_keys
    – user436442
    Nov 3 '20 at 15:22
  • 2
    you're missing the < /root/.ssh/authorized_keys part, that is the source. It sends the content of the file to stdin of ssh command. and tee or cat reads that.
    – pLumo
    Nov 3 '20 at 15:23
  • I have another little issue , I replaced the ssh with --> /usr/bin/ssh -n -o ConnectTimeout=40 -o StrictHostKeyChecking=no -xaq but this isnt works , can you advice about this?
    – user436442
    Nov 3 '20 at 15:48
  • 2
    i guess it should work if you remove -n.
    – pLumo
    Nov 3 '20 at 15:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy