logo NodeSeekbeta

服务器上使用 ssh 密钥登录

前言:

SSH 密钥是一种更安全的登录SSH 服务器的方法,因为它们不易受到常见的暴力密码黑客攻击

尽管SSH 支持基于密码的身份验证,但通常建议使用SSH 密钥

生成SSH 密钥对会创建两个长字符串:公钥和私钥

可以将公钥放在任何服务器上,然后使用可以访问私钥的SSH 客户端连接到服务器

服务器上使用 ssh 密钥登录

本地客户端生成密钥对

使用下面命令生成密钥对:

ssh-keygen -t rsa -P

-P 表示空密码,一路回车,在 .ssh 目录会生成下面三个文件

cd ~/.ssh && ls

id_rsa id_rsa.pub known_hosts

id_rsa: 表示私钥,不要泄露
id_rsa.pub: 表示公钥

查看公钥内容,然后复制下来或者将两个文件下载下来:

cat ~/.ssh/id_rsa.pub

上面客户端完成,开始折腾服务端

服务端新建authorized_keys

root目录下新建 .ssh 文件夹

mkdir /root/.ssh

.ssh 文件夹新建 authorized_keys 文件

vi /root/.ssh/authorized_keys

上面添加客户端复制下来的 id_rsa.pub 内容,保存。

修改 sshd_config 内容

vi /etc/ssh/sshd_config

禁用密码登陆

PasswordAuthentication no

允许root用户登录

PermitRootLogin yes

指定公钥数据库文件

AuthorsizedKeysFile .ssh/authorized_keys

以启用密钥登陆

PubkeyAuthentication yes

防ssh断开

ClientAliveInterval 60
ClientAliveCountMax 30

最后重启 sshd 服务:

systemctl restart sshd

然后你就可以用 ssh 命令无密码登录服务器了

12
  • 可以的

  • 好贴 顶你上去

  • 生成密钥对之后用我的一键脚本

    #!/bin/bash
    
    # 将ssh公钥复制到vps,并关闭密码登录
    
    # 如果非root登录则退出
    
    if [ "$UID" -ne 0 ]; then
        echo "必须以root用户执行此脚本"
        exit
    fi
    
    public_key='这里填写你的公钥'
    
    # 添加公钥
    # 有authorized_keys文件,没有公钥才添加
    # 没有authorized_keys文件,创建并添加
    
    if [ -e /root/.ssh/authorized_keys ]; then
        result=$(cat /root/.ssh/authorized_keys | grep "${public_key:8:20}")
        if [ "$result" != "" ]; then
            echo "已有此公钥"
        else
            echo $public_key >> /root/.ssh/authorized_keys
        fi
    else
        mkdir /root/.ssh
        touch /root/.ssh/authorized_keys
        echo $public_key >> /root/.ssh/authorized_keys
    fi
    
    # 修改ssh配置文件
    
    sed -e '/PubkeyAuthentication/cPubkeyAuthentication yes' \
        -e '#AuthorizedKeysFile#cAuthorizedKeysFile .ssh/authorized_keys' \
        -e '/PermitRootLogin/cPermitRootLogin yes' \
        -e '/PasswordAuthentication/cPasswordAuthentication no' \
        -i /etc/ssh/sshd_config
    
    result=$(cat /etc/ssh/sshd_config | grep "RSAAuthentication yes")
    
    if [ "$result" = "" ]; then
        echo "RSAAuthentication yes" >> /etc/ssh/sshd_config
    fi
    
    service sshd restart
    
  • @Unfocused2432 #3 你这太刺眼了

  • 担心文件权限搞不定的可以用ssh-copy-id进一步简化操作

  • 这个不错 收藏了

  • xhj007

  • @斯巴达 #4

    本地客户端生成密钥对,这个是在哪里操作?是在本地电脑上吗?

  • @iamfly #9 就你服务器上输入命令它会自动生成密钥对的,你将密钥对保存在本地电脑上就行

12

你好啊,陌生人!

我的朋友,看起来你是新来的,如果想参与到讨论中,点击下面的按钮!

📈用户数目📈

目前论坛共有61579位seeker

🎉欢迎新用户🎉