自分メモ
ssh-copy-idを使うとかんたんに公開鍵の設定ができます。
こんな感じでパスワード認証でログインできるサーバがあるとして、
$ ssh foo@192.168.33.10 foo@192.168.33.10's password: [foo@localhost ~]$
ここにローカルの公開鍵をセットするにはこうします。
$ ssh-copy-id foo@192.168.33.10 /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/hoge/.ssh/id_rsa.pub" /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys foo@192.168.33.10's password: XXXXXXXX Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'foo@192.168.33.10'" and check to make sure that only the key(s) you wanted were added.
公開鍵がセットされました。再度sshしてみましょう。
$ ssh foo@192.168.33.10 Last login: Wed Nov 24 17:24:40 2021 from 192.168.33.1 [foo@localhost ~]$
パスワードを聞かれることなく、ログインできました。公開鍵認証でログインしたためですね。
さらに、このサーバを踏み台にして別のサーバにssh-copy-idを使って場合はどうすればよいでしょうか、というのが今日のお題。
ローカル --> 踏み台(192.168.33.10, 192.168.66.10) --> サーバ(192.168.66.11)
1つ目の方法としては、.ssh/configに踏み台の設定をしておけばよいです。
Host 192.168.33.10 HostName 192.168.33.10 User foo host 192.168.66.11 hostname 192.168.66.11 user bar ProxyJump 192.168.33.10
やってみましょう。
$ ssh-copy-id 192.168.66.11 /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/foo/.ssh/id_rsa.pub" The authenticity of host '192.168.66.11 (<no hostip for proxy command>)' can't be established. ECDSA key fingerprint is SHA256:XXXXXXXXXXXXXXXXXXXXXXXX Are you sure you want to continue connecting (yes/no/[fingerprint])? yes /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys bar@192.168.66.11's password: Number of key(s) added: 1 Now try logging into the machine, with: "ssh '192.168.66.11'" and check to make sure that only the key(s) you wanted were added.
$ ssh 192.168.66.11 Last login: Wed Nov 24 18:15:23 2021 from 192.168.66.10 [bar@localhost ~]$
できました。
では、ssh/configを使得ない場合はどうすればいいか。sshの-oオプションがssh-copy-idにそのまま渡せるようですので、ProxyJumpを設定してあげればよいです。
$ ssh-copy-id -o ProxyJump=foo@192.168.33.10 bar@192.168.66.11 /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/kun432/.ssh/id_rsa.pub" /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys bar@192.168.66.11's password: Number of key(s) added: 1 Now try logging into the machine, with: "ssh -o 'ProxyJump=foo@192.168.33.10' 'bar@192.168.66.11'" and check to make sure that only the key(s) you wanted were added.
ではログインしてみましょう。sshでも-oを指定してあげればOKです。
$ ssh -o ProxyJump=foo@192.168.33.10 bar@192.168.66.11 Last login: Wed Nov 24 18:21:36 2021 from 192.168.66.10 [bar@localhost ~]$
できました。