当前位置: 首页 > news >正文

使用python脚本一个简单的搭建ansible集群

1.环境说明:

角色主机名ip地址
控制主机server192.168.174.150
受控主机/被管节点client1192.168.174.151
受控主机/被管节点client2192.168.174.152

2.安装python和pip包

yum install -y epel-release
yum install -y python python-pip

3.pip安装依赖库

pip install pexpect     # 此库用相当于linux中的expect命令

4.完整脚本:

# coding=UTF-8
import sys,os,pexpect,subprocessmaster_addresses=["192.168.174.150"]           # 主节点们的IP地址
master_domains=["server"]                          # 域名们
client_addresses=["192.168.174.151","192.168.174.152"]           # 从节点们的IP地址
client_domains=["client1","client2"]                          # 域名们host_username="root"                                         # ssh连接的用户,控制端的用户为root
host_passwd="110119"                                         # ssh连接的用户密码
chrony_allows_addresses="192.168.174.0"ansible_hostGroup_all="clients_all"
ansible_hostGroup_master="clients_master"
ansible_hostGroup_client="clients_client"# 1.本地创建ssh公钥
if os.path.exists("/root/.ssh/id_rsa.pub") == True:print("\033[32m"+"ssh公钥已创建"+"\033[0m")                # 输出绿色字体
else:print("\033[32m"+"ssh公钥未创建,开始创建"+"\033[0m")child = pexpect.spawn('ssh-keygen -t rsa -b 1024')child.expect('Enter file in which to save the key')child.sendline('')child.expect('Enter passphrase')child.sendline('')child.expect('Enter same passphrase again')child.sendline('')child.expect(pexpect.EOF)               # 用于等待子进程的结束print(child.before.decode())            # 等待命令执行完毕并打印输出信息print("\033[32m" + "ssh公钥已创建" + "\033[0m")print("\n")# 向被控主机添加公钥的方法
def add_ssh_public_key_client(address,username,password):print("\033[32m"+"{}正在被添加公钥".format(address)+"\033[0m")# BatchMode=yes:表示使SSH在连接过程中不会提示输入密码,而直接尝试免密连接,-o ConnectTimeout=5:表示限制连接超时时间为5秒public_key_flag=os.system("ssh {}@{} -o BatchMode=yes 'exit' &> /dev/null".format(username,address))if public_key_flag== 0:print("\033[32m" + "{}已经可以ssh连接".format(address) + "\033[0m")returnchild = pexpect.spawn('ssh-copy-id -i /root/.ssh/id_rsa.pub {}@{}'.format(username,address))try:child.expect('Are you sure you want to continue connecting')except pexpect.exceptions.TIMEOUT:       # 如果try块中的咨询超时5秒没有出现就会出现异常pexpect.TIMEOUTprint("\033[32m"+"{}已经不是首次ssh连接了".format(address)+"\033[0m")else:                         # 是否回答咨询yeschild.sendline('yes')finally:child.expect('password')child.sendline(password)child.expect(pexpect.EOF)               # 用于等待子进程的结束print(child.before.decode())            # 等待命令执行完毕并打印输出信息
# 测试ssh连接的方法
def test_ssh_connection(all_flag,address,username):print("\033[32m" + "{}测试是否可以ssh连接".format(address) + "\033[0m")flag=os.system('ssh {}@{} -o ConnectTimeout=5 "exit"'.format(username,address))if flag==0:print("\033[32m" + "Success: {}可以ssh免密连接".format(address) + "\033[0m")else:print("\033[1;31m" + "Failed: {}ssh免密连接失败".format(address) + "\033[0m")     # 输出红色字体all_flag=1return all_flag# 本地的密钥开始加入被控制主机
for i in range(0, len(master_addresses)):add_ssh_public_key_client(master_addresses[i],host_username,host_passwd)print("\n")
for i in range(0, len(client_addresses)):add_ssh_public_key_client(client_addresses[i],host_username,host_passwd)print("\n")
# 测试ssh连接
for i in range(0, len(master_addresses)):final_flag=test_ssh_connection(0,master_addresses[i],host_username)
for i in range(0, len(client_addresses)):final_flag = test_ssh_connection(0, client_addresses[i], host_username)
if final_flag ==1:sys.exit("ssh测试失败,请检查!")
else:print("\033[32m" + "Success: 全部可以ssh免密连接" + "\033[0m")
print("\n")# 配置防火墙和selinux的方法
def set_firwalld_selinux(address,username):print("\033[32m" + "{}正在配置防火墙和selinux".format(address + "\033[0m"))fir_flag=os.system('ssh {}@{} "systemctl stop firewalld;systemctl disable firewalld"'.format(username,address))if fir_flag!=0:print("\033[1;31m" + "Failed: 防火墙修改失败" + "\033[0m")sys.exit("请检查!")sel_flag=os.system("ssh {}@{} 'sed -i 's/SELINUX=.*/SELINUX=disabled/' /etc/selinux/config'".format(username,address))if sel_flag!=0:print("\033[1;31m" + "Failed: selinux修改失败" + "\033[0m")sys.exit("请检查!")
# 配置防火墙和selinux
for i in range(0, len(master_addresses)):set_firwalld_selinux(master_addresses[i],host_username)
for i in range(0, len(client_addresses)):set_firwalld_selinux(client_addresses[i],host_username)
print("\n")# 配置域名映射
print("\033[32m" + "本地开始配置域名映射" + "\033[0m")
with open("/etc/hosts","w") as f:                      # w重写,a添加,只读f.write("127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4\n")f.write("::1         localhost localhost.localdomain localhost6 localhost6.localdomain6\n")for i in range(0, len(master_addresses)):f.write("{} {}\n".format(master_addresses[i],master_domains[i]))for i in range(0, len(client_addresses)):f.write("{} {}\n".format(client_addresses[i],client_domains[i]))
# 复制本地的/etc/hosts覆盖掉远程主机的/etc/hosts文件
for i in range(0, len(master_addresses)):os.system("scp /etc/hosts {}@{}:/etc/hosts".format(host_username,master_addresses[i]))
for i in range(0, len(client_addresses)):os.system("scp /etc/hosts {}@{}:/etc/hosts".format(host_username,client_addresses[i]))# 使用域名首次ssh连接
# 首次域名ssh连接的方法
def first_domain_name_con(domain,username,password):print("\033[32m"+"{}首次ssh连接".format(domain)+"\033[0m")# BatchMode=yes:表示使SSH在连接过程中不会提示输入密码,而直接尝试免密连接,-o ConnectTimeout=5:表示限制连接超时时间为5秒os.system("ssh -o BatchMode=yes -o ConnectTimeout=5 {}@{} 'exit' &> /dev/null".format(username, domain))first_domain_flag = os.system("ssh -o BatchMode=yes -o ConnectTimeout=5 {}@{} 'exit'".format(username, domain))if first_domain_flag == 0:print("\033[32m" + "{}已经可以ssh连接".format(domain) + "\033[0m")returnchild = pexpect.spawn('ssh {}@{} "exit"'.format(username,domain))try:connecting_tuple = child.expect('Are you sure you want to continue connecting')except pexpect.exceptions.TIMEOUT:print("\033[32m"+"{}已经不是首次ssh连接了".format(domain)+"\033[0m")else:child.sendline('yes')child.expect(pexpect.EOF)               # 用于等待子进程的结束print(child.before.decode())            # 等待命令执行完毕并打印输出信息for i in range(0, len(master_domains)):first_domain_name_con(master_domains[i],host_username,host_passwd)
for i in range(0, len(client_domains)):first_domain_name_con(client_domains[i], host_username, host_passwd)print("\n")# 配置chrony服务器
print("\033[32m" + "开始配置chrony" + "\033[0m")
# 配置chrony主服务器的方法
def chrony_master_service(username,address):print("\033[32m" + "{}配置主chrony".format(address) + "\033[0m")# 安装chronychrony_flag = os.system("ssh {}@{} 'yum install -y chrony'".format(username,address))if chrony_flag != 0:print("\033[1;31m" + "Failed: {}chrony安装失败".format(address) + "\033[0m")sys.exit("请检查!")# 开启同步地址范围chrony_master_allows_addresses = "sed -i 's/#allow 192.168.0.0\/16/allow {}\/24/' /etc/chrony.conf".format(chrony_allows_addresses)os.system('ssh {}@{} "{}"'.format(username, address, chrony_master_allows_addresses))# 开启stratum层数chrony_master_allows_stratum = "sed -i 's/#local stratum 10/local stratum 10/' /etc/chrony.conf"os.system('ssh {}@{} "{}"'.format(username, address, chrony_master_allows_stratum))# 重启服务chrony_service = "systemctl restart chronyd && systemctl enable chronyd &> /dev/null"os.system('ssh {}@{} "{}"'.format(username, address, chrony_service))os.system('ssh {}@{} "sleep 5"'.format(username, address))# 开启时间同步os.system('ssh {}@{} "timedatectl set-ntp true"'.format(username, address))
#配置chrony同步节点的方法
def chrony_master_client(username,address):print("\033[32m" + "{}配置同步chrony".format(address) + "\033[0m")# 安装chronychrony_flag = os.system("ssh {}@{} 'yum install -y chrony'".format(username,address))if chrony_flag != 0:print("\033[1;31m" + "Failed: {}chrony安装失败".format(address) + "\033[0m")sys.exit("请检查!")# 删除默认的server地址sed_chrony_delete = "sed -i '{}' /etc/chrony.conf".format('/^server/d')os.system('ssh {}@{} "{}"'.format(username,address,sed_chrony_delete))# 添加自定义的server地址for j in range(0, len(master_addresses)):sed_chrony_add = "sed -i '{}' /etc/chrony.conf".format("2a\server {} iburst".format(master_addresses[j]))os.system('ssh {}@{} "{}"'.format(username, address, sed_chrony_add))# 重启服务chrony_service = "systemctl restart chronyd && systemctl enable chronyd &> /dev/null"os.system('ssh {}@{} "{}"'.format(username,address,chrony_service))# 开启时间同步os.system('ssh {}@{} "timedatectl set-ntp true"'.format(username, address))os.system('ssh {}@{} "sleep 5"'.format(username, address))chrony_time = "chronyc sources -v | sed -n '{}'".format("/^\^\*/p")chrony_output = subprocess.check_output('ssh {}@{} "{}"'.format(username,address,chrony_time) ,shell=True)# 输出结果print(chrony_output)if chrony_output == "" or chrony_output is None:print("\033[1;31m" + "Failed: {}时间同步失败".format(address) + "\033[0m")sys.exit("请检查!")for i in range(0, len(master_addresses)):chrony_master_service(host_username,master_addresses[i])
for i in range(0, len(client_addresses)):chrony_master_client(host_username,client_addresses[i])
print("\n")# 安装ansbile
print("\033[32m" + "本地安装ansible软件" + "\033[0m")
os.system("yum install -y epel-release && yum install -y ansible")
try:ansible_output = subprocess.check_output("ansible --version", shell=True)
except subprocess.CalledProcessError:print("\033[1;31m" + "Failed: 本地安装ansible失败" + "\033[0m")sys.exit("请检查!")
finally:print("\033[32m" + "安装的ansible软件版本如下: " + "\033[0m")print(ansible_output)# /etc/ansible/hosts文件中添加主机租
print("\033[32m" + "修改配置文件/etc/ansible/hosts" + "\033[0m")
with open('/etc/ansible/hosts','a') as f:# ansible主机组clients_allf.write("["+ansible_hostGroup_all+"]"+"\n")for i in range(0, len(master_domains)):f.write(master_domains[i] + "\n")for i in range(0, len(client_domains)):f.write(client_domains[i] + "\n")# ansible主机组clients_masterf.write("[" + ansible_hostGroup_master + "]" + "\n")for i in range(0, len(master_domains)):f.write(master_domains[i] + "\n")# ansible主机组clients_clientf.write("[" + ansible_hostGroup_client + "]" + "\n")for i in range(0, len(client_domains)):f.write(client_domains[i] + "\n")# 测试
print("\033[32m" + "测试ansible命令" + "\033[0m")
try:ansible_hoc_output = subprocess.check_output("ansible {} -a uptime".format(ansible_hostGroup_all), shell=True)
except subprocess.CalledProcessError:print("\033[1;31m" + "Failed: 测试失败无法使用ansible命令" + "\033[0m")sys.exit("请检查!")
finally:print("\033[32m" + "测试结果如下" + "\033[0m")print("\033[1;33;40m"+ansible_hoc_output+"\033[0m")

http://www.lryc.cn/news/259179.html

相关文章:

  • 【价值几十万的仿抖音直播电商系统源码共享】
  • 对于vue3项目中使用shareReward还是shareReward.value的问题
  • 利用websockify将websocket通信转换成tcp
  • 【LeetCode刷题】-- 163.缺失的区间
  • ClickHouse为何如此之快
  • Avalonia中如何将View事件映射到ViewModel层
  • (第42天)DataGuard 搭建之使用 Duplicate 复制
  • LeetCode 0070. 爬楼梯:动态规划(递推)
  • XMemcached network layout exception java.nio.channels.ClosedChannelException
  • 记录 | vscode pyhton c++调试launch.json配置
  • Java入门基础:浅显易懂 死循环
  • LeetCode刷题--- 验证二叉搜索树
  • go-zero 开发入门-加法客服端示例
  • Python 快速入门——基础语法
  • EasyRecovery2024苹果电脑mac破解版安装包下载
  • Git常用命令大全
  • vue项目本地正常运行,打包到线上时无法访问js等资源
  • 计网Lesson10 - 网络层之IP协议分析
  • LangChain 25: SQL Agent通过自然语言查询数据库sqlite
  • Redis生产实战-热key、大key解决方案、数据库与缓存最终一致性解决方案
  • 可惜+悲伤+唉=emmo...
  • [gRPC实现go调用go]
  • uniapp使用v-html调用接口,富文本图片 视频自适应大小
  • 安卓MediaRecorder(2)录制源码分析
  • MySql数据库全量备份脚本
  • windows10下jdk安装
  • Centos7防火墙及端口开启
  • vue开发,axios网络请求框架基本用法和封装
  • 对比SPI、UART、I2C通信的区别与应用
  • CentOS7安装MySQL8.0