Skip to content

ansible批量设置ssh免密码登陆

背景

homelab通过vps来对外提供服务,不同vps提供的公网流量不同,所以会使用不同的vps来分散公网流量压力。

这些廉价vps默认通过ssh+密码登陆,看看系统日志,就可以知道,每天都会面临大量的恶意扫描。家庭数据还是比较重要的,虽然设置复杂的密码会增加安全度,但为了避免被意外爆破,这批vps都需要改成私钥登陆。这样在个人电脑上保存好私钥就好,如果私钥丢失,那么就重装vps咯。应用和数据分离,保护好数据的安全就好。

操作步骤

扫描vps的主机指纹(fingerprint)

在访问主机的时候,会验证指纹,避免因为dns污染或者IP冲突,访问到错误的主机。

scanFingerPrint.sh

echo "
你的vps IP1
你的vps IP2
" > my-hosts
ssh-keyscan -H -f my-hosts >> ~/.ssh/known_hosts

这个脚本在我本地的执行结果,大概是这样的

 ./scanFingerPrint.sh 
# vpsip:vps端口 SSH-2.0-OpenSSH_8.2p1 Ubuntu-4ubuntu0.4

安装sshpass

sudo apt install sshpass

如果没有正确安装,会报以下错误

PLAY [all] ***********************************************************************************************************************************

TASK [install ssh key] ***********************************************************************************************************************
fatal: [us1]: FAILED! => {"msg": "to use the 'ssh' connection type with passwords, you must install the sshpass program"}

PLAY RECAP ***********************************************************************************************************************************
us1                        : ok=0    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0   

测试的inventory

代码的目录结构

├── inventory
│   ├── group_vars
│   └── static
├── my-hosts
├── scanFingerPrint.sh
└── ssh-add.yml

static的内容为

[vps1]
us1 ansible_host=vps ip ansible_port=vps port ansible_user=root

ansible的playbook配置

---
- hosts: all
  gather_facts: false
  remote_user: root

  tasks:
    - name: install ssh key
      authorized_key: # `ansible-doc authorized_key`
        user: root
        key: "{{ lookup('file', '~/.ssh/vps/vps_rsa.pub') }}" # can use url, then we can put the public key online.
        state: present

验证

~/projects/ansible$ ansible-playbook -i inventory --ask-pass ssh-add.yml
SSH password: 

PLAY [all] ***********************************************************************************************************************************

TASK [install ssh key] ***********************************************************************************************************************
changed: [us1]

PLAY RECAP ***********************************************************************************************************************************
us1                        : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

验证成功后,就可以关闭vps的密码访问方式,只允许通过私钥来访问了。

Published in自建服务

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *