python自动化运维之CMDB篇-大米哥

时间:2021-08-05 04:01:41

python自动化运维之CMDB篇

视频地址:复制这段内容后打开百度网盘手机App,操作更方便哦 链接:https://pan.baidu.com/s/1Oj_sglTi2P1CMjfMkYKwCQ 提取码:ifp2

  1. CMD是什么以及发挥什么样的作用

1.1:CMDB架构

文档使用CMDB部署redis集群来演示

python自动化运维之CMDB篇-大米哥

1.2:CMDB核心功能

1、使用CMDB部署的服务,会服务器记录所有设备信息 ,包括机房,公网IP/私网,集群信息,负责人,连接交换机端口

带宽,硬盘,CPU内存等信息

2、在CMDB可以对服务管理维护,任意增删改查

3、CMDB可以配置图形界面,也可以使用命令终端操作

1.3:CMDB完成的工作

python自动化运维之CMDB篇-大米哥

  1. 选择安装哪些集群包
  2. 推送新的服务器的DNS解析记录(内网,外网解析,以及DNS domain的C/S同步工作)
  3. 新添加的服务器自动加入监控系统,包括在监控平台添加新节点
  4. 生成防火墙规则,以及配置网络设备相关

二、CMDB的整体业务架构

客户端服务端架构,使用tcp通讯(不使用ssh)

python自动化运维之CMDB篇-大米哥

2.1: 架构简介

python自动化运维之CMDB篇-大米哥

  1. c/s模型
  2. 服务端负责调用数据库,并且实时和客户端保持通信
  3. 客户端:配置agent端(脚本)在每一台客户端机器上,agent作为沟通的中间件,让所有客户端节点与服务端保持实时联系
  4. 网络通讯:使用的tcp协议,ssh协议数量大了效率低(还需要配置公钥私钥
  5. 数据库需要设计表结构,存储客户端以及部署的服务信息

2.2:部署redis准备

python自动化运维之CMDB篇-大米哥

目录分配:

软件安装:/usr/local/redis/ #启动redis进程

配置文件:/usr/local/etc/redis #redis配置文件

redis存储目录:/data/.xxxx #存储一般单独分目录,给定足够空间,用隐藏目录是为了安全

日志目录: /data/log

redis是单线程运行,需要拆分成多个实例来启动(提升效率)

python自动化运维之CMDB篇-大米哥

三、环境配置

基本环境准备,至少3台服务器

  1. cmdb服务端
  2. redis+cmdb客户端
  3. 任意监控系统+cmdb

3.1: 做好cmdb服务端的解析工作

修改/etc/hosts,或者配置named解析。解析cmdb服务端

3.2:配置好python3的环境

yum install python3

3.3:第一台机器服务端配置好mysql server的环境

下载并安装mysql官方的yum repository

在server01上安装

[root@localhost ~]# wget -i -c http://dev.mysql.com/get/mysql57-community-release-el7-10.noarch.rpm

[root@localhost ~]# yum -y install mysql57-community-release-el7-10.noarch.rpm

安装mysql

server01

[root@localhost ~]# yum -y install mysql-community-server

mysql数据库启动

server01

[root@localhost ~]# systemctl start mysqld.service

[root@localhost ~]# systemctl status mysqld.service

修改mysql密码

server01

[root@localhost ~]# grep "password" /var/log/mysqld.log

[root@localhost ~]# mysql -uroot -p

输⼊入初始密码,此时不不能做任何事情,因为MySQL默认必须,修改密码之后才能操作数据库:

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY '123456';

下载安装pymysql库

server01

接下来 我们在第⼀一台机器器上 安装⼀一下 python3 需要调⽤用。pymysql 为了了后⾯面 可以操作DB

wget https://files.pythonhosted.org/packages/44/39/6bcb83cae0095a31b6be4511707fdf2009d3e29903a55a0494d3a9a2fac0/PyMySQL-0.8.1.tar.gz

ls

tar -xvzf PyMySQL-0.8.1.tar.gz

cd PyMySQL-0.8.1/

python setup.py install

python3

import pymysql没问题,说明安装成功

在server01上安装FTP服务

yum install vsftpd

service vsftpd start

默认的ftp路径:/var/ftp/pub/ #将软件包拷贝到该目录

为什么需要ftp服务?

1、当需要在客户端安装服务时,在服务端下载安装包安装

python自动化运维之CMDB篇-大米哥

3.4: 在client01和02安装python3

客户端只需要安装python3,不需要安装pymysql,因为与数据库通信,是客户端通过服务端调用数据库

3.5:在client02安装nagios

nagios的配置文件后面将由cmdb来生成

host.cfgèdefine server

四、CMDB的mysql数据库结构

python自动化运维之CMDB篇-大米哥

第一张表

python自动化运维之CMDB篇-大米哥

第二张表

python自动化运维之CMDB篇-大米哥

第三张表

存储定义类型,如定义redis nginx

python自动化运维之CMDB篇-大米哥

结果如下:

python自动化运维之CMDB篇-大米哥

建表语句

python使用 pymysql模块创建sql表格代码:

#存储服务器信息

sql = """CREATE TABLE IF NOT EXISTS SERVERS (

SERVER_ID SMALLINT UNSIGNED NOT NULL auto_increment,        #服务id

SERVERNAME CHAR(30) NOT NULL,                 #可以被解析成ip的机器名

INTERNAL_IP CHAR(20) NOT NULL,            #ip地址

ONLINE BOOLEAN,                服务器是否在线

PRIMARY KEY(SERVER_ID))"""             主键是server—id

cursor.execute(sql)

#存储进程信息表

sql = """CREATE TABLE IF NOT EXISTS PROCESS (

PROCESS_ID SMALLINT UNSIGNED NOT NULL auto_increment,     #安装软件的进程id

PROCESS_NAME CHAR(20) NOT NULL, #进程名

SERVER_ID SMALLINT UNSIGNED NOT NULL,                第一张服务器表对应的server-id,进程位于那台服务器上

SERVICE_ID SMALLINT UNSIGNED NOT NULL,             第三张表service表对应的service-id,进程对应的类型

MASTER BOOLEAN,            #是否为主,比如redis的主从,其他服务默认应当是主

SLAVE BOOLEAN,            #是否为从

PORT SMALLINT UNSIGNED,                #端口号

ONLINE BOOLEAN, #是否在线

PRIMARY KEY(PROCESS_ID))"""

cursor.execute(sql)

#存储服务id表

sql = """CREATE TABLE IF NOT EXISTS SERVICE (

SERVICE_ID SMALLINT UNSIGNED NOT NULL auto_increment,

SERVICE_NAME CHAR(20) NOT NULL,

PRIMARY KEY(SERVICE_ID))"""

cursor.execute(sql)

python自动化运维之CMDB篇-大米哥

五、CMDB的菜单代码模块

准备

python自动化运维之CMDB篇-大米哥

python自动化运维之CMDB篇-大米哥

python自动化运维之CMDB篇-大米哥

python自动化运维之CMDB篇-大米哥

菜单模块2

python自动化运维之CMDB篇-大米哥

异常退出,关闭进程的方法

python自动化运维之CMDB篇-大米哥

六、CMDB的C/S模块和网络通讯的利用

python自动化运维之CMDB篇-大米哥

python自动化运维之CMDB篇-大米哥

python自动化运维之CMDB篇-大米哥

七、CMDB的子进程代码模块

python自动化运维之CMDB篇-大米哥

开启一个子进程

python自动化运维之CMDB篇-大米哥

python自动化运维之CMDB篇-大米哥

python自动化运维之CMDB篇-大米哥

八、CMDB的推送部署模块

python自动化运维之CMDB篇-大米哥

python自动化运维之CMDB篇-大米哥

python自动化运维之CMDB篇-大米哥

python自动化运维之CMDB篇-大米哥

python自动化运维之CMDB篇-大米哥

python自动化运维之CMDB篇-大米哥

九、CMDB整体联调

server01-服务器端

Client01

Client02

python cmdb.py #调用

fork.py #自动调用

server.py #自动调用

python agent.py #调用

deplogment.py #自动调用

Nagios #略

安装数据库

   

代码

cmdb.py

环境代码

#!/usr/bin/python3

#coding: utf8

import os

import pymysql

import fork #调用了fork,fork调用了server

#数据库初始化,建表函数,创建3张表,记录信息

def db_init():

db = pymysql.connect("192.168.1.228", "root", "Lzq@31508", "CMDB") #连接cmdb数据库

cursor = db.cursor()

sql = """CREATE TABLE IF NOT EXISTS SERVERS (

SERVER_ID SMALLINT UNSIGNED NOT NULL auto_increment,SERVERNAME CHAR(40) NOT NULL,

INTERNAL_IP CHAR(20) NOT NULL,

ONLINE BOOLEAN,

PRIMARY KEY(SERVER_ID))"""

cursor.execute(sql)

sql = """CREATE TABLE IF NOT EXISTS PROCESS (

PROCESS_ID SMALLINT UNSIGNED NOT NULL

auto_increment,

PROCESS_NAME CHAR(20) NOT NULL,

SERVER_ID SMALLINT UNSIGNED NOT NULL,

SERVICE_ID SMALLINT UNSIGNED NOT NULL,

MASTER BOOLEAN,

SLAVE BOOLEAN,

PORT SMALLINT UNSIGNED,

ONLINE BOOLEAN,

PRIMARY KEY(PROCESS_ID))"""

cursor.execute(sql)

sql = """CREATE TABLE IF NOT EXISTS SERVICE (

SERVICE_ID SMALLINT UNSIGNED NOT NULL

auto_increment,

SERVICE_NAME CHAR(20) NOT NULL,

PRIMARY KEY(SERVICE_ID))"""

cursor.execute(sql)

db.close()

#定义一个类,数据库插入数据

class db_insert:

def db_insert_servers(self,servername,internal_ip,online): #往第一张SERVERS表服务器表插入数据

db = pymysql.connect("192.168.1.228", "root", "Lzq@31508", "CMDB") #连接数据库

cursor = db.cursor()

cursor.execute('insert into SERVERS (SERVERNAME, INTERNAL_IP, ONLINE)VALUES("%s","%s","%d")' % (servername, internal_ip, online)) #执行sql语句

db.commit() #使用python操作数据库,必须commit后sql语句才能生效

db.close()

def db_insert_process(self, process_name, server_id, service_id, master, slave, port ,online): #往第二张进程信息表插入数据

db = pymysql.connect("192.168.1.228", "root", "Lzq@31508", "CMDB")

cursor = db.cursor()

#TODO

cursor.execute('insert into PROCESS (PROCESS_NAME, SERVER_ID, SERVICE_ID, MASTER, SLAVE, PORT, ONLINE)VALUES("%s","%d","%d","%d","%d","%d","%d")' % (process_name, server_id, service_id, master, slave, port ,online))

db.commit()

db.close()

def db_insert_service(self,service_name): #第三张进程类型表,插入进程类型数据

db = pymysql.connect("192.168.1.228", "root", "Lzq@31508", "CMDB")

cursor = db.cursor()

cursor.execute('insert into SERVICE (SERVICE_NAME)VALUES("%s")'%(service_name))

db.commit()

db.close()

 #定义一个数据库查询类

class db_search:

def db_search_servers(self): #查询第三张表进程类型表

db = pymysql.connect("192.168.1.228", "root", "Lzq@31508", "CMDB")

cursor = db.cursor()

cursor.execute('select * from SERVERS')

results = cursor.fetchall() #fetchall获取sql执行结果

for row in results: #循环遍历结果存储到变量中打印

server_id = row[0]

servername = row[1]

internal_ip = row[2]

online = row[3]

print("服务器编号=%d,服务器名=%s,内网地址=%s,是否在线=%d"%(server_id, servername, internal_ip, online))

db.close()

return server_id

def db_search_service(self):

db = pymysql.connect("192.168.1.228", "root", "Lzq@31508", "CMDB")

cursor = db.cursor()

cursor.execute('select * from SERVICE') #取出第三张表所有值

results = cursor.fetchall()

for row in results:

service_id = row[0]

service_name = row[1]

print("服务名编号=%d,服务名=%s"%(service_id, service_name))

#比上一个函数多了一个参数,这种方法叫什么?类的重构?

def db_search_service(self, service_name):

db = pymysql.connect("192.168.1.228", "root", "Lzq@31508", "CMDB")

cursor = db.cursor()

server_id_list = []

commond = "select * from SERVICE where SERVICE_NAME = '" + service_name + " '" #第三张进程类型表

cursor.execute(commond)

result = cursor.fetchall()

if result:

service_id = result[0][0]

else:

print("未能找到相关服务,请重新确认")

return

commond = "select * from PROCESS where SERVICE_ID = '" + str(service_id) + " '"

cursor.execute(commond)

result = cursor.fetchall()

if result:

for row in result:

server_id_list.append(row[3])

for server_id in server_id_list:

commond = "select * from SERVERS where SERVER_ID = '" + str(server_id) + " '"

cursor.execute(commond)

result = cursor.fetchall()

if result:

server_name = result[0][1]

print(f'{server_name}\n')

return

def db_search_servers_for_agent_verify(self, sql):

db = pymysql.connect("192.168.1.228", "root", "Lzq@31508", "CMDB")

cursor = db.cursor()

sql_line = "select * from SERVERS " + sql

print(sql_line)

cursor.execute(sql_line)

results = cursor.fetchall()

if results:

for row in results:

server_id = row[0]

servername = row[1]

internal_ip = row[2]

online = row[3]

print("服务器编号=%d,服务器名=%s,内网地址=%s,是否在线=%d" % (server_id, servername, internal_ip, online))

sql_line = "select * from PROCESS where SERVER_ID = " + str(server_id)

cursor.execute(sql_line)

results = cursor.fetchall()

for row in results:

process_name = row[1]

master = row[4]

slave = row[5]

port = row[6]

print("process_name: %s, master: %d, slave: %d, port: %d" % (process_name, master, slave, port))

db.close()

return process_name, master, slave, port

else:

print("no data")

#检查服务器是否正常 

def check_servername_ping(servername):

cmd_line = "ping -c 1 -W 1 " + servername #使用ping命令检查

cmd_re = os.popen(cmd_line).readlines()

if 'rrt' in str(cmd_re):

print("机器可以正常PING ok...自动转换IP入")

ip = cmd_re[0].split()

ip = ip[2].replace("(", "")

ip = ip.replace(")", "")

print(ip)

return ip

else:

print("机器名无法PING通
请重新输入")

return 1

#检查服务器是否被注册 

def check_servername(servername):

db = pymysql.connect("192.168.1.228", "root", "Lzq@31508", "CMDB")

cursor = db.cursor()

re_sna = servername

commond = 'select * from SERVERS where SERVERNAME = ' + '"' + re_sna + '"'

cursor.execute(commond)

results = cursor.fetchall()

if not len(results) == 0:

print("服务器已经被注册")

return len(results)

if __name__ == '__main__': # 相当于主函数⼊⼝

select_level_1 = True

select_level_2 = True

input_Q_A = True

db_init()

fork.process(1) #调用fork.py的process方法,创建一个子进程,创建fork相当于将父进程复制了一份,生成了子进程。然后2个进程同时调用process方法,需要判断当前是否是子进程再执行

while select_level_1: #死循环,当循环内达到条件时再跳出

i = os.system("clear") #清理屏幕

select_level_1 = input("1:添加新服务器 2:服务器信息查询 3:服务部署 4:服务查询 5:新增服务项\n")

if select_level_1 == '1':        #输入1

while select_level_2: #死循环

servername = ''

servername = input("请输入机器名\n")

re_num = check_servername_ping(servername) #检查服务器是否正常

re_sna = check_servername(servername) #检查服务器是否被注册

if (not re_num == 1) and (re_sna == 0):

internal_ip = re_num

else:

continue

re_online = input("本机器是否已上线?(Y/N) \n") #确认本机是否上线

if re_online == 'Y':

online = 1

t = db_insert()

t.db_insert_servers(servername, internal_ip, online) #数据库登记服务器信息

print("新服务器已入库", servername)

skip = input("按任意键返回")

break

else:

online = 0 #服务器未上线

t = db_insert()

t.db_insert_servers(servername, internal_ip, online)

print("新服务器已入库", servername)

skip = input("按任务键返回")

break

if select_level_1 == '2': #输入2,查询服务器信息

print("服务器信息查询")

t = db_search()

t.db_search_servers()

skip = input("按任意键返回")

if select_level_1 == '3':     #输入3,服务部署

print("服务部署")

while select_level_2: #死循环

#######进程名

while input_Q_A:

os.system("clear")

process_name = input("请输入进程名\n") #输入部署的进程名

if process_name == '':

continue

else:

break

###### 进程部署到哪个服务器

while input_Q_A:

os.system("clear")

print("已输入进程名",process_name)

t = db_search()

max_server_id = t.db_search_servers() #输出当前最大的服务器id

print("输入范围 1 - %d"%(max_server_id))

server_id = input("请输入进程希望部署在哪台服务器(选择服务器编号)\n") #选择进程部署到哪台服务器

if server_id.isdigit(): #检查输入的字符是否是数字

pass

else:

continue

if int(server_id) <= max_server_id and int(server_id) > 0: #检查输入的id号是否在可用范围

break

else:

continue

###### 选择进程所属服务类型

while input_Q_A:

t = db_search()

max_server_id = t.db_search_servers()

service_id = input("请输入进程所属的服务类型编号\n")

if service_id.isdigit():

pass

else:

continue

if int(service_id) <= max_server_id and int(service_id) > 0:

break

else:

continue

while input_Q_A:

m_s_choice = input("本进程是否存在
主从关系?(Y/N)")

if m_s_choice == '':

continue

if m_s_choice == 'Y':

break

if m_s_choice == 'N':

break

else:

continue

while input_Q_A:

if m_s_choice == 'Y':

master = input("本进程是否为主?(Y/N)")

if master == 'Y':

master = 1

slave = 0

break

if master == 'N':

master = 0

slave = 1

break

else:

continue

else:

break

while input_Q_A:

port = input("请输入进程的端口号")

if port.isdigit():

pass

else:

print("端口号输入不合格(0-65535)")

continue

if int(port) <= 0 or int(port) > 65535:

print("端口号输入不合法(0-65535)")

continue

else:

break

online = 1

t = db_insert()

t.db_insert_process(process_name, int(service_id),int(service_id),int(master),int(slave),int(port),int(online)) #将选择的进程信息插入到数据库

print("进程信息录入完毕")

skip = input("请按任意键返回上层菜单")

break

if select_level_1 == '4':

print("查询服务所在部署的机器")

t = db_search()

service_name = input("请输入查询的服务,如redis、nginx\n")

print("查询结果如下")

t.db_search_service(service_name)

ret = input("任意键返回")

if ret:

continue

if select_level_1 == '5':

while select_level_2:

service_name = input("请输入新的服务名\n")

t = db_insert()

t.db_insert_service(service_name)

print("新服务名已入库",service_name)

skip = input("按任意键返回")

break

else:

select_level_1 = '0'

os.system("clear")

fork.py

python自动化运维之CMDB篇-大米哥

父进程记忆的是子进程id,子进程记忆的是父进程id

#!/usr/bin/python3

#coding: utf8

import os

import time

import server #调用server.py

def process(var):

print("current Process (%s) start ..."%(os.getpid()))

pid = os.fork() #创建一个子进程

print(pid)

#判断pid方式,确定当前在子进程,当在子进程中,开始调用server.server(1)。server.py

if pid < 0: #pid<0,代表主进程

print("error in fork")

elif pid == 0: #pid==0,代表子进程

print("I anm a child process (%s) and my parent process os(%s)"%(os.getpid(),os.getppid())) #getpid是子进程,getppid是父进程

a = 2

while a > 1:

time.sleep(1)

print("sleeping child!!~~~~")

a = a - 1

server.server(1) #调用server.py的server方法,建立socket连接,监听客户端访问。

else:

print("I (%s) created a child process (%s)."%(os.getpid(),pid))

server.py

服务器端跑的脚本

#!/usr/bin/python3

#coding: utf8

import socket

import sys

import cmdb #需要使用cmdb中的类

def server(var):

serversocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #创建服务端socket文件

host = socket.gethostname() #获取当前主机名

print(host)

port = 9999

serversocket.bind((host, port)) #将端口与主机名绑定

serversocket.listen(5) #开启监听端口port

while True:

clientsocket, addr = serversocket.accept() #解析监听到的客户端地址,和客户端socket通信对象

print("连接地址:%s" % str(addr))

ip1 = str(addr)

ip2 = ip1.split(",")

ip = ip2[0].replace("(", "")

t = cmdb.db_search() #创建cmdb.py的db_search类

sql = "where INTERNAL_IP = " + ip

process_name, master, slave, port = t.db_search_servers_for_agent_verify(sql) #查询客户端服务器信息

msg = ip + ' ' + process_name + ' ' + str(master) + ' ' + str(slave) + ' ' + str(port)

clientsocket.send(msg.encode('utf-8')) #将查询到的信息发送给客户端socker文件

clientsocket.close()

agent.py

客户端脚本

#!/usr/bin/python3

#coding: utf8

import socket

import os

import sys

import deployment

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #建立客户端socket文件

host = "192.168.1.227" #服务器端地址

port = 9999

s.connect((host, port)) #与服务器端建立连接

msg = s.recv(1024)     #接受服务端返回的数据

s.close()

print(msg.decode('utf-8'))

msg_list = msg.split()

ip = msg_list[0]

process_name = msg_list[1]

master = msg_list[2]

slave = msg_list[3]

port = msg_list[4]

print(ip)

print(process_name)

print(master)

print(slave)

print(port)

res = os.popen("cat /etc/crontab").readlines() #读取定时任务文件

tof = True

for a in res:

if "/root/python/agent.py" in a:

tof = False

break

if tof:

commond = 'echo " 5 * * * * root /usr/bin/python /root/python/agent.py" >> /etc/crontab' #如果没有写入定时任务,往定时任务中加入每5分钟运行一次agent脚本

os.popen(commond)

os.popen("systemctl restart crond")

t = deployment.deployment_redis() #调用deployment的脚本,创建redis部署对象

r = t.check_demo(1)

r = t.download(1)

r = t.unzip(1)

r = t.re_locate(1)

r = t.config_file_generating(ip, process_name, master, slave, port)

r = t.make_install(1)

r = t.start_redis(1)

deplogment.py

#coding:utf-8

#! /usr/bin/python3

# -*- coding: UTF-8 -*-

import os

import time

class deployment_redis: #定义一个类

def check_demo(self,var):

cmd_line = "ls /usr/local/redis/"

cmd_re = os.popen(cmd_line).readlines()
#linux命令行执行命令,获取返回结果

if cmd_re:

return

cmd_line ="netstat -tnlp |grep redis1"

cmd_line = os.popen(cmd_line).readline()

if cmd_re:

return

def download(self, var): #下载软件

# ftp://10.26.100.120/pub/redis.tar.gz and ftp://10.26.100.120/pub/redis.conf

cmd_line = "wget ftp://anonymous@192.168.1.227/pub/redis.tar.gz" #在服务端使用ftp下载

cmd_re = os.popen(cmd_line).readlines()

def unzip(self, var): #解压软件

cmd_line = "tar -xvzf redis.tar.gz && rm -rf redis.tar.gz"

cmd_re = os.popen(cmd_line).readlines()

cmd_line = "mv redis-4.0.8 redis"

cmd_re = os.popen(cmd_line).readlines()

def re_locate(self, var): #移动redis目录

prefix = "/usr/local/"

cmd_line = "mv redis " + prefix

cmd_re = os.popen(cmd_line).readlines()

def make_install(self,var): #安装

cmd_line = "cd /usr/local/redis ;make"

cmd_re = os.popen(cmd_line).readlines()

cmd_line = "yes|cp ./redis.conf /usr/local/redis/" #yes,拷贝redis配置文件

cmd_re = os.popen(cmd_line).readlines()

def start_redis(self,var): #开启redis实例

cmd_line = "/usr/local/redis/src/redis-server /usr/local/redis/redis.conf"

cmd_re = os.popen(cmd_line).readlines()

def config_file_generating(self, ip, process_name, master, slave, port): #打开redis配置文件写入配置,传递服务器参数

f
= open("redis.conf", "w")

# 关闭打开的⽂件

## REDIS CONFIGS

emp = {'bind':'10.26.100.120\n',\

'port':'50500\n',\

'pidfile' : '/data/.storage/redis/redis_50500m.redis1.pid\n',\

'logfile' : '/data/log/redis/redis_50500m.redis1.log\n' ,\

'dir' : '/data/.storage/redis/\n' ,\

'dbfilename' : 'redis_50500m.redis1.dump.rdb\n' ,\

'slaveof' : 'redis1 50500\n' ,\

'masterauth' : 'Np3jftX7808X\n' }

print(ip)

print(process_name)

print(master)

print(slave)

print(port)

new_ip = str(bytes.decode(ip)).strip("'") #将传递的ip参数编码,写入到emp字典

str1 = new_ip + '\n'

emp['bind'] = str1

str1 = bytes.decode(port) + '\n'

emp['port'] = str1

#如果是主服务器,就删掉slaveof这一项
可以添加如果是非

if master == '1':

del emp['slaveof'] #删除字典的从信息

master = 'm'

str1 = "/data/.storage/redis/redis_" + bytes.decode(port) + bytes.decode(master) + ".redis1.pid" + "\n" #pid文件路径

emp['pidfile'] = str1

str1 = "/data/log/redis/redis_" + bytes.decode(port) + bytes.decode(master) + ".redis1.log" + "\n" #日志文件路径

emp['logfile'] = str1

for k, v in emp.items():

print('{v} = {k}'.format(v = v, k = k))

config_str = k + ' ' + v

f.write(config_str)

#
将emp字典,键值对组合成字符串写入到f对象中,即打开的redis.conf

emp2 = "protected-mode yes\n\

tcp-backlog 511\n\

timeout 0\n\

tcp-keepalive 300\n\

daemonize yes\n\

supervised no\n\

loglevel notice\n\

databases 16\n\

always-show-logo yes\n\

save 900 1\n\

save 300 10\n\

save 60 10000\n\

stop-writes-on-bgsave-error yes\n\

rdbcompression yes\n\

rdbchecksum yes\n\

slave-serve-stale-data yes\n\

slave-read-only no\n\

repl-diskless-sync no\n\

repl-diskless-sync-delay 5\n\

repl-disable-tcp-nodelay no\n\

slave-priority 100\n\

lazyfree-lazy-eviction no\n\

lazyfree-lazy-expire no\n\

lazyfree-lazy-server-del no\n\

slave-lazy-flush no\n\

appendonly no\n\

appendfilename appendonly.aof\n\

appendfsync everysec\n\

no-appendfsync-on-rewrite no\n\

auto-aof-rewrite-percentage 100\n\

auto-aof-rewrite-min-size 64mb\n\

aof-load-truncated yes\n\

aof-use-rdb-preamble no\n\

lua-time-limit 5000\n\

slowlog-log-slower-than 10000\n\

slowlog-max-len 128\n\

latency-monitor-threshold 0\n\

notify-keyspace-events \"\"\n\

hash-max-ziplist-entries 512\n\

hash-max-ziplist-value 64\n\

list-max-ziplist-size -2\n\

list-compress-depth 0\n\

set-max-intset-entries 512\n\

zset-max-ziplist-entries 128\n\

zset-max-ziplist-value 64\n\

hll-sparse-max-bytes 3000\n\

activerehashing yes\n\

client-output-buffer-limit normal 0 0 0\n\

client-output-buffer-limit slave 256mb 64mb 60\n\

client-output-buffer-limit pubsub 32mb 8mb 60\n\

hz 10\n\

aof-rewrite-incremental-fsync yes\n\

"

print(emp2)

prefix = "/data/log/redis/"

cmd_line = "mkdir -p " + prefix #创建redis日志目录

cmd_re = os.popen(cmd_line).readlines()

prefix = "/data/.storage/redis/"

cmd_line = "mkdir -p " + prefix

cmd_re = os.popen(cmd_line).readlines()

f.write(emp2) #将emp2字符串,即redis其他配置属性加入到redis.conf

f.close()