ssh 常见配置
环境信息
- Centos 7
ssh 免密登陆
在需要免密码登陆的场景下,可以配置 ssh 密钥登陆。配置步骤如下
- 在本地服务器上面执行命令生成密钥对 以上命令生成了公私密钥对,分别存储在了
ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/testuser/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/testuser/.ssh/id_rsa.
Your public key has been saved in /home/testuser/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:Lzvl8GbOQETBVcTf8lf0Qk9KUQAESs9h8wARud+iQrk testuser@k8s-uat-master1.148962587001
The key's randomart image is:
+---[RSA 2048]----+
| .BBB*=.o+.|
| oo= =. o o|
| o.o .+ *.|
| .. = =|
| .S. . +.|
| o...+ . o|
| . .o*.. .|
| E o== |
| ..=o |
+----[SHA256]-----+/home/testuser/.ssh/id_rsa.pub
和/home/testuser/.ssh/id_rsa
中。 - 在本地服务器上面执行命令将其公钥添加到目标主机的
/home/testuser/.ssh/authorized_keys
。或者手动拷贝公钥追加到目标主机的.ssh/authorized_keys
ssh-copy-id -p 30000 testuser@172.31.30.115
/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/testuser/.ssh/id_rsa.pub"
The authenticity of host '[172.31.30.115]:30000 ([172.31.30.115]:30000)' can't be established.
ECDSA key fingerprint is SHA256:vKD5th2QpWYv/hmt+180BsENDHWNcJdKiEBOH06h/K8.
ECDSA key fingerprint is MD5:bf:8c:b9:e6:31:92:1f:a9:b6:7b:8f:50:d7:10:9e:fd.
Are you sure you want to continue connecting (yes/no)? yes
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keystestuser@172.31.30.115's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh -p '30000' 'testuser@172.31.30.115'"
and check to make sure that only the key(s) you wanted were added. - 在本地服务器上面验证可以免密登陆到目标服务器。
如果要配置双向免密,将以上步骤反过来操作一遍即可
常见配置
登录服务器,经常遇见以下提示信息,说明有主机一直在尝试暴力破解用户名密码
There were 696 failed login attempts since the last successful login. |
查看登录失败的用户名和 ip 地址
grep "Failed password for invalid user " /var/log/secure | awk '{print $11,$13}' | sort | uniq -c | sort -k1 -n |
sshd 加固配置建议
修改 sshd
配置文件 /etc/ssh/sshd_config
,更改以下配置
sshd
默认端口 22 改为其他端口- 禁止
root
用户登录,创建其他普通用户以登录系统,普通用户登录后有需要再切换到root
Port 30000 |
修改配置后重启 sshd
服务生效
systemctl restart sshd |
如果可以安全的保存秘钥,也可以使用秘钥登录,禁止用户名密码登录,具体配置可参考:ssh 秘钥登录
若使用密码登陆,建议 配置 fail2ban 防止暴力破解
常见错误
Could not load host key
docker 容器中安装 openssh-server
后,使用命令 /usr/sbin/sshd -D
启动 sshd
服务,通常会报以下错误
/usr/sbin/sshd |
执行以下命令解决:
ssh-keygen -q -t rsa -b 2048 -f /etc/ssh/ssh_host_rsa_key -N '' |
配置 ssh 公私钥免密登录后提示输入密码登陆
在使用了 ssh-copy-id root@192.168.81.12
配置免密钥登录之后,发现 ssh 到机器上还是需要密码。在目标服务器上面查看 ssh
日志
cat /var/log/secure |
看到登陆报错: Authentication refused: bad ownership or modes for file /home/testuser/.ssh/authorized_keys
,检查文件 /home/testuser/.ssh/authorized_keys
权限,看到文件权限为 -rw-rw-r--
ll /home/testuser/.ssh/ |
修改文件权限为 600
,重新登陆,可以免密码登陆。