Ansible安装

首先需要配置ansible主机到其他被控机器的SSH免密登录,一个一个的配置太繁琐,这里编写一个脚本,使用expect解决脚本执行过程中的交互问题,批量配置免密登录。

在ansible-host上生成ssh公钥:

ssh-keygen -t rsa

touch expect.sh

    #!/bin/bash
    FILE=`cat /root/ip.txt`
    for i in $FILE;do
    ip=$(echo "$i"|cut -d":" -f1)
    password=$(echo "$i"|cut -d":" -f2)
    
    expect -c "
    spawn /usr/bin/ssh-copy-id -i /root/.ssh/id_rsa.pub root@$ip
        expect {
        \"*yes/no*\" {send \"yes\r\";exp_continue}
        \"*password*\" {send \"$password\r\";exp_continue}
        \"*password*\" {send \"$password\r\";}
    }
    "
    done

ip.txt中,以ip:password的格式,写好被控机器的密码信息。执行该脚本即可完成ssh免密登录。若机器上未安装expect命令,yum安装即可。

注意普通用户执行这个脚本后,可能仍然无法免密登录,这一般是selinux造成的问题。出现该问题后,要么直接关闭被控机的selinux服务,要么重置被控机的安全上下文;具体操作如下:

查看/var/log/audit/audit.log中关于ssh免密登录时的报错,查找类似avc: denied { search/read }的报错,根据name="/path"字段restorecon安全上下文;

执行restorecon -r -vv / , 再修改~/.ssh/authorized_keys 的安全上下文:

执行ls -laZ 查看安全上下文,尝试restorecon -R -vv authorized_keys 恢复(-R为递归,-vv为verbose),若未生效,则手动修改 :

chcon -R -u system_u -t ssh_home_t /home/user/.ssh/authorized_keys (修改时可参照/root/.ssh中文件信息修改)

关闭selinux方法如下:

更改selinux状态,如果selinux是开启的可以使用setenforce 0/1来切换enforcing和permissive状态;

如果selinux是关闭的,需要开启,首先修改配置文件/etc/selinux/config,然后查看/boot/grub/menu.lst,确保kernel那一行后面没有selinux=0,接下来重新启动,selinux从开启到关闭或者从关闭到开启必须要重启。

selinux安全上下文主要分三个部分:

system_u:object_r:ssh_home_t:s0
(-u:-r:-t:-l)
chcon命令选项:
-h, --no-dereference:影响符号连接而非引用的文件。
--reference=参考文件:使用指定参考文件的安全环境,而非指定值。
-R, --recursive:递归处理所有的文件及子目录。
-v, --verbose:为处理的所有文件显示诊断信息。
-u, --user=用户:设置指定用户的目标安全环境。
-r, --role=角色:设置指定角色的目标安全环境。
-t, --type=类型:设置指定类型的目标安全环境。
-l, --range=范围:设置指定范围的目标安全环境。

安装epel源:按照配置yum的方法来。

vi /etc/hosts
    195.220.108.108 fr2.rpmfind.net
    112.124.140.210 mirrors.aliyun.com
    67.219.144.68 download.fedoraproject.org
    219.216.128.25 mirrors.neusoft.edu.cn
    166.111.206.178 mirrors.tuna.tsinghua.edu.cn
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo
rpm -ivh http://fr2.rpmfind.net/linux/epel/6/x86_64/epel-release-6-8.noarch.rpm
yum upgrade ca-certificates --disablerepo=epel -y
sed -i 's/#baseurl/baseurl/g' /etc/yum.repos.d/epel.repo
sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/epel.repo

安装ansible:

yum install ansible -y



发表评论

您的电子邮箱地址不会被公开。