SSH 使用指南

SSH config

file location ~/.ssh/config file template is below

bash
1Host github.com
2    HostName github.com
3    User git
4    Port 22
5    IdentityFile ~/.ssh/private_key

generate public key and private key

use command ssh-keygen

Copy public key to remote server

  1. Append the content of xxx.pub into ~/.ssh/authorized_keys file on the server-side.
  2. Change the permission of the ~/.ssh/authorized_keys file.
    bash
    1cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
    2chmod 600 ~/.ssh/authorized_keys

Disable password login on the server

  1. Edit /etc/ssh/sshd_config in server, PasswordAuthentication no.
    bash
    1PasswordAuthentication no
  2. Add this configuration PubkeyAuthentication yes in /etc/ssh/sshd_config.
    bash
    1PubkeyAuthentication yes
  3. To enable the change, restart SSH daemon with this command systemctl restart sshd.

How to prevent SSH from disconnecting if it's been idle for a while

  • 修改ssh设置
  • vim ~/.ssh/config
    bash
    1ServerAliveInterval 60

Local Port Forwarding

bash
1ssh -L [LOCAL_IP:]LOCAL_PORT:DESTINATION:DESTINATION_PORT [USER@]SSH_SERVER

参数说明:

  • [LOCAL_IP:]LOCAL_PORT - 本地 IP 和端口号,LOCAL_IP 默认是 localhost。
  • DESTINATION:DESTINATION_PORT - 目标机器的 IP 地址和端口号。
  • [USER@]SERVER_IP - 远程 SSH 地址和登录用户。

案例:

使用本地地址 127.0.0.1:58211 连接远程的数据库 1.1.1.1:58211

bash
1ssh -L 58211:1.1.1.1:58211 user@remote-server