集群SSH免密登陆:主要是ansible服务端需要将/root/.ssh/id_rsa.pub分发到其他服务器


#!/bin/bash 
case $1 in # 获取option 
-cp | --cpoy)  #判断option
        for ip_list in `cat $2`;do  #读取$2文件每一行,将ip密码信息存入ip_list变量
        ip=`echo $ip_list | cut -d: -f1` #提取ip
        ps=`echo $ip_list | cut -d: -f2` #提取密码
            expect -c"                   
            spawn scp -r /root/.ssh/  $ip:  #直接拷贝.ssh目录,配置免密码登录
            expect {       
                \"*password*\" {send \"$ps\r\";exp_continue}
                \"*password*\" {send \"$ps\r\";}
            }
           "
       done
;;
-c  | --cmd) #执行命令
        for ip_line in `cat $2`;do
        ip=`echo $ip_line| cut -d: -f1`
            if [[ "$4" = \h ]];then
                echo -e "\033[33m $ip: \033[0m" 
                ssh $ip $3
            else
            echo -e "\033[33m $ip: \033[0m" `ssh $ip $3`
            fi
        done
;;
-h | --help )
echo -e "\e[1;32m  Please create a IP Password file in advance: \e[0m"
echo -e "\e[1;32m  $0 -cp,--copy  ip.txt  \e[0m"
echo -e "\e[1;32m  $0 -c,--cmd  ip.txt 'cmd' and \h \e[0m"
;;
esac

expect脚本:

#!/usr/bin/expect
#for ((i=1;i<254;i++)) ; do  echo "192.168.2.$i:p@ssWord" >> hosts.txt; done
#yum install expect
#hosts.txt格式:host:ip
info=`awk '{print $0}' ./hosts.txt`
for i in $info;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

fabric是一个基于python开发的对ssh集成工具,对我们而言只需要使用相应的接口,来高效的完成工作,我们常用到的功能基本是 : 本地或者远端执行命令, 分发文件,收集文件,还有一些权限相关的操作。官网:http://docs.fabfile.org/en/1.12/index.html

fabric脚本:

[root@zabbix NewhostInit]# cat fabfile.py 
from fabric.api import *
import zabbix_install_salt as zs

env.hosts = zs.get_ip()
env.password='p@ssWord'
def auth():
#    with settings(sudo_user='root'):
    with settings(warn_only=True):
        run("mkdir /root/.ssh/")
        put( local_path="/root/.ssh/id_rsa_zabbix.pub",remote_path="/root/.ssh/id_rsa_zabbix.pub")
        run("cat /root/.ssh/id_rsa_zabbix.pub >> /root/.ssh/authorized_keys")
        run("chmod 600 /root/.ssh/authorized_keys")

测试登录,然后就可以愉快得玩耍了。

注:更多脚本请关注:https://github.com/strongit/NewhostInit


Ansible常用模块使用

(1)、setup

#查看远程主机的一些基础信息

[root@zabbix ansible]# ansible 2_cluster -m setup
192.168.2.93 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "192.168.2.93"
        ], 
        "ansible_all_ipv6_addresses": [
            "fe80::250:56ff:fe8e:79be"
        ], 
        "ansible_architecture": "x86_64", 
        "ansible_bios_date": "08/16/2013", 
        "ansible_bios_version": "6.00", 
        "ansible_cmdline": {
            "KEYBOARDTYPE": "pc", 
            "KEYTABLE": "us", 
            "LANG": "en_US.UTF-8", 
            "SYSFONT": "latarcyrheb-sun16", 
            "crashkernel": "129M@0M", 
            "quiet": true, 
            "rd_LVM_LV": "VolGroup/lv_root", 
            "rd_NO_DM": true, 
            "rd_NO_LUKS": true, 
            "rd_NO_MD": true, 
            "rhgb": true, 
            "ro": true, 
            "root": "/dev/mapper/VolGroup-lv_root"
        }, 
        "ansible_date_time": {
            "date": "2016-11-02", 
            "day": "02", 
            "epoch": "1478071697", 
            "hour": "15", 
            "iso8601": "2016-11-02T07:28:17Z", 
            "iso8601_basic": "20161102T152817376320", 
            "iso8601_basic_short": "20161102T152817", 
            "iso8601_micro": "2016-11-02T07:28:17.376402Z", 
            "minute": "28", 
            "month": "11", 
            "second": "17", 
            "time": "15:28:17", 
            "tz": "CST", 
            "tz_offset": "+0800", 
            "weekday": "Wednesday", 
            "weekday_number": "3", 
            "weeknumber": "44", 
            "year": "2016"
        }, 
        "ansible_default_ipv4": {
            "address": "192.168.2.93", 
            "alias": "eth2", 
            "broadcast": "192.168.2.255", 
            "gateway": "192.168.2.1", 
            "interface": "eth2", 
            "macaddress": "00:50:56:8e:79:be", 
            "mtu": 1500, 
            "netmask": "255.255.255.0", 
            "network": "192.168.2.0", 
            "type": "ether"
        }, 
        "ansible_default_ipv6": {}, 
        "ansible_devices": {
            "sda": {
                "holders": [], 
                "host": "SCSI storage controller: LSI Logic / Symbios Logic 53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI (rev 01)", 
                "model": "Virtual disk", 
                "partitions": {
                    "sda1": {
                        "sectors": "1024000", 
                        "sectorsize": 512, 
                        "size": "500.00 MB", 
                        "start": "2048"
                    }, 
                    "sda2": {
                        "sectors": "628119552", 
                        "sectorsize": 512, 
                        "size": "299.51 GB", 
                        "start": "1026048"
                    }
                }, 
                "removable": "0", 
                "rotational": "1", 
                "sas_address": null, 
                "sas_device_handle": null, 
                "scheduler_mode": "cfq", 
                "sectors": "629145600", 
                "sectorsize": "512", 
                "size": "300.00 GB", 
                "support_discard": "0", 
                "vendor": "VMware"
            }, 
            "sr0": {
                "holders": [], 
                "host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)", 
                "model": "VMware IDE CDR10", 
                "partitions": {}, 
                "removable": "1", 
                "rotational": "1", 
                "sas_address": null, 
                "sas_device_handle": null, 
                "scheduler_mode": "cfq", 
                "sectors": "2097151", 
                "sectorsize": "512", 
                "size": "1024.00 MB", 
                "support_discard": "0", 
                "vendor": "NECVMWar"
            }
        }, 
        "ansible_distribution": "CentOS", 
        "ansible_distribution_major_version": "6", 
        "ansible_distribution_release": "Final", 
        "ansible_distribution_version": "6.7", 
        "ansible_dns": {
            "nameservers": [
                "192.168.2.20", 
                "8.8.8.8"
            ]
        }, 
        "ansible_domain": "", 
        "ansible_env": {
            "G_BROKEN_FILENAMES": "1", 
            "HOME": "/root", 
            "LANG": "en_US.UTF-8", 
            "LC_ALL": "en_US.UTF-8", 
            "LC_MESSAGES": "en_US.UTF-8", 
            "LESSOPEN": "||/usr/bin/lesspipe.sh %s", 
            "LOGNAME": "root", 
            "MAIL": "/var/mail/root", 
            "PATH": "/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin", 
            "PWD": "/root", 
            "PYTHONPATH": "", 
            "SHELL": "/bin/bash", 
            "SHLVL": "2", 
            "SSH_CLIENT": "192.168.2.223 55940 22", 
            "SSH_CONNECTION": "192.168.2.223 55940 192.168.2.93 22", 
            "SSH_TTY": "/dev/pts/0", 
            "TERM": "xterm", 
            "USER": "root", 
            "_": "/usr/bin/python"
        }, 
        "ansible_eth2": {
            "active": true, 
            "device": "eth2", 
            "ipv4": {
                "address": "192.168.2.93", 
                "broadcast": "192.168.2.255", 
                "netmask": "255.255.255.0", 
                "network": "192.168.2.0"
            }, 
            "ipv6": [
                {
                    "address": "fe80::250:56ff:fe8e:79be", 
                    "prefix": "64", 
                    "scope": "link"
                }
            ], 
            "macaddress": "00:50:56:8e:79:be", 
            "module": "vmxnet3", 
            "mtu": 1500, 
            "pciid": "0000:03:00.0", 
            "promisc": false, 
            "type": "ether"
        }, 
        "ansible_fips": false, 
        "ansible_form_factor": "Other", 
        "ansible_fqdn": "mycatcluster26", 
        "ansible_gather_subset": [
            "hardware", 
            "network", 
            "virtual"
        ], 
        "ansible_hostname": "mycatcluster26", 
        "ansible_interfaces": [
            "lo", 
            "eth2"
        ], 
        "ansible_kernel": "2.6.32-573.el6.x86_64", 
        "ansible_lo": {
            "active": true, 
            "device": "lo", 
            "ipv4": {
                "address": "127.0.0.1", 
                "broadcast": "host", 
                "netmask": "255.0.0.0", 
                "network": "127.0.0.0"
            }, 
            "ipv6": [
                {
                    "address": "::1", 
                    "prefix": "128", 
                    "scope": "host"
                }
            ], 
            "mtu": 65536, 
            "promisc": false, 
            "type": "loopback"
        }, 
        "ansible_lvm": {
            "lvs": {
                "lv_root": {
                    "size_g": "291.66", 
                    "vg": "VolGroup"
                }, 
                "lv_swap": {
                    "size_g": "7.85", 
                    "vg": "VolGroup"
                }
            }, 
            "vgs": {
                "VolGroup": {
                    "free_g": "0", 
                    "num_lvs": "2", 
                    "num_pvs": "1", 
                    "size_g": "299.51"
                }
            }
        }, 
        "ansible_machine": "x86_64", 
        "ansible_memfree_mb": 6893, 
        "ansible_memory_mb": {
            "nocache": {
                "free": 7157, 
                "used": 714
            }, 
            "real": {
                "free": 6893, 
                "total": 7871, 
                "used": 978
            }, 
            "swap": {
                "cached": 0, 
                "free": 8039, 
                "total": 8039, 
                "used": 0
            }
        }, 
        "ansible_memtotal_mb": 7871, 
        "ansible_mounts": [
            {
                "device": "/dev/mapper/VolGroup-lv_root", 
                "fstype": "ext4", 
                "mount": "/", 
                "options": "rw", 
                "size_available": 270789632000, 
                "size_total": 308114112512, 
                "uuid": "8ded72c8-a452-4038-9edc-4d90233f3e98"
            }, 
            {
                "device": "/dev/sda1", 
                "fstype": "ext4", 
                "mount": "/boot", 
                "options": "rw", 
                "size_available": 442224640, 
                "size_total": 499355648, 
                "uuid": "05b2397a-c913-4dcf-aee2-a1cf6a0d8a99"
            }
        ], 
        "ansible_nodename": "mycatcluster26", 
        "ansible_os_family": "RedHat", 
        "ansible_pkg_mgr": "yum", 
        "ansible_processor": [
            "GenuineIntel", 
            "Intel(R) Xeon(R) CPU E5-2690 v3 @ 2.60GHz", 
            "GenuineIntel", 
            "Intel(R) Xeon(R) CPU E5-2690 v3 @ 2.60GHz", 
            "GenuineIntel", 
            "Intel(R) Xeon(R) CPU E5-2690 v3 @ 2.60GHz", 
            "GenuineIntel", 
            "Intel(R) Xeon(R) CPU E5-2690 v3 @ 2.60GHz", 
            "GenuineIntel", 
            "Intel(R) Xeon(R) CPU E5-2690 v3 @ 2.60GHz", 
            "GenuineIntel", 
            "Intel(R) Xeon(R) CPU E5-2690 v3 @ 2.60GHz", 
            "GenuineIntel", 
            "Intel(R) Xeon(R) CPU E5-2690 v3 @ 2.60GHz", 
            "GenuineIntel", 
            "Intel(R) Xeon(R) CPU E5-2690 v3 @ 2.60GHz"
        ], 
        "ansible_processor_cores": 2, 
        "ansible_processor_count": 4, 
        "ansible_processor_threads_per_core": 1, 
        "ansible_processor_vcpus": 8, 
        "ansible_product_name": "VMware Virtual Platform", 
        "ansible_product_serial": "VMware-42 0e 75 05 61 04 d0 4b-17 00 c9 58 01 61 23 b1", 
        "ansible_product_uuid": "420E7505-6104-D04B-1700-C958016123B1", 
        "ansible_product_version": "None", 
        "ansible_python": {
            "executable": "/usr/bin/python", 
            "has_sslcontext": false, 
            "type": "CPython", 
            "version": {
                "major": 2, 
                "micro": 6, 
                "minor": 6, 
                "releaselevel": "final", 
                "serial": 0
            }, 
            "version_info": [
                2, 
                6, 
                6, 
                "final", 
                0
            ]
        }, 
        "ansible_python_version": "2.6.6", 
        "ansible_selinux": false, 
        "ansible_service_mgr": "upstart", 
        "ansible_ssh_host_key_dsa_public": "AAAAB3NzaC1kc3MAAACBAPAkBHfLDqSJbKdBGA0OmDHl3OGEK9Js+5TUVLuX2kkPOBZJ2gRKzTpRYnu+PieWNv6/r0zaZTW7oR7PFKk/j/MYLjieMcX4ozrr4A8RjI8V/NaOG/WKM2Bqe4WweK2wRiCvqlO2kq4P3AcfCHuaRV4RMKg9QJDmVgWABA7vTftBAAAAFQDZ1AhlZFwBR7rhRA0C9/GZhZr3zwAAAIBjnRmc0UbTJuuIH3ckANIOer4OJJhQYf4bEg1tDfvuqZGC9I+1+TIKaN31ORvNXFidoeNiESVtmov70YhZuCqOSwtUcNC5nkmZVECZW5jyvy5nQF6Ly/fXBVZ9tW6uOzk75nDttVidYswLZeslgdVrr92d3JwHmGC8Rqxqy1nI2gAAAIAiHYnJJyuqjypq2qArClD2umSlfYuJfmwNEAqq4Bo9t9e2cDvXosQdqmZG15DdaTwgUrwOIiVZWYvq0eJlqg34Z1aQFp5QrQspaIV4XNRSS8NkMgcNEYo9YlCFh9SITUFKFuPrCKwAUHrNTiRpOzbz23/FGWchQxR8JLraMKZoGw==", 
        "ansible_ssh_host_key_rsa_public": "AAAAB3NzaC1yc2EAAAABIwAAAQEAqu7dCDG6tP3kEc/K8f/phvgPpRMJedPbrRDBdw37iusm0/5GM/AqPGzkZ5tcFCjRwnvmVAlD9IZtOEAUk/JjzRdyPQnlhMq9ZkpuKa7o2OmLzLlpilwds8FH1hY3DVh043uosVY/DZ+RWp7LVY/keRaN3PSx5e0wBXzAmhh3AthL1UR4xTSALQ3uAULVFJytgKvphPfitwbFB7pmV9txcrLOqdlFrUkGdS/wD3WJF6XBjIXOOWHi3PIQuzdMbnTd0LlBlEvw7OqqoXDd66KHxxIVdpbIjSRtaS7itSmxYhxToZSRklkdZi6gUarH8qMRcyJn4uBPCPV6hnSryHh1QQ==", 
        "ansible_swapfree_mb": 8039, 
        "ansible_swaptotal_mb": 8039, 
        "ansible_system": "Linux", 
        "ansible_system_capabilities": [], 
        "ansible_system_capabilities_enforced": "False", 
        "ansible_system_vendor": "VMware, Inc.", 
        "ansible_uptime_seconds": 4901602, 
        "ansible_user_dir": "/root", 
        "ansible_user_gecos": "root", 
        "ansible_user_gid": 0, 
        "ansible_user_id": "root", 
        "ansible_user_shell": "/bin/bash", 
        "ansible_user_uid": 0, 
        "ansible_userspace_architecture": "x86_64", 
        "ansible_userspace_bits": "64", 
        "ansible_virtualization_role": "guest", 
        "ansible_virtualization_type": "VMware", 
        "module_setup": true
    }, 
    "changed": false
}


(2)、ping

#测试远程主机运行状态

[root@zabbix ansible]# ansible 2_cluster -m ping
192.168.2.93 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.2.25 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.2.26 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}


(3)、file 

#设置文件属性

相关选项如下:

force:需要在两种情况下强制创建软链接,一种是源文件不存在,但之后会建立的情况下;另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes|no

group:定义文件/目录的属组

mode:定义文件/目录的权限

owner:定义文件/目录的属主

path:必选项,定义文件/目录的路径

recurse:递归设置文件的属性,只对目录有效

src:被链接的源文件路径,只应用于state=link的情况

dest:被链接到的路径,只应用于state=link的情况

state:

       directory:如果目录不存在,就创建目录

       file:即使文件不存在,也不会被创建

       link:创建软链接

       hard:创建硬链接

       touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间

       absent:删除目录、文件或者取消链接文件


(4)、copy

#复制文件到远程主机

相关选项如下:

backup:在覆盖之前,将源文件备份,备份文件包含时间信息。有两个选项:yes|no

content:用于替代“src”,可以直接设定指定文件的值

dest:必选项。要将源文件复制到的远程主机的绝对路径,如果源文件是一个目录,那么该路径也必须是个目录

directory_mode:递归设定目录的权限,默认为系统默认权限

force:如果目标主机包含该文件,但内容不同,如果设置为yes,则强制覆盖,如果为no,则只有当目标主机的目标位置不存在该文件时,才复制。默认为yes

others:所有的file模块里的选项都可以在这里使用

src:被复制到远程主机的本地文件,可以是绝对路径,也可以是相对路径。如果路径是一个目录,它将递归复制。在这种情况下,如果路径使用“/”来结尾,则只复制目录里的内容,如果没有使用“/”来结尾,则包含目录在内的整个内容全部复制,类似于rsync。

(5)、command 

#在远程主机上执行命令

相关选项如下:

creates:一个文件名,当该文件存在,则该命令不执行

free_form:要执行的linux指令

chdir:在执行指令之前,先切换到该目录

removes:一个文件名,当该文件不存在,则该选项不执行

executable:切换shell来执行指令,该执行路径必须是一个绝对路径



(6)、shell

#切换到某个shell执行指定的指令,参数与command相同

与command不同的是,此模块可以支持命令管道,同时还有另一个模块也具备此功能:raw


示例:

## 先在本地创建一个SHELL脚本

# vim /tmp/rocketzhang_test.sh
#!/bin/sh
date +%F_%H:%M:%S
#chmod +x /tmp/rocketzhang_test.sh


## 将创建的脚本文件分发到远程

# ansible 2_cluster -m copy -a "src=/tmp/rocketzhang_test.sh dest=/tmp/rocketzhang_test.sh owner=root group=root mode=0755"


## 远程执行

# ansible 2_cluster -m shell -a "/tmp/rocketzhang_test.sh"


(7)、更多模块

其他常用模块,比如:service、cron、yum、synchronize就不一一例举,可以结合自身的系统环境进行测试。

service:系统服务管理

cron:计划任务管理

yum:yum软件包安装管理

synchronize:使用rsync同步文件

user:系统用户管理

group:系统用户组管理


更多模块可以参考:

#ansible-doc –l

http://docs.ansible.com/modules_by_category.html

http://www.ansible.cn/docs/