公開鍵ファイル作成

$ ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
Enter file in which to save the key (/home/you/.ssh/id_rsa): (そのままエンターを押す)
Enter passphrase (empty for no passphrase): (パスフレーズを入力)
Enter same passphrase again: (パスフレーズ確認)

公開鍵ファイルを配置

# su user1
$ cd ~
$ mkdir ~/.ssh
$ chmod 700 ~/.ssh
$ vi ~/.ssh/authorized_keys (公開鍵ファイルの内容を書き込み)
$ chmod 644 ~/.ssh/authorized_keys
$ restorecon -Rv ~/.ssh/

sshd_config

  • /etc/ssh/sshd_config (抜粋)
    #Port 22
    Port 20022 (ポートスキャン対策, 既定から適当な未使用のポートへ変更)
    
    #PermitRootLogin yes
    PermitRootLogin no
    
    #PasswordAuthentication yes
    #PermitEmptyPasswords no
    PasswordAuthentication no
    PermitEmptyPasswords no
  • sshd を再起動した後、別ターミナルでログイン確認。
    root でログインしているターミナルを終了すると、設定に問題があった場合、修正できなくなるため。
    • CentOS7
      # systemctl restart sshd
    • CentOS6
      # service sshd restart

firewalld

  • /etc/firewalld/services/ssh-port.xml
    <?xml version="1.0" encoding="utf-8"?>
    <service>
      <short>SSH</short>
        <description>Secure Shell (SSH) is a protocol for logging into and executing commands on remote machines. It provides secure encrypted communications. If you plan on accessing your machine remotely via SSH over a firewalled interface, enable this option. You need the openssh-server package installed for this option to be useful.</description>
      <port protocol="tcp" port="20022"/>
    </service>
  • 許可サービス追加
    # firewall-cmd --permanent --add-service=ssh-port
    # systemctl stop firewalld
    # systemctl start firewalld

ポートフォワード

  • Windows クライアントのローカルポートに対するアクセスを Linux サーバのリモートポートへ転送する。
  • Win32-OpenSSH のインストール (Chocolatey)
    > cinst -y openssh
  • 設定ファイル %UserProfile%/.ssh/config
    host Host1
      user user1
      hostname host1.domain1
      port 20022
      identityfile ~/.ssh/id_rsa.user1
      LocalForward 5901 host1.domain1:5900
    
    host Host2
      user user2
      hostname host2.domain2
      port 22
      identityfile ~/.ssh/id_rsa.user2
      LocalForward 5902 host2.domain2:5900
  • 接続 (PowerShell 上から)
    > ssh -F "C:\Users\user1\.ssh\config" Host1
  • 切断
$ exit