見出し画像

公開鍵認証によりパスワード無しでSSH接続する

複数のサーバにSSH接続する機会が多いとサーバ毎にパスワードを入力するのは面倒です。
中にはセキュリティの観点からSSH接続のパスワードログインを禁止しているサーバも存在します。
そこで、公開鍵認証によりパスワード無しでSSH接続してみます。


キーペアの作成

クライアントPCでssh-keygenコマンドにより公開鍵と秘密鍵のペア(キーペア)を作成します。

  • Enter file in which to save the key (/Users/roboworks/.ssh/id_rsa):
    キーペアの保存先を聞かれます。何も指定せずにenterキーを押せばデフォルトの場所に保存されます。

  • Enter passphrase (empty for no passphrase):
    何も入力せずにenterキーを押せばパスワードなしでSSH接続が可能になります。

ユーザ名@クライアントPC: ~$ ssh-keygen -t rsa -b 4096
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/roboworks/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /Users/roboworks/.ssh/id_rsa
Your public key has been saved in /Users/roboworks/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:8T1nJ2yDVqUG+aryRKWF6bUzsZoJH3hsIfcQ07XH1Vk roboworks@okadahiroyukinoMacBook-Pro.local
The key's randomart image is:
+---[RSA 4096]----+
|          o..o. E|
|           =o. *o|
|        o * =.= o|
|         O X O.. |
|        S X @.B .|
|         * *.B + |
|          *.     |
|        ...      |
|         o.      |
+----[SHA256]-----+

公開鍵を接続先(サーバーPC)にコピー

ssh-copy-idコマンドで公開鍵をクライアントPCからサーバPCにコピーします。
途中でサーバPCへのログインパスワードを聞かれるので入力します。

ユーザ名@クライアントPC: ~$ ssh-copy-id  ユーザ名@サーバPC
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/roboworks/.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
ユーザ名@サーバPC's password: 

Number of key(s) added:        1

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

動作確認

下記の通り、SSH接続にパスワードが必要無くなります。

ユーザ名@クライアントPC: ~$ ssh  ユーザ名@サーバPC
Welcome to Ubuntu 22.04.3 LTS (GNU/Linux 6.2.0-39-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

Expanded Security Maintenance for Applications is not enabled.

0のアップデートはすぐに適用されます。

34 additional security updates can be applied with ESM Apps.
Learn more about enabling ESM Apps service at https://ubuntu.com/esm

Last login: Tue Dec 26 08:46:32 2023 from fe80::1c69:ac76:631e:9517%wlp0s20f3
ユーザ名@サーバPC:~$ 

この記事が気に入ったらサポートをしてみませんか?