Linux下SSH配置密钥key登录禁用密码登录
mantou478人阅读
首先需要在ROOT用户下
操作步骤如下
1 创建用户haoduck
- useradd haoduck
2 创建haoduck用户ssh密钥文件夹
- mkdir -p /home/haoduck/.ssh/
- chmod 700 /home/haoduck/.ssh/
3 创建公钥文件
公钥文件一般从自己的电脑上生成,诸如XShell、MobaXterm等工具都是可以生成的。这里就不赘述了
- vim /home/haoduck/.ssh/authorized_keys
- chmod 600 /home/haoduck/.ssh/authorized_keys
- chown -R haoduck /home/haoduck/.ssh/ #设置文件所有者为新用户haoduck
4 配置sudo权限(可选)
在最后添加一行haoduck ALL=(ALL) ALL
或者haoduck ALL=(ALL) NOPASSWD: ALL
,后者可以免密码使用sudo
- chmod u+w /etc/sudoers
- vim /etc/sudoers
- chmod u-w /etc/sudoers
5 修改sshd配置
- vim /etc/ssh/sshd_config
密钥登录:找到以下内容去掉签名的#号
#RSAAuthentication yes
#PubkeyAuthentication yes
#AuthorizedKeysFile .ssh/authorized_keys
禁用密码和ROOT登录:
找到以下内容
PasswordAuthentication yes
PermitRootLogin yes
改为
PasswordAuthentication no
PermitRootLogin no
重启sshdsystemctl restart sshd
或systemctl restart ssh
或service sshd restart
或service ssh restart
一键脚本
- #!/bin/bash
- #username=${1:="haoduck"}
- #pubkey=${2:="ssh-xxxxx"}
- username="haoduck"
- #pubkey="$(wget -qO- https://直链)"
- pubkey="ssh-xxxxx"
- #yum install -y sudo
- #apt-get install -y sudo
- useradd ${username}
- mkdir -p /home/${username}/.ssh/
- chmod 700 /home/${username}/.ssh/
- echo $pubkey > /home/${username}/.ssh/authorized_keys
- chmod 600 /home/${username}/.ssh/authorized_keys
- chown -R ${username} /home/${username}/.ssh/
- #sudo配置
- chmod u+w /etc/sudoers
- echo "${username} ALL=(ALL) ALL" > /etc/sudoers.d/${username}
- #echo "${username} ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/${username}
- #sshd配置
- sshd_file="/etc/ssh/sshd_config"
- cp -n $sshd_file /etc/ssh/sshd_config.bak
- sed -i "s|#\?RSAAuthentication.*|RSAAuthentication yes|" $sshd_file
- sed -i "s|#\?PubkeyAuthentication.*|PubkeyAuthentication yes|" $sshd_file
- sed -i "s|#AuthorizedKeysFile .ssh/authorized_keys|AuthorizedKeysFile .ssh/authorized_keys|" $sshd_file
- #sed -i "s|#\?PasswordAuthentication.*|PasswordAuthentication no|" $sshd_file
- #sed -i "s|#\?PermitRootLogin.*|PermitRootLogin no|" $sshd_file
- systemctl restart sshd;systemctl restart ssh;service sshd restart;service ssh restart
如果只需要用ROOT用户,可以省略添加用户的步骤,一键脚本如下:
- #pubkey="$(wget -qO- https://直链)"
- pubkey="ssh-xxxxx" #这里改成你的公钥
- mkdir -p /root/.ssh/
- chmod 700 /root/.ssh/
- echo $pubkey > /root/.ssh/authorized_keys
- chmod 600 /root/.ssh/authorized_keys
- sshd_file="/etc/ssh/sshd_config"
- cp -n $sshd_file /etc/ssh/sshd_config.bak
- sed -i "s|#\?RSAAuthentication.*|RSAAuthentication yes|" $sshd_file
- sed -i "s|#\?PubkeyAuthentication.*|PubkeyAuthentication yes|" $sshd_file
- sed -i "s|#AuthorizedKeysFile .ssh/authorized_keys|AuthorizedKeysFile .ssh/authorized_keys|" $sshd_file
- sed -i "s|#\?PasswordAuthentication.*|PasswordAuthentication no|" $sshd_file
- sed -i "s|#\?PermitRootLogin.*|PermitRootLogin yes|" $sshd_file
- systemctl restart sshd;systemctl restart ssh;service sshd restart;service ssh restart
评论 | 0 条评论
登录之后才可留言,前往登录