本文共 9130 字,大约阅读时间需要 30 分钟。
#!/usr/bin/env python3#-*- coding = utf-8 -*-import subprocessimport ostry: import distroexcept Exception: os.system('/usr/bin/pip3 install distro')import distrofrom time import sleep#检测当前是什么操作系统def checksystem(): if 'Ubuntu' in distro.linux_distribution(): release = 'ubuntu' elif 'CentOS Linux' in distro.linux_distribution(): release = 'centos' return release#检测curldef checkUrl(): release=checksystem() if os.system('ls /usr/bin/curl | grep -Eqi curl') == 0: pass else: print(' 正在安装 Curl') if release == 'centos': os.system('yum -y update') os.system('yum -y install curl') else: os.system('apt-get -y update') os.system('apt-get -y install curl')#检测wegtdef checkWget(): release=checksystem() if os.system('ls /usr/bin/wget | grep -Eqi wget') == 0: pass else: print(' 正在安装 Wget') if release == 'centos': os.system('yum -y update') os.system('yum -y install wget') else: os.system('apt-get -y update') os.system('apt-get -y install wget')#检测tardef checkTar(): release=checksystem() if os.system('ls /usr/bin/tar | grep -Eqi tar') == 0: pass else: print(' 正在安装 tar') if release == 'centos': os.system('yum -y update') os.system('yum -y install tar') else: os.system('apt-get -y update') os.system('apt-get -y install tar')# 安装redisdef creat_redis(hots_IP,passwd): if not os.path.exists('/opt/tools'): os.makedirs('/opt/tools') os.chdir('/opt/tools') release=checksystem() if release == 'centos': os.system('yum -y install gcc make') write_redis(hots_IP,passwd) sleep(2) redis_cluster(hots_IP) print('\33[32;1m redis已完成安装,目录文件在:/etc/redis,启动命令在:/usr/local/redis/bin\33[0m') else: os.system('apt-get -y install gcc make') write_redis(hots_IP,passwd) sleep(2) redis_cluster(hots_IP) print('\33[32;1m redis已完成安装,目录文件在:/etc/redis,启动命令在:/usr/local/redis/bin\33[0m')def write_redis(hots_IP,passwd): os.system('wget http://download.redis.io/releases/redis-6.2.0.tar.gz') os.system('tar -xzf redis-6.2.0.tar.gz -C /usr/local/') os.chdir('/usr/local/redis-6.2.0/') os.system('make && make install') #拷贝到环境变量 os.chdir('/usr/local/redis-6.2.0/src') os.system('cp redis-cli redis-server redis-sentinel /usr/bin/') # os.system('echo "export PATH=\"$PATH:/usr/local/redis-6.2.0/bin\"" >> /etc/profile') # os.system('source /etc/profile') #创建目录 os.system('mkdir -p /etc/redis/{conf,log,pid,redis6981,redis6982,redis6983,sentinel26981,sentinel26982,sentinel26983}') #编写配置文件 with open('/etc/redis/conf/redis6981.conf','w+',encoding='utf-8') as rd: rd.write('''##########################################redis.conf############################################bind 0.0.0.0protected-mode noport 6981tcp-backlog 511unixsocket "/tmp/redis6981.sock"unixsocketperm 700timeout 0tcp-keepalive 300daemonize yessupervised nopidfile "/etc/redis/pid/redis_6981.pid"loglevel noticelogfile "/etc/redis/log/redis6981.log"databases 16always-show-logo yes################################# 持久化配置 ##################################RDB 快照持久化save 900 1save 300 10save 60 10000stop-writes-on-bgsave-error yesrdbcompression yesrdbchecksum yesdbfilename "dump6981.rdb"dir "/etc/redis/redis6981"#AOF 持久化appendonly noappendfilename "appendonly.aof"appendfsync everysecno-appendfsync-on-rewrite noauto-aof-rewrite-percentage 100auto-aof-rewrite-min-size 64mbaof-load-truncated yesaof-use-rdb-preamble yesaof-rewrite-incremental-fsync yes################################# 主从配置 #################################masterauth "{}"replica-serve-stale-data yesreplica-read-only yesrepl-diskless-sync norepl-diskless-sync-delay 5repl-disable-tcp-nodelay norepl-backlog-size 10mbrepl-backlog-ttl 3600################################## 安全认证 ###################################requirepass "{}"rename-command CONFIG "b840fc02d524045429941cc43f59e41cb7be6c52"################################### 连接配置 ####################################maxclients 10000############################# 懒惰的释放 ####################################lazyfree-lazy-eviction nolazyfree-lazy-expire nolazyfree-lazy-server-del noreplica-lazy-flush no################################ LUA SCRIPTING ###############################lua-time-limit 5000############################### 慢日志 ################################slowlog-log-slower-than 10000slowlog-max-len 128#rejson.so#loadmodule /usr/local/redis-6.2.0/module/rejson.soo######################### 高级设置 #########################activerehashing yes#缓存空间限制client-output-buffer-limit normal 0 0 0client-output-buffer-limit slave 1024mb 256mb 300client-output-buffer-limit pubsub 32mb 8mb 60client-query-buffer-limit 1gb#加快写入rdb 和aofaof-rewrite-incremental-fsync yesrdb-save-incremental-fsync yes'''.format(passwd,passwd)) with open('/etc/redis/conf/sentinel26981.conf','w+',encoding='utf-8') as rs: rs.write('''################################sentnel.conf########################################port 26981daemonize yespidfile "/etc/redis/pid/redis-sentinel26981.pid"logfile "/etc/redis/log/sentinel26981.log"dir "/etc/redis/sentinel26981"sentinel deny-scripts-reconfig yessentinel monitor mymaster {} 6981 2sentinel auth-pass mymaster {}'''.format(hots_IP,passwd))#拷贝配置文件,并启动def redis_cluster(hots_IP): os.chdir('/etc/redis/conf') for conf_id in [2,3]: # 拷贝文件 os.system('cp redis6981.conf redis698{}.conf'.format(conf_id)) os.system('cp sentinel26981.conf sentinel2698{}.conf'.format(conf_id)) # 修改配置文件 os.system('''sed -i '/6981/s/6981/698{}/' redis698{}.conf'''.format(conf_id,conf_id)) os.system('''sed -i '/26981/s/26981/2698{}/' sentinel2698{}.conf'''.format(conf_id,conf_id)) # 配置从 os.system('''sed -i '/masterauth/i\slaveof {} 6981' redis698{}.conf'''.format(hots_IP,conf_id))#创建service 文件def service_file(local): #创建redis的service文件 with open('{}redis1.service'.format(local),'w', encoding='utf-8') as f: f.write('''[Unit]Description=redis1After=network.target remote-fs.target nss-lookup.target[Service]Type=forkingExecStart=/usr/bin/redis-server /etc/redis/conf/redis6981.confExecReload=/bin/kill -s HUP $MAINPIDExecStop=/usr/bin/redis-cli -p 6981 -a {} shutdownPrivateTmp=true[Install]WantedBy=multi-user.target'''.format(passwd)) #创建sentinel的service文件 with open('{}sentinel1.service'.format(local),'w', encoding='utf-8') as f: f.write('''[Unit]Description=redis-sentinelAfter=network.target remote-fs.target nss-lookup.target[Service]Type=forkingExecStart=/usr/bin/redis-sentinel /etc/redis/conf/sentinel26981.confExecReload=/bin/kill -s HUP $MAINPIDExecStop=/usr/bin/redis-cli -p 26981 shutdownPrivateTmp=true[Install]WantedBy=multi-user.target''') #修改service文件 os.chdir('{}'.format(local)) for ints in [2,3]: os.system('cp redis1.service redis{}.service'.format(ints)) os.system('cp sentinel1.service sentinel{}.service'.format(ints)) os.system('''sed -i '/6981/s/6981/698{}/' redis{}.service'''.format(ints,ints)) os.system('''sed -i '/26981/s/26981/2698{}/' sentinel{}.service'''.format(ints,ints)) os.system('systemctl daemon-reload') #开机自启 for ents in [1,2,3]: os.system('systemctl enable redis{}.service'.format(ents)) os.system('systemctl enable sentinel{}.service'.format(ents)) #systemd 管理服务def systemd_redis(passwd): release = checksystem() if release == 'centos': local='/usr/lib/systemd/system/' service_file(local) else: local='/lib/systemd/system/' service_file(local)#创建起停控制脚本def start_and_stop(passwd): os.chdir('/opt') with open('./redis.py','w',encoding='utf-8') as rs: rs.write('''#!/usr/bin/env python3import sysimport ostry: if sys.argv[1] == 'start': for start_id in [1,2,3]: os.system('redis-server /etc/redis/conf/redis698{}.conf'.format(start_id)) print(' start redis 698{} '.format(start_id)) os.system('redis-sentinel /etc/redis/conf/sentinel2698{}.conf'.format(start_id)) print(' start sentinel 2698{} '.format(start_id)) elif sys.argv[1] == 'stop': passwd='%s' for stop_id in [1,2,3]: os.system('redis-cli -p 698{} -a {} shutdown >/dev/null 2>&1 &'.format(stop_id,passwd)) print(' stop redis 698{} '.format(stop_id)) os.system('redis-cli -p 2698{} shutdown >/dev/null 2>&1 &'.format(stop_id)) print(' stop sentinel 2698{} '.format(stop_id)) else: print(' Please enter start | stop ')except Exception as e: print(' Error is {} '.format(e))''' %(passwd)) os.system('chmod u+x redis.py') print('\33[32;1m 启动控制脚本 python3 /opt/redis.py \33[0m')if __name__=='__main__': checkUrl() checkWget() checkTar() #主机IP hots_IP='192.168.88.155' #redis密码 passwd='1' creat_redis(hots_IP,passwd) #systemd管理 systemd_redis(passwd) start_and_stop(passwd)
转载地址:http://ameh.baihongyu.com/