3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

公開鍵認証の鍵をリモートホストに登録するワンライナー

Last updated at Posted at 2018-06-11

(追記 6/11)
コメント欄にて@tag1216さんにご指摘いただき,ssh-copy-idというコマンドを知ったので追記.
ご指摘ありがとうございました.

追記

ssh-copy-idコマンドを使えばファイル操作で気にしないといけない諸々のことを気にせず公開鍵の登録ができるらしい.
ということで早速オプションを調べて実行してみたが,私の環境では,なんか秘密鍵がないぜ,って怒られたので少し調べた.

想定している環境

  • サーバはPubkeyAuthenticationのみ可とし,PasswordAuthenticationは無効化している
  • 既にサーバへ接続可能なクライアントが1台あって,その端末へ新規に接続させたいクライアントの公開鍵を転送し登録したい
  • (当然ながら)クライアントの秘密鍵・公開鍵はクライアント毎に異なる

調べたこと

まず,何も考えずに新規クライアントの公開鍵を旧クライアントのカレントに転送して登録を試みたところ以下のエラーが出る.

$ ssh-copy-id -i id_ed25519.pub remotehostname

/usr/bin/ssh-copy-id: ERROR: failed to open ID file './id_ed25519': No such file
        (to install the contents of 'id_ed25519.pub' anyway, look at the -f option)

-fをつければ,勿論登録できる.

$ ssh-copy-id -f -i id_ed25519.pub remotehostname
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "id_ed25519.pub"

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'remotehostname'"
and check to make sure that only the key(s) you wanted were added.

ところで,私は.ssh/configでホストへの接続設定を書いている.
これがない場合に,どう書くのかもついでにメモっておく.
代表的なものだと,会社の端末ではproxyを越えるのでProxyCommandが必要だったりする.

.ssh/config
Host remotehostname
    User        hadacchi
    HostName    ssh.remotehostname.com
    Port        11223
    ProxyCommand /usr/bin/corkscrew localproxy 11111 %h %p

この環境でコマンドラインで全部指定してみる.

オプションはほとんどsshと同じで,

  • ユーザ名,ポート番号の指定はusername@hostname -p 0000
  • -oでsshオプションの指定.中に書くオプションの記述方法も同じらしい
  • なおいちいち消すのが面倒くさいかったので,登録テストするためのdry runのオプション-nを使っている
    -nをつけると,実際には登録されないので注意
$ ssh-copy-id -f -n -i id_ed25519.pub -p 11223 -o 'ProxyCommand=/usr/bin/corkscrew localproxy 11111 %h %p' hadacchi@ssh.remotehostname.com
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "id_ed25519.pub"
=-=-=-=-=-=-=-=
Would have added the following key(s):

ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFE3JWtoBTsfq9HNkSagRcaIsAYquxPJeeeQHDOQKM34 keycomment
=-=-=-=-=-=-=-=

元の記事

この記事の方法を使えば非常に簡単に実現できる.
SSHでscpを使わずにファイルをコピーする - TIM Labs

ssh remotehostname 'cat >> .ssh/authorized_keys' < .ssh/id_ed25519.pub

今まで,scpしてsshしてcatして転送したファイルを削除するとか,無駄な手間をかけていたなぁ.

うっかりリダイレクトを間違えると悲劇的な状況になるので注意だが,それはリモートシェルにログインしても同じことだし.

3
2
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?