使用Ansible通过ssh批量读取和修改Client设备
1. 安装ansible工具
apt-get install ansible
2. 添加需要访问的client信息
ansible配置文件如下
/etc/ansible/ansible.cfg
/etc/ansible/hosts
首先放开ansible.cfg中指定的hosts路径,然后编辑hosts如下:
[client] x.x.x.x ansible_ssh_user="user_name" ansible_ssh_pass="user_pwd" ansible_ssh_port=22
3. 安装sshpass
apt-get install sshpass
4. 执行命令
ansible client -m command -a "ls /root"
5. 用python在IP后添加ssh自动验证
#_*_coding:utf-8_*_ with open('client') as f_input: lines=f_input.readlines() with open('client_aaron', 'w') as f_output: for line in lines: f_output.write(line.replace(b' ',b' ansible_ssh_user="usr_name" ansible_ssh_pass="usr_pwd" ansible_ssh_port=22 ')) f_input.close() f_output.close()
问题:
1. 首次登陆需要对ssh进行校验,会导致上述命令报错如下
ERROR: Using a SSH password instead of a key is not possible because Host key checking is enabled and sshpass does not support this. Please add this host's fingerprint to your known_hosts file to manage this host.
参见http://www.361way.com/ansible-cfg/4401.html 关闭ansible.cfg中的host_key_checking功能