利用 Python 实现 Nginx 启动/重启等一些操作

程序主文件 Nginx.py

#!/usr/bin/python
# _*_coding:utf-8_*_
# __author__ = 'yulong'
# Good memory than rotten written
import subprocess
import sys
import os
import ConfigParserclass Nginx(object):conf = ConfigParser.ConfigParser()conf.read('Nginx_conf.ini')# 查看nginx进程def check_nginx_process(self):# 运行查看Linux Nginx进程command = "%s" % (self.conf.get('global', 'nginx_process'))print "\033[32m########################Nginx Process########################\033[0m"subprocess.call(command, shell=True)print "\033[32m#########################################################\033[0m"# 启动Nginxdef start_nginx(self):# 启动Nginxcommand = "%s %s %s" % (self.conf.get('global', 'nginx_bin_home'), self.conf.get('global', 'nginx_start_options'),self.conf.get('global', 'nginx_config'))print "\033[32m########################Nginx Starting########################\033[0m"start_nginx = subprocess.Popen(command, shell=True)start_nginx.wait()'''启动需要进行判断,因为关闭掉nginx后nginx.pid不会删除,会保留上一次的pid'''# 获取nginx.pid的值# 存放临时取出的pidfiles_pid = []run_pid = []# 获取pid文件中的值存放到files_pid中command_files_pid = "%s" % (self.conf.get('global', 'nginx_process_pid'))outs = subprocess.Popen(command_files_pid, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)for line in outs.stdout.readlines():files_pid.append(line.strip())# 获取正在运行的PID存放到run_pid中command_running_pid = "%s" % (self.conf.get('global', 'nginx_get_runing_pid'))outs_pid = subprocess.Popen(command_running_pid, shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT)for line in outs_pid.stdout.readlines():run_pid.append(line.strip())# 进行判断文件中的Pid是否存在与正在运行的pid中try:if files_pid[0] in run_pid:print "\033[32m----------Staring Nginx Successful----------\033[0m"else:print "\033[31m----------Staring Nginx Failed----------\033[0m"except IndexError:print "\033[31m----------The Server Is Not Exist----------\033[0m"# 平滑重启Ningxdef reload_nginx(self):command_reload = "%s %s" % (self.conf.get('global', 'nginx_bin_home'), self.conf.get('global', 'nginx_reload'))print "\033[32m########################Nginx Reload########################\033[0m"subprocess.call(command_reload, shell=True)print "\033[32m#########################################################\033[0m"# 停止Ningx,处理完当前请求后进行重启def stop_nginx(self):command_stop_request = "%s" % (self.conf.get('global', 'nginx_normal_stop'))print "\033[32m########################Nginx Stop(Request)########################\033[0m"request = subprocess.Popen(command_stop_request, shell=True)print "\033[32mStoping............."request.wait()if request.returncode == 0:print "\033[32m---------Stop Nginx Successful---------\033[0m"else:print "\033[31m---------Stop Nginx Failed-------------\033[0m"# 快速停止Nginxdef fast_stop_nginx(self):command_Fast = "%s" % (self.conf.get('global', 'nginx_fast_stop'))print "\033[32m########################Nginx Fast Stop########################\033[0m"fast_stop = subprocess.Popen(command_Fast, shell=True)fast_stop.wait()if fast_stop.returncode == 0:print "\033[32m Fast Stop Nginx Successful\033[0m"else:print "\033[32m Fast Stop Nginx Failed\033[0m"print "\033[32m#########################################################\033[0m"# 显示Nginx的配置文件内容def view_nginx_conf(self):# 显示Nginx的配置文件内容command = "%s %s" % (self.conf.get('global', 'nginx_bin_home'), (self.conf.get('global', 'nginx_conf_view')))print "\033[32m########################配置文件为########################\033[0m"subprocess.call(command, shell=True)print "\033[32m#########################################################\033[0m"# 检测Ningx配置文件def check_nginx_conf(self):# 检测nginx的完整配置信息command = "%s %s %s" % (self.conf.get('global', 'nginx_bin_home'), self.conf.get('global', 'nginx_config_test'),self.conf.get('global', 'nginx_config'))print "\033[32m########################检测结果为########################\033[0m"subprocess.call(command, shell=True)print "\033[32m#########################################################\033[0m"# 查看Ningx所有信息def check_nginx_info(self):# 查看nginx完整配置信息command = "%s %s" % (self.conf.get('global', 'nginx_bin_home'), self.conf.get('global', 'nginx_info'))print "\033[32m########################Nginx Info########################\033[0m"subprocess.call(command, shell=True)print "\033[32m##########################################################\033[0m"# ip地址列表# 统计Nginx日志内的访问IPdef nginx_accessnum(self):dir = "%s" % self.conf.get('global', 'Nginx_logs_path')files = os.listdir(dir)print "\033[32m*******************日志目录下的文件内容为*******************\033[0m"for f in files:print dir + os.sep + f# ip地址列表ip_list = []log_pat = raw_input("Please Input Logs Path:").strip()command_num = "cat %s  | awk '{print $1,$6}' > list.txt" % log_patcommand = subprocess.Popen(command_num, shell=True)command.wait()f = file("list.txt", "r")for line in f.readlines():ip_list.append(line.strip())print "\033[31m Nginx总的访问次数为:\033[0m", len(ip_list), "\n"# 首先遍历set集合,以遍历到的元素为值传给统计列表函数# 首先转换ip_list类型ip_set = set(ip_list)access_max = int(raw_input("请输入你过滤的访问次数:"))print "\033[32m超过 %s 次访问的IP \033[0m --------\033[32m 访问次服务器的次数为:\033[0m" % access_maxfor item in ip_set:if ip_list.count(item) > access_max:print item, "--------------------", ip_list.count(item)f.close()if __name__ == "__main__":help_com = """\033[32mps:查看Nginx当前进程start:启动Nginx服务reload:平滑重启Nginx服务(重新读取配置文件)stop:停止Nginx服务(处理完当前的请求后关闭Ningx)kill:×快速停止Nginx服务(不保存相关信息)config:显示Nginx配置文件test:测试Nginx配置文件-V:显示Nginx的所有信息access:统计访问日志的ip\033[0m"""run = Nginx()try:if sys.argv[1] == 'ps':run.check_nginx_process()elif sys.argv[1] == 'start':run.start_nginx()elif sys.argv[1] == 'reload':run.reload_nginx()elif sys.argv[1] == 'stop':run.stop_nginx()elif sys.argv[1] == 'kill':run.fast_stop_nginx()elif sys.argv[1] == 'config':run.view_nginx_conf()elif sys.argv[1] == 'test':run.check_nginx_conf()elif sys.argv[1] == '-V':run.check_nginx_info()elif sys.argv[1] == 'access':run.nginx_accessnum()elif sys.argv[1] == '--help':print help_comexcept IndexError:print help_com

程序配置文件 Nginx_conf.ini

[global]
#Nginx配置文件路径
nginx_config = /usr/local/nginx/conf/nginx.conf
#Nginx脚本存放路径
nginx_bin_home = /usr/local/nginx/sbin/nginx
#Nginx日志存放路径
Nginx_logs_path = /software/tengine/logs
#Nginx启动制定配置文件参数
nginx_start_options = -c
#Nginx进程信息
nginx_process = ps aux | grep nginx | grep -v "grep"
#获取正在运行的pid
nginx_get_runing_pid = ps aux | grep nginx | grep -v "grep" |awk '{print $2}'
#Nginx_pid===查看files
nginx_process_pid = cat /software/nginx.pid
#Nginx平滑启动参数
nginx_reload = -s reload
#Nginx停止,处理完当前请求关闭Nginx
nginx_normal_stop = kill -QUIT `cat /software/nginx.pid`
#Nginx快速停止
nginx_fast_stop = kill -TERM `cat /software/nginx.pid`
#Nginx配置文件检测参数
nginx_config_test = -t -c
#Nginx所有信息查看参数
nginx_info = -V
#Nginx显示配置文件
nginx_conf_view = -d

以上实现了一些基本的 Nginx 操作,练习一下 Python

转载于:https://blog.51cto.com/edward110/1706436

Python_Nginx相关推荐

  1. nginx fastcgi python_Nginx + webpy 和FastCGI搭建webpy环境

    web.py 是一个轻量级Python web框架,它简单而且功能大.web.py是一个开源项目. 1.所需要的软件: Nginx nginx-1.4.7.tar.gz (需要包含fastcgi和re ...

  2. nginx配合python_Nginx基本配置

    Nginx基础 1.nginx启动的2种方式 这2种方式不能混用,只能用一种 ## 第一种:(适合源码编译安装) nginx启动 nginx -s stop停止 nginx -s reload | r ...

最新文章

  1. 1045 Favorite Color Stripe(LIS解法)
  2. 软件篇:程序员如何提升自己的技能
  3. S3C2440 SDRAM内存驱动 .
  4. [Ynoi2019模拟赛]Yuno loves sqrt technology II
  5. selenium代码练习
  6. 付力力: 基于 ImpalaS 构建实时用户行为分析引擎
  7. unity3D游戏开发三之unity编辑器二
  8. [蓝桥杯][2017年第八届真题]拉马车(String)
  9. 读Getting Started With Windows PowerShell笔记
  10. 深度学习之 RPN(RegionProposal Network)- 区域候选网络
  11. 请举例说明python中**运算符的含义_举例讲解Python中的身份运算符的使用方法
  12. Django模板:url反向解析
  13. sql执行组件是灰色的_如何分析SQL执行计划图形组件
  14. csrf攻击ajax,如何在使用ajax post时处理CSRF攻击?
  15. 死磕 18 个 Java 8 的日期处理,工作必用!
  16. oracle多列转换成树结构,如何将树“压缩”为Oracle中层次结构上的聚合数据?
  17. 性能测试场景设计之用户启停设置
  18. Linux基础——GCC编译器
  19. 电子版2寸照片的像素是多少
  20. idea 提示Expecting newline or semicolon解决办法

热门文章

  1. 网络编程学习笔记(IPv4套接口选项)
  2. mysql里的ibdata1文件
  3. Django--models一对多实例
  4. 《Java程序书面采访猿收藏》之 instanceof的作用是什么
  5. 利用python3.x实现小爬虫下载贴吧内图片
  6. xcode 4.5 new feature __ ios6 新特性
  7. PHP之preg_replace()与ereg_replace()正则匹配比较讲解
  8. VS2005下开发PPC2003和WM50编译器一些设置
  9. 利用最大熵进行阈值分割从而实现灰度图像的二值化的原理概要及OpenCV代码
  10. 事实证明,OpenCV中对RGB图像数据的存储顺序是BGR,而且Scalar()的顺序也是B,G,R