Linux 使用私钥登录

  1. 生成ssh公钥密钥对:参考
root@0aedf4c047f8:~/.ssh# ssh-keygen -t rsa
生成ssh公钥密钥对

2. 进入/root/.ssh目录下, 将公钥复制到 authorized_keys 文件。

# cat id_rsa.pub >> authorized_keys
# chmod 600 authorized_keys

3. 下载私钥 id_rsa,这样,便可以通过私钥来免密登录服务器了!

现在可以在本地 docker 起一台ubuntu 虚拟机

## 安装一下 openssh-client
apt-get update -y && apt-get install openssh-client -y

##
## Run ssh-agent
##
eval $(ssh-agent -s)

# 将 私钥 id_rsa 文件同步到 docker 容器里的 /tmp 目录
# 然后 赋值 给 SSH_PRIVATE_KEY
SSH_PRIVATE_KEY="$(cat /tmp/rsa_key)"


##
## 把私钥添加到ssh-agent的高速缓存中
## We're using tr to fix line endings which makes ed25519 keys work
## without extra base64 encoding.
## https://gitlab.com/gitlab-examples/ssh-private-key/issues/1#note_48526556
##
echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null

##
## 创建 SSH 目录,赋予正确的权限
##
- mkdir -p ~/.ssh
- chmod 700 ~/.ssh

##
## Use ssh-keyscan to scan the keys of your private server. Replace gitlab.com
## with your own domain name. You can copy and repeat that command if you have
## more than one server to connect to.
##
- ssh-keyscan gitlab.com >> ~/.ssh/known_hosts
- chmod 644 ~/.ssh/known_hosts

# 登陆您的服务器
ssh -vvv root@test.domain.com