[さくらVPS] ssh(鍵認証)を使って、Linuxサーバーにログインする

ssh接続を鍵認証で行うため、鍵を作成します。

【PC操作】
$ cd .ssh
$ ssh-keygen -f sakura_rsa -t rsa -b 2048
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again:


作成した鍵をサーバーにコピーします。

【PC操作】
$ ssh-copy-id -i sakura_rsa.pub littlebets@xxx.xxx.xxx.xxx


鍵認証でサーバーにログインします。

【PC操作】
$ ssh -i sakura_rsa.pub littlebets@xxx.xxx.xxx.xxx


セキュリティを強化するために、ポート番号の変更、rootユーザーのログイン禁止、パスワード認証の禁止を設定します。

【サーバー操作】
# vi /etc/ssh/sshd_config
[変更前]
Port 22
PermitRootLogin yes
PasswordAuthentication yes

[変更後]
Port 50022
PermitRootLogin no
PasswordAuthentication no 


sshを再起動します。

【サーバー操作】
# systemctl restart sshd


firewallのポート番号を変更します。

【サーバー操作】
# vi /usr/lib/firewalld/services/ssh.xml
[変更前]
<port protocol="tcp" port="22"/>
[変更後]
<port protocol="tcp" port="50022"/>


firewallの設定を有効にします。

【サーバー操作】
# firewall-cmd --reload


毎回、ユーザーIDやIPアドレス、ポート番号、鍵の名前を指定して、sshコマンドを実行するのは手間がかかります。
ssh設定ファイルを作成することで、sshコマンドのオプションを省略して、コマンドを実行できるようになります。

【PC操作】
$ vi ~/.ssh/config
Host littlebets
    HostName xxx.xxx.xxx
    User littlebtes
    IdentityFile ~/.ssh/sakura_rsa 
    Port 50022
    TCPKeepAlive yes
    IdentitiesOnly yes


sshコマンドを実行します。

【PC操作】
$ ssh littlebets