さくらVPS Cent OS7.7 にSSH公開鍵認証設定した


さくらVPSにCent OS7.7をインストールしてまっさらな状態からスタート。

パッケージを最新に

yum -y update

sshでログインしてユーザー追加とパスワード設定

ssh [email protected]
adduser hogehoge
passwd hogehoge

権限を変更

cd ../
chmod 700 hogehoge

Macで鍵を作る

mkdir .ssh
cd .ssh
ssh-keygen -t rsa
Enter file in which to save the key (/Users/aya/.ssh/id_rsa): hogehoge #任意の鍵の名前
Enter passphrase (empty for no passphrase):
Enter same passphrase again:

パスフレーズも任意だけど、忘れないように。
これで「hogehoge_rsa」と「hogehoge_rsa.pub」という2つのファイルができた。

鍵をサーバーに送って配置する

scp hogehoge.pub [email protected]:~
ssh [email protected]
ls
#hogehoge_rsa.pub が存在する事を確認。
mkdir .ssh
chmod 700 .ssh
mv hogehoge_rsa.pub .ssh/authorized_keys
chmod 600 .ssh/authorized_keys

sshd_configの編集

su
vi /etc/ssh/sshd_config
#Port 22
↓
Port xxxx

ポート番号は1024以上、49513~65535が望ましい。今回は「49513」を使う。

rootでログインできないようにする

#PermitRootLogin yes
↓
PermitRootLogin no

公開鍵認証設定。

#PubkeyAuthentication yes
↓
PubkeyAuthentication yes

パスワードによるログイン不可にする

PasswordAuthentication yes
↓
PasswordAuthentication no

ここまで変えたら保存する。

sshdの再起動

systemctl restart sshd.service

ファイアウォールの設定

ポートを書き換える

vi /usr/lib/firewalld/services/ssh.xml
port protocol="tcp" port="22"/ の「22」を「49513」に書き換える。

ファイアウォール再起動

systemctl reload firewalld.service

SSH接続できるか確認

ssh [email protected] -i ~/.ssh/hogehoge_rsa -p 49513

mac側で鍵の設定

vi ~/.ssh/config
Host ops
    Hostname xxx.xxx.xxx.xxx
    User hogehoge
    Port 49513
    IdentityFile ~/.ssh/hogehoge_rsa
    IdentitiesOnly yes

接続できるか確認

ssh hogehoge

こちらの記事を参考にしました。
https://qiita.com/sugasaki/items/a297f0404bd5fe0d818a