![ssh copy keys ssh copy keys](http://www.cccreate.cn/images/donate/alipay.png)
correct permissions: in cases where the.order preserved: entries in authorized_keys retain their order.idempotent: subsequent runs given the same input will yield the same result.unique entries: no duplicate authorized_keys.To modify, replace user and with values relevant to you, and either substitute your public key in place of the $PUB_KEY variable, or define the variable in a bash script or set it as an environment variable prior to executing the command. A umask ensures the correct file permissions. The command adds the public key stored in the shell variable $PUB_KEY to the authorized_keys file of the user on the server. Modify the snippet below to suit your needs: ssh -T "umask 0077 mkdir -p ~/.ssh grep -q -F \"$PUB_KEY\" ~/.ssh/authorized_keys 2>/dev/null || echo \"$PUB_KEY\" > ~/.ssh/authorized_keys" The following is a one-liner to be run by a user that can authenticate with the remote server. When a remote host tries to authenticate, ssh works its way down the authorized_keys file until it comes across a match. However, accumulating junk in this file can create performance issues, and can make troubleshooting, auditing, and other admin tasks more difficult. Note that ssh authentication works fine when there are multiple identical authorized_keys entries. One thing I don’t like about many of the working solutions that I’ve come across is when the authorized_keys file is reordered as a side-effect. Examples are provided in bash and for ansible using ansible’s shell module (old versions) and authorized_key module (newer versions).įor shell scripts, there seem to be a lot of solutions out there for this common problem, but I think a lot of them overcomplicate things with sed, awk, uniq, and similar commands or go overboard by implementing standalone utilities for the task. This post covers a solution that adds a given key to authorized_keys only if that key isn’t already present in the file.
Ssh copy keys mac#
This command is also not bundled with MacOS, creating issues for some Mac users (though it can be installed with Homebrew). This creates a hassle for scripts and automations because subsequent runs can add duplicate key entries. Popular methods of adding an ssh public key to a remote host’s authorized_keys file include using the ssh-copy-id command, and using bash operators such as > to append to the file.Īn issue with ssh-copy-id is that this command does not check if a key already exists.