因为又搞了一台Mac所以有了相应的需求,稍微把这点东西记下来省的每次用到都得去查。上一次的Windows篇在这里,不知不觉过去半年了,时间真是把杀猪刀。另外一些背景知识的介绍也在Windows篇里,这边就不赘述了。
I. 生成SSH钥匙对
作为基于BSD的Unix分支,macOS和Linux的亲近程度比Windows自然是高了好几条街。很多功能都已经在系统中内建,自然也就没有安装额外软件的必要了。
ssh-keygen -t rsa
会问到存贮位置,直接回车采用默认位置(~/.ssh/id_rsa)即可。之后要求键入passphrase(口令),输入并确认。直接回车可以使用空白口令,不过不推荐。
示例输出:
Your identification has been saved in /Users/myname/.ssh/id_rsa. Your public key has been saved in /Users/myname/.ssh/id_rsa.pub. The key fingerprint is: ae:89:72:0b:85:da:5a:f4:7c:1f:c2:43:fd:c6:44:38 myname@mymac.local The key's randomart image is: +--[ RSA 2048]----+ | | | . | | E . | | . . o | | o . . S . | | + + o . + | |. + o = o + | | o...o * o | |. oo.o . | +-----------------+
II. 将公钥上传至服务器
假设步骤I中密钥保存到了默认位置(~/.ssh/id_rsa),执行以下命令将对应公钥保存到剪切板:
pbcopy ~/.ssh/id_rsa.pub
公钥格式应为:
ssh-rsa AAAA ... username@host
最后一个空格后面的部分为注释内容,可以随意修改。
SSH登入服务器,使用文本编辑器打开如下文件,并在最后新起一行粘贴剪切板内的公钥:
# 为<user>添加公钥 /home/<user>/.ssh/authorized_keys # 为root添加公钥 /root/.ssh/authorized_keys
若不存在相应文件/文件夹,手动创建即可。注意权限改为700 (仅所有者有权读写):
cd ~/ mkdir .ssh chmod 0700 .ssh cd .ssh touch authorized_keys chmod 0700 authorized_keys
完成后重启ssh服务
sudo service ssh restart
重启后,本地重新ssh将会自动使用SSH钥匙对的方式登陆。具体表现形式为终端提示录入passphrase而非密码。如果没有成功可能是因为ssh默认的authorized_keys路径不同,参考下一步修改。
III. (可选)增强安全性
ssh服务的配置文件位于 /etc/ssh/sshd_config 使用sudo权限打开文本编辑器进行编辑。
# 确认启用pubkey方式远程访问
PubkeyAuthentication yes
# authorized_keys路径,上一步如果失败修改为以下值
AuthorizedKeysFile %h/.ssh/authorized_keys
# 禁用用户名-密码方式登陆
PasswordAuthentication no
# 为特定用户禁用用户名-密码登陆,注意Match命令需要另一条Match来终结,否者作用到EOF
Match User user1,user2,user3,user4
PasswordAuthentication no
# 禁用root的远程登录
PermitRootLogin no
参考
- https://docs.joyent.com/public-cloud/getting-started/ssh-keys/generating-an-ssh-key-manually/manually-generating-your-ssh-key-in-mac-os-x
- https://serverfault.com/questions/312500/how-do-i-configure-sshd-on-debian-to-use-public-key-authentication
- https://serverfault.com/questions/285800/how-to-disable-ssh-login-with-password-for-some-users
- https://askubuntu.com/questions/27559/how-do-i-disable-remote-ssh-login-as-root-from-a-server
2 条评论
Sunny · 03/18/2018 上午5:26
非常好用!
Canmipai · 03/22/2018 上午12:23
哈哈哈好用233 刚才手贱升级服务器的Debian,结果数据库被autoremove了