1.环境说明:
角色 |
主机名 |
ip地址 |
控制主机 |
server |
192.168.174.150 |
受控主机/被管节点 |
client1 |
192.168.174.151 |
受控主机/被管节点 |
client2 |
192.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,subprocess
master_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")
return
child = 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.TIMEOUT
print("\033[32m"+"{}已经不是首次ssh连接了".format(address)+"\033[0m")
else: # 是否回答咨询yes
child.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=1
return 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")
return
child = 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")
# 安装chrony
chrony_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")
# 安装chrony
chrony_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_all
f.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_master
f.write("[" + ansible_hostGroup_master + "]" + "\n")
for i in range(0, len(master_domains)):
f.write(master_domains[i] + "\n")
# ansible主机组clients_client
f.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")