ssh 基础
ssh 用来远程登录服务器。
账号密码登录
ssh host
默认的登录用户名是本机电脑的用户名,登录端口是 22。执行后会提示输入密码。如果需要登录其他用户名或者端口使用:
# 通过端口10052,登录用户root
ssh -p 10052 root@host
密钥登录
首先通过ssh-keygen
命令生成密钥。
然后执行以下命令,将密钥拷贝到服务器上,输入密码。
ssh-copy-id user@host
成功会提示:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'user@host'"
and check to make sure that only the key(s) you wanted were added.
后续再连接就不需要输入密码了。
如果不起作用,则在远程主机上打开/etc/ssh/sshd_config
,将前方的#
去掉:
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
然后执行:
systemctl restart sshd
手动上传密钥
如果不用ssh-copy-id
,手动上传密钥(这种场景比较适合 ci,在 ci 中将公钥配置到服务器中,然后在 ci 主机上执行远程服务器脚本)。
实际上是把本地的公钥,即id_rsa.pub
的内容复制到远程服务器的~/.ssh/authorized_keys
文件内,脚本:
ssh user@host 'mkdir -p .ssh && cat >> .ssh/authorized_keys' < ~/.ssh/id_rsa.pub