LoginSignup
1
1

CentOSでSSH公開鍵認証設定した際の作業メモ

Last updated at Posted at 2024-05-29

はじめに

概要

ユーザー(ユーザー名:ssh)を作成し、公開鍵認証でSSH接続できるように設定を行う。

環境などなど

  • クライアント
    • OS:Windows11
    • SSHキーの配置場所
      • 秘密鍵ファイル:C:\work\.ssh\id_rsa
      • 公開鍵ファイル:C:\work\.ssh\id_rsa.pub
  • サーバ
    • OS:CentOS 7.9
    • ホスト名:CentOS
    • SSH公開鍵の配置場所
      • 公開鍵ファイル:/home/ssh/.ssh/authorized_keys

サーバ側の作業

rootユーザーの作業

sshユーザーの作成

[root@CentOS ~]# useradd -m -d /home/ssh ssh

sshユーザーのパスワード設定

[root@CentOS ~]# passwd ssh
Changing password for user ssh.
New password: **********
Retype new password: **********
passwd: all authentication tokens updated successfully.
[root@CentOS ~]# 

SSH接続設定の変更

[root@CentOS ~]# vi /etc/ssh/sshd_config


#空パスワードのユーザーのログインを禁止
#PermitEmptyPasswords no
PermitEmptyPasswords no

#公開鍵認証を許可する
#PubkeyAuthentication yes
PubkeyAuthentication yes


[root@CentOS ~]# 

SSHサービスの再起動

[root@CentOS ~]# systemctl restart sshd.service

sshユーザーの作業

フォルダ「.ssh」の作成

[ssh@CentOS ~]$ mkdir /home/ssh/.ssh

フォルダ「.ssh」の権限設定

[ssh@CentOS .ssh]$ chmod 700 /home/ssh/.ssh

フォルダ「.ssh」の権限確認

[ssh@CentOS ~]$ ls -ld /home/ssh/.ssh
drwx------. 2 ssh ssh 47 May 29 17:56 /home/ssh/.ssh
[ssh@CentOS ~]$ 

クライアント側の作業

PowerShell

定義

$dirPath            = "C:\work\.ssh";
$privateKeyFileName = "id_rsa";
$publicKeyFileName  = "id_rsa.pub";
$privateKeyFilePath = Join-Path -Path "$($dirPath)" -ChildPath "$($privateKeyFileName)";
$publicKeyFilePath  = Join-Path -Path "$($dirPath)" -ChildPath "$($publicKeyFileName)";

フォルダ作成

New-Item `
  -Path "$($dirPath)" `
  -ItemType Directory `
  -ErrorAction SilentlyContinue;

SSHキー(秘密鍵/公開鍵)の生成

ssh-keygen `
  -t rsa `
  -b 2048 `
  -q `
  -N '""' `
  -C "${env:USERNAME}@${env:COMPUTERNAME}" `
  -f "$($privateKeyFilePath)";

SSHキー(公開鍵)の配置

サーバーの以下の場所に配置する。
配置元ファイル:C:\work\.ssh\id_rsa.pub
配置先ファイル:/home/ssh/.ssh/authorized_keys

サーバ側の作業

sshユーザーの作業

ファイル「authorized_keys」の権限設定

[ssh@CentOS .ssh]$ chmod 600 /home/ssh/.ssh/authorized_keys

ファイル「authorized_keys」の権限確認

[ssh@CentOS ~]$ ls -l /home/ssh/.ssh/authorized_keys
-rw------- 1 ssh ssh 738 May 17 13:51 /home/ssh/.ssh/authorized_keys
[ssh@CentOS ~]$ 

クライアント側の作業

PowerShell

公開鍵認証での接続確認

ssh -i "$($privateKeyFilePath)" ssh@CentOS

サーバ側の作業

rootユーザーの作業

SSH接続設定の変更

[root@CentOS ~]# vi /etc/ssh/sshd_config


#rootユーザーのログイン禁止
#PermitRootLogin yes
PermitRootLogin no

#パスワード認証を無効にする
#PasswordAuthentication yes
PasswordAuthentication no


[root@CentOS ~]# 

SSHサービスの再起動

[root@CentOS ~]# systemctl restart sshd.service
1
1
0

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
1
1