Skip to content

ssh

提交代码时无需手动输入用户名密码,直接提交到远程仓库,简化代码提交,查看时是否已经生成 SSH Key

sh
$ ls ~/.ssh
id_rsa      id_rsa.pub      known_hosts

如果已经生成 id_rsa ,id_rsa.pub, known_hosts 则可以直接使用,如果没有则使用命令 ssh-keygen 可以生成配对的 id_rsa 与 id_rsa.pub 文件

sh
ssh-keygen -t rsa -C "your.email@example.com" -b 4096

复制生成的公钥到粘贴板

sh
# Git Bash on Windows / Windows PowerShell
cat ~/.ssh/id_rsa.pub | clip

# macOS
pbcopy < ~/.ssh/id_rsa.pub

# Linux
xclip -sel clip < ~/.ssh/id_rsa.pub

# Windows
type %userprofile%\.ssh\id_rsa.pub | clip

检查是否连接到正确的服务器

sh
$ ssh -vT git@github.com

配置 OpenSSH 服务允许使用 RSA-SHA1key

在 ~/.ssh/config 加上如下配置

Host gitee.com
  HostkeyAlgorithms +ssh-rsa
  PubkeyAcceptedAlgorithms +ssh-rsa

密码登录

sh
$ ssh root@47.113.95.50

以 root 身份登录 47.113.95.50 服务器

为了更大保障服务器的安全性,这里禁止密码登录。修改云服务器的 /etc/ssh/sshd_config 配置文件。其中 PasswordAuthentication 设置为 no,以此来禁用密码登录。

sh
PasswordAuthentication no

快速登录

在本地客户端环境 (个人电脑) 上配置 ~/.ssh/config,对个人服务器起别名,可以更方便地登录云服务器。

Host aliyun
  HostName 47.113.95.50
  User root

配置成功之后直接使用别名登录 ssh <HostName>

sh
ssh aliyun

免密登录

每次输入密码也是足够麻烦的。那如何实现远程服务器的免密登录?

sh
# 在本地环境进行操作

# 提示你输入密码,成功之后可以直接 ssh 登录,无需密码
ssh-copy-id aliyun

ssh-copy-id 即把自己本地 ~/.ssh/id_rsa.pub 公钥复制到远程服务器的 ~/.ssh/authorized_keys 上。

sh
# 登陆成功,无需密码
$ ssh aliyun

保持连接

~/.ssh/config 添加以下配置

Host *
  ServerAliveInterval 60

我介绍个通用的方法吧, 可以让不同的服务器用不同的ssh文件登陆

ssh-keygen -f xxx 生成指定的文件名xxx ssh-copy-id -i xxx.pub HOST 把公钥文件拷贝到指定的服务器 在.ssh/config 配置文件下中加个密钥文件的定义

HOST w231
    HostName 192.168.1.231
    IdentityFile ~/.ssh/xxx