pull/109/head
Mr Chen 7 years ago
parent e2e88df295
commit b92be80c36
  1. 46
      class/db.py
  2. 109
      class/page.py
  3. 56
      class/public.py
  4. 618
      class/system.py
  5. 1
      plugins/nginx/info.json
  6. 1609
      static/js/files.js
  7. 2
      task.py

@ -1,15 +1,10 @@
# coding: utf-8 # coding: utf-8
# +-------------------------------------------------------------------
# | 宝塔Linux面板
# +-------------------------------------------------------------------
# | Copyright (c) 2015-2016 宝塔软件(http://bt.cn) All rights reserved.
# +-------------------------------------------------------------------
# | Author: 黄文良 <287962566@qq.com>
# +-------------------------------------------------------------------
import sqlite3 import sqlite3
import os import os
class Sql(): class Sql():
#------------------------------ #------------------------------
# 数据库操作类 For sqlite3 # 数据库操作类 For sqlite3
@ -43,7 +38,6 @@ class Sql():
self.__DB_TABLE = table self.__DB_TABLE = table
return self return self
def where(self, where, param): def where(self, where, param):
# WHERE条件 # WHERE条件
if where: if where:
@ -51,33 +45,30 @@ class Sql():
self.__OPT_PARAM = param self.__OPT_PARAM = param
return self return self
def order(self, order): def order(self, order):
# ORDER条件 # ORDER条件
if len(order): if len(order):
self.__OPT_ORDER = " ORDER BY " + order self.__OPT_ORDER = " ORDER BY " + order
return self return self
def limit(self, limit): def limit(self, limit):
# LIMIT条件 # LIMIT条件
if len(limit): if len(limit):
self.__OPT_LIMIT = " LIMIT " + limit self.__OPT_LIMIT = " LIMIT " + limit
return self return self
def field(self, field): def field(self, field):
# FIELD条件 # FIELD条件
if len(field): if len(field):
self.__OPT_FIELD = field self.__OPT_FIELD = field
return self return self
def select(self): def select(self):
# 查询数据集 # 查询数据集
self.__GetConn() self.__GetConn()
try: try:
sql = "SELECT " + self.__OPT_FIELD + " FROM " + self.__DB_TABLE + self.__OPT_WHERE + self.__OPT_ORDER + self.__OPT_LIMIT sql = "SELECT " + self.__OPT_FIELD + " FROM " + self.__DB_TABLE + \
self.__OPT_WHERE + self.__OPT_ORDER + self.__OPT_LIMIT
result = self.__DB_CONN.execute(sql, self.__OPT_PARAM) result = self.__DB_CONN.execute(sql, self.__OPT_PARAM)
data = result.fetchall() data = result.fetchall()
# 构造字曲系列 # 构造字曲系列
@ -104,20 +95,17 @@ class Sql():
except Exception, ex: except Exception, ex:
return "error: " + str(ex) return "error: " + str(ex)
def getField(self, keyName): def getField(self, keyName):
# 取回指定字段 # 取回指定字段
result = self.field(keyName).select(); result = self.field(keyName).select()
if len(result) == 1: if len(result) == 1:
return result[0][keyName] return result[0][keyName]
return result return result
def setField(self, keyName, keyValue): def setField(self, keyName, keyValue):
# 更新指定字段 # 更新指定字段
return self.save(keyName, (keyValue,)) return self.save(keyName, (keyValue,))
def find(self): def find(self):
# 取一行数据 # 取一行数据
result = self.limit("1").select() result = self.limit("1").select()
@ -125,7 +113,6 @@ class Sql():
return result[0] return result[0]
return result return result
def count(self): def count(self):
# 取行数 # 取行数
key = "COUNT(*)" key = "COUNT(*)"
@ -135,7 +122,6 @@ class Sql():
except: except:
return 0 return 0
def add(self, keys, param): def add(self, keys, param):
# 插入数据 # 插入数据
self.__GetConn() self.__GetConn()
@ -144,8 +130,9 @@ class Sql():
values = "" values = ""
for key in keys.split(','): for key in keys.split(','):
values += "?," values += "?,"
values = self.checkInput(values[0:len(values)-1]); values = self.checkInput(values[0:len(values) - 1])
sql = "INSERT INTO "+self.__DB_TABLE+"("+keys+") "+"VALUES("+values+")" sql = "INSERT INTO " + self.__DB_TABLE + \
"(" + keys + ") " + "VALUES(" + values + ")"
result = self.__DB_CONN.execute(sql, param) result = self.__DB_CONN.execute(sql, param)
id = result.lastrowid id = result.lastrowid
self.__close() self.__close()
@ -155,8 +142,10 @@ class Sql():
return "error: " + str(ex) return "error: " + str(ex)
def checkInput(self, data): def checkInput(self, data):
if not data: return data; if not data:
if type(data) != str: return data; return data
if type(data) != str:
return data
checkList = [ checkList = [
{'d': '<', 'r': ''}, {'d': '<', 'r': ''},
{'d': '>', 'r': ''}, {'d': '>', 'r': ''},
@ -167,8 +156,8 @@ class Sql():
{'d': '<', 'r': ''} {'d': '<', 'r': ''}
] ]
for v in checkList: for v in checkList:
data = data.replace(v['d'],v['r']); data = data.replace(v['d'], v['r'])
return data; return data
def addAll(self, keys, param): def addAll(self, keys, param):
# 插入数据 # 插入数据
@ -179,7 +168,8 @@ class Sql():
for key in keys.split(','): for key in keys.split(','):
values += "?," values += "?,"
values = values[0:len(values) - 1] values = values[0:len(values) - 1]
sql = "INSERT INTO "+self.__DB_TABLE+"("+keys+") "+"VALUES("+values+")" sql = "INSERT INTO " + self.__DB_TABLE + \
"(" + keys + ") " + "VALUES(" + values + ")"
result = self.__DB_CONN.execute(sql, param) result = self.__DB_CONN.execute(sql, param)
return True return True
except Exception, ex: except Exception, ex:
@ -189,7 +179,6 @@ class Sql():
self.__close() self.__close()
self.__DB_CONN.commit() self.__DB_CONN.commit()
def save(self, keys, param): def save(self, keys, param):
# 更新数据 # 更新数据
self.__GetConn() self.__GetConn()
@ -231,7 +220,6 @@ class Sql():
except Exception, ex: except Exception, ex:
return "error: " + str(ex) return "error: " + str(ex)
def execute(self, sql, param): def execute(self, sql, param):
# 执行SQL语句返回受影响行 # 执行SQL语句返回受影响行
self.__GetConn() self.__GetConn()
@ -242,7 +230,6 @@ class Sql():
except Exception, ex: except Exception, ex:
return "error: " + str(ex) return "error: " + str(ex)
def query(self, sql, param): def query(self, sql, param):
# 执行SQL语句返回数据集 # 执行SQL语句返回数据集
self.__GetConn() self.__GetConn()
@ -287,4 +274,3 @@ class Sql():
self.__DB_CONN = None self.__DB_CONN = None
except: except:
pass pass

@ -1,12 +1,9 @@
# coding: utf-8 # coding: utf-8
# +-------------------------------------------------------------------
# | 宝塔Linux面板 import math
# +------------------------------------------------------------------- import string
# | Copyright (c) 2015-2016 宝塔软件(http://bt.cn) All rights reserved. import public
# +-------------------------------------------------------------------
# | Author: 黄文良 <2879625666@qq.com>
# +-------------------------------------------------------------------
import math,string,public
class Page(): class Page():
#-------------------------- #--------------------------
@ -32,16 +29,16 @@ class Page():
__END_NUM = None # 结束行 __END_NUM = None # 结束行
def __init__(self): def __init__(self):
tmp = public.getMsg('PAGE'); tmp = public.getMsg('PAGE')
if tmp: if tmp:
self.__PREV = tmp['PREV']; self.__PREV = tmp['PREV']
self.__NEXT = tmp['NEXT']; self.__NEXT = tmp['NEXT']
self.__START = tmp['START']; self.__START = tmp['START']
self.__END = tmp['END']; self.__END = tmp['END']
self.__COUNT_START = tmp['COUNT_START']; self.__COUNT_START = tmp['COUNT_START']
self.__COUNT_END = tmp['COUNT_END']; self.__COUNT_END = tmp['COUNT_END']
self.__FO = tmp['FO']; self.__FO = tmp['FO']
self.__LINE = tmp['LINE']; self.__LINE = tmp['LINE']
def GetPage(self, pageInfo, limit='1,2,3,4,5,6,7,8'): def GetPage(self, pageInfo, limit='1,2,3,4,5,6,7,8'):
# 取分页信息 # 取分页信息
@ -72,43 +69,51 @@ class Page():
pages['5'] = self.__GetEnd() pages['5'] = self.__GetEnd()
# 当前显示页与总页数 # 当前显示页与总页数
pages['6'] = "<span class='Pnumber'>" + bytes(self.__C_PAGE) + "/" + bytes(self.__COUNT_PAGE) + "</span>" pages['6'] = "<span class='Pnumber'>" + \
bytes(self.__C_PAGE) + "/" + bytes(self.__COUNT_PAGE) + "</span>"
# 本页显示开始与结束行 # 本页显示开始与结束行
pages['7'] = "<span class='Pline'>" + self.__FO + bytes(self.__START_NUM) + "-" + bytes(self.__END_NUM) + self.__LINE + "</span>" pages['7'] = "<span class='Pline'>" + self.__FO + \
bytes(self.__START_NUM) + "-" + \
bytes(self.__END_NUM) + self.__LINE + "</span>"
# 行数 # 行数
pages['8'] = "<span class='Pcount'>" + self.__COUNT_START + bytes(self.__COUNT_ROW) + self.__COUNT_END + "</span>" pages['8'] = "<span class='Pcount'>" + self.__COUNT_START + \
bytes(self.__COUNT_ROW) + self.__COUNT_END + "</span>"
# 构造返回数据 # 构造返回数据
retuls = '<div>'; retuls = '<div>'
for value in keys: for value in keys:
retuls += pages[value] retuls += pages[value]
retuls +='</div>'; retuls += '</div>'
# 返回分页数据 # 返回分页数据
return retuls; return retuls
def __GetEnd(self): def __GetEnd(self):
# 构造尾页 # 构造尾页
endStr = "" endStr = ""
if self.__C_PAGE >= self.__COUNT_PAGE: if self.__C_PAGE >= self.__COUNT_PAGE:
endStr = ''; endStr = ''
else: else:
if self.__RTURN_JS == "": if self.__RTURN_JS == "":
endStr = "<a class='Pend' href='" + self.__URI + "p=" + bytes(self.__COUNT_PAGE) + "'>" + self.__END + "</a>" endStr = "<a class='Pend' href='" + self.__URI + "p=" + \
bytes(self.__COUNT_PAGE) + "'>" + self.__END + "</a>"
else: else:
endStr = "<a class='Pend' onclick='" + self.__RTURN_JS + "(" + bytes(self.__COUNT_PAGE) + ")'>" + self.__END + "</a>" endStr = "<a class='Pend' onclick='" + self.__RTURN_JS + \
"(" + bytes(self.__COUNT_PAGE) + ")'>" + self.__END + "</a>"
return endStr return endStr
def __GetNext(self): def __GetNext(self):
# 构造下一页 # 构造下一页
nextStr = "" nextStr = ""
if self.__C_PAGE >= self.__COUNT_PAGE: if self.__C_PAGE >= self.__COUNT_PAGE:
nextStr = ''; nextStr = ''
else: else:
if self.__RTURN_JS == "": if self.__RTURN_JS == "":
nextStr = "<a class='Pnext' href='" + self.__URI + "p=" + bytes(self.__C_PAGE + 1) + "'>" + self.__NEXT + "</a>" nextStr = "<a class='Pnext' href='" + self.__URI + "p=" + \
bytes(self.__C_PAGE + 1) + "'>" + self.__NEXT + "</a>"
else: else:
nextStr = "<a class='Pnext' onclick='" + self.__RTURN_JS + "(" + bytes(self.__C_PAGE + 1) + ")'>" + self.__NEXT + "</a>" nextStr = "<a class='Pnext' onclick='" + self.__RTURN_JS + \
"(" + bytes(self.__C_PAGE + 1) + ")'>" + self.__NEXT + "</a>"
return nextStr return nextStr
@ -118,64 +123,74 @@ class Page():
num = 0 num = 0
# 当前页之前 # 当前页之前
if (self.__COUNT_PAGE - self.__C_PAGE) < self.__LIST_NUM: if (self.__COUNT_PAGE - self.__C_PAGE) < self.__LIST_NUM:
num = self.__LIST_NUM + (self.__LIST_NUM - (self.__COUNT_PAGE - self.__C_PAGE)); num = self.__LIST_NUM + \
(self.__LIST_NUM - (self.__COUNT_PAGE - self.__C_PAGE))
else: else:
num = self.__LIST_NUM num = self.__LIST_NUM
n = 0 n = 0
for i in range(num): for i in range(num):
n = num - i n = num - i
page = self.__C_PAGE - n; page = self.__C_PAGE - n
if page > 0: if page > 0:
if self.__RTURN_JS == "": if self.__RTURN_JS == "":
pages += "<a class='Pnum' href='" + self.__URI + "p=" + bytes(page) + "'>" + bytes(page) + "</a>" pages += "<a class='Pnum' href='" + self.__URI + \
"p=" + bytes(page) + "'>" + bytes(page) + "</a>"
else: else:
pages += "<a class='Pnum' onclick='" + self.__RTURN_JS + "(" + bytes(page) + ")'>" + bytes(page) + "</a>" pages += "<a class='Pnum' onclick='" + self.__RTURN_JS + \
"(" + bytes(page) + ")'>" + bytes(page) + "</a>"
# 当前页 # 当前页
if self.__C_PAGE > 0: if self.__C_PAGE > 0:
pages += "<span class='Pcurrent'>" + bytes(self.__C_PAGE) + "</span>" pages += "<span class='Pcurrent'>" + \
bytes(self.__C_PAGE) + "</span>"
# 当前页之后 # 当前页之后
if self.__C_PAGE <= self.__LIST_NUM: if self.__C_PAGE <= self.__LIST_NUM:
num = self.__LIST_NUM + (self.__LIST_NUM - self.__C_PAGE) + 1 num = self.__LIST_NUM + (self.__LIST_NUM - self.__C_PAGE) + 1
else: else:
num = self.__LIST_NUM; num = self.__LIST_NUM
for i in range(num): for i in range(num):
if i == 0: if i == 0:
continue continue
page = self.__C_PAGE + i; page = self.__C_PAGE + i
if page > self.__COUNT_PAGE: if page > self.__COUNT_PAGE:
break; break
if self.__RTURN_JS == "": if self.__RTURN_JS == "":
pages += "<a class='Pnum' href='" + self.__URI + "p=" + bytes(page) + "'>" + bytes(page) + "</a>" pages += "<a class='Pnum' href='" + self.__URI + \
"p=" + bytes(page) + "'>" + bytes(page) + "</a>"
else: else:
pages += "<a class='Pnum' onclick='" + self.__RTURN_JS + "(" + bytes(page) + ")'>" + bytes(page) + "</a>" pages += "<a class='Pnum' onclick='" + self.__RTURN_JS + \
"(" + bytes(page) + ")'>" + bytes(page) + "</a>"
return pages; return pages
def __GetPrev(self): def __GetPrev(self):
# 构造上一页 # 构造上一页
startStr = '' startStr = ''
if self.__C_PAGE == 1: if self.__C_PAGE == 1:
startStr = ''; startStr = ''
else: else:
if self.__RTURN_JS == "": if self.__RTURN_JS == "":
startStr = "<a class='Ppren' href='" + self.__URI + "p=" + bytes(self.__C_PAGE - 1) + "'>" + self.__PREV + "</a>" startStr = "<a class='Ppren' href='" + self.__URI + "p=" + \
bytes(self.__C_PAGE - 1) + "'>" + self.__PREV + "</a>"
else: else:
startStr = "<a class='Ppren' onclick='" + self.__RTURN_JS + "(" + bytes(self.__C_PAGE - 1) + ")'>" + self.__PREV + "</a>" startStr = "<a class='Ppren' onclick='" + self.__RTURN_JS + \
"(" + bytes(self.__C_PAGE - 1) + ")'>" + self.__PREV + "</a>"
return startStr return startStr
def __GetStart(self): def __GetStart(self):
# 构造起始分页 # 构造起始分页
startStr = '' startStr = ''
if self.__C_PAGE == 1: if self.__C_PAGE == 1:
startStr = ''; startStr = ''
else: else:
if self.__RTURN_JS == "": if self.__RTURN_JS == "":
startStr = "<a class='Pstart' href='" + self.__URI + "p=1'>" + self.__START + "</a>" startStr = "<a class='Pstart' href='" + \
self.__URI + "p=1'>" + self.__START + "</a>"
else: else:
startStr = "<a class='Pstart' onclick='" + self.__RTURN_JS + "(1)'>" + self.__START + "</a>" startStr = "<a class='Pstart' onclick='" + \
return startStr; self.__RTURN_JS + "(1)'>" + self.__START + "</a>"
return startStr
def __GetCpage(self, p): def __GetCpage(self, p):
# 取当前页 # 取当前页

@ -72,22 +72,6 @@ def GetRandomString(length):
return str return str
def checkCode(code, outime=120):
# 校验验证码
import web
try:
if md5(code.lower()) != web.ctx.session.codeStr:
web.ctx.session.login_error = getMsg('CODE_ERR')
return False
if time.time() - web.ctx.session.codeTime > outime:
web.ctx.session.login_error = getMsg('CODE_TIMEOUT')
return False
return True
except:
web.ctx.session.login_error = getMsg('CODE_NOT_EXISTS')
return False
def retJson(status, msg, data=()): def retJson(status, msg, data=()):
return jsonify({'status': status, 'msg': msg, 'data': data}) return jsonify({'status': status, 'msg': msg, 'data': data})
@ -139,13 +123,6 @@ def getLan(key):
return msg return msg
def getJson(data):
import json
import web
web.header('Content-Type', 'application/json; charset=utf-8')
return json.dumps(data)
def readFile(filename): def readFile(filename):
# 读文件内容 # 读文件内容
try: try:
@ -333,13 +310,13 @@ def GetLocalIp():
ipaddress = re.search('\d+.\d+.\d+.\d+', ipaddress).group(0) ipaddress = re.search('\d+.\d+.\d+.\d+', ipaddress).group(0)
return ipaddress return ipaddress
except: except:
try: pass
url = web.ctx.session.home + '/Api/getIpAddress' # try:
opener = urllib2.urlopen(url) # url = web.ctx.session.home + '/Api/getIpAddress'
return opener.read() # opener = urllib2.urlopen(url)
except: # return opener.read()
import web # except:
return web.ctx.host.split(':')[0] # return web.ctx.host.split(':')[0]
# 搜索数据中是否存在 # 搜索数据中是否存在
@ -355,7 +332,6 @@ def inArray(arrays, searchStr):
def checkWebConfig(): def checkWebConfig():
import web
if get_webserver() == 'nginx': if get_webserver() == 'nginx':
result = ExecShell( result = ExecShell(
"ulimit -n 10240 && /www/server/nginx/sbin/nginx -t -c /www/server/nginx/conf/nginx.conf") "ulimit -n 10240 && /www/server/nginx/sbin/nginx -t -c /www/server/nginx/conf/nginx.conf")
@ -787,15 +763,15 @@ def CheckCert(certPath='ssl/certificate.pem'):
# 获取面板地址 # 获取面板地址
def getPanelAddr(): # def getPanelAddr():
import web # import web
protocol = 'https://' if os.path.exists("data/ssl.pl") else 'http://' # protocol = 'https://' if os.path.exists("data/ssl.pl") else 'http://'
h = web.ctx.host.split(':') # h = web.ctx.host.split(':')
try: # try:
result = protocol + h[0] + ':' + h[1] # result = protocol + h[0] + ':' + h[1]
except: # except:
result = protocol + h[0] + ':' + readFile('data/port.pl').strip() # result = protocol + h[0] + ':' + readFile('data/port.pl').strip()
return result # return result
# 字节单位转换 # 字节单位转换

@ -1,42 +1,48 @@
# coding: utf-8 # coding: utf-8
# +-------------------------------------------------------------------
# | 宝塔Linux面板 x3 import psutil
# +------------------------------------------------------------------- import time
# | Copyright (c) 2015-2016 宝塔软件(http://bt.cn) All rights reserved. import os
# +------------------------------------------------------------------- import public
# | Author: 黄文良 <287962566@qq.com> import re
# +-------------------------------------------------------------------
import psutil,web,time,os,public,re
class system: class system:
setupPath = None; setupPath = None
pids = None pids = None
def __init__(self): def __init__(self):
self.setupPath = '/www/server'; self.setupPath = '/www/server'
def GetConcifInfo(self, get=None): def GetConcifInfo(self, get=None):
# 取环境配置信息 # 取环境配置信息
if not hasattr(web.ctx.session, 'config'): if not hasattr(web.ctx.session, 'config'):
web.ctx.session.config = public.M('config').where("id=?",('1',)).field('webserver,sites_path,backup_path,status,mysql_root').find(); web.ctx.session.config = public.M('config').where("id=?", ('1',)).field(
'webserver,sites_path,backup_path,status,mysql_root').find()
if not hasattr(web.ctx.session.config, 'email'): if not hasattr(web.ctx.session.config, 'email'):
web.ctx.session.config['email'] = public.M('users').where("id=?",('1',)).getField('email'); web.ctx.session.config['email'] = public.M(
'users').where("id=?", ('1',)).getField('email')
data = {} data = {}
data = web.ctx.session.config data = web.ctx.session.config
data['webserver'] = web.ctx.session.config['webserver'] data['webserver'] = web.ctx.session.config['webserver']
# PHP版本 # PHP版本
phpVersions = ('52','53','54','55','56','70','71','72','73','74') phpVersions = ('52', '53', '54', '55', '56',
'70', '71', '72', '73', '74')
data['php'] = [] data['php'] = []
for version in phpVersions: for version in phpVersions:
tmp = {} tmp = {}
tmp['setup'] = os.path.exists(self.setupPath + '/php/'+version+'/bin/php'); tmp['setup'] = os.path.exists(
self.setupPath + '/php/' + version + '/bin/php')
if tmp['setup']: if tmp['setup']:
phpConfig = self.GetPHPConfig(version) phpConfig = self.GetPHPConfig(version)
tmp['version'] = version tmp['version'] = version
tmp['max'] = phpConfig['max'] tmp['max'] = phpConfig['max']
tmp['maxTime'] = phpConfig['maxTime'] tmp['maxTime'] = phpConfig['maxTime']
tmp['pathinfo'] = phpConfig['pathinfo'] tmp['pathinfo'] = phpConfig['pathinfo']
tmp['status'] = os.path.exists('/tmp/php-cgi-'+version+'.sock') tmp['status'] = os.path.exists(
'/tmp/php-cgi-' + version + '.sock')
data['php'].append(tmp) data['php'].append(tmp)
tmp = {} tmp = {}
@ -44,127 +50,139 @@ class system:
serviceName = 'nginx' serviceName = 'nginx'
tmp['setup'] = False tmp['setup'] = False
phpversion = "54" phpversion = "54"
phpport = '888'; phpport = '888'
pstatus = False; pstatus = False
pauth = False; pauth = False
if os.path.exists(self.setupPath + '/nginx'): if os.path.exists(self.setupPath + '/nginx'):
data['webserver'] = 'nginx' data['webserver'] = 'nginx'
serviceName = 'nginx' serviceName = 'nginx'
tmp['setup'] = os.path.exists(self.setupPath +'/nginx/sbin/nginx'); tmp['setup'] = os.path.exists(self.setupPath + '/nginx/sbin/nginx')
configFile = self.setupPath + '/nginx/conf/nginx.conf'; configFile = self.setupPath + '/nginx/conf/nginx.conf'
try: try:
if os.path.exists(configFile): if os.path.exists(configFile):
conf = public.readFile(configFile); conf = public.readFile(configFile)
rep = "listen\s+([0-9]+)\s*;"; rep = "listen\s+([0-9]+)\s*;"
rtmp = re.search(rep,conf); rtmp = re.search(rep, conf)
if rtmp: if rtmp:
phpport = rtmp.groups()[0]; phpport = rtmp.groups()[0]
if conf.find('AUTH_START') != -1: pauth = True; if conf.find('AUTH_START') != -1:
if conf.find(self.setupPath + '/stop') == -1: pstatus = True; pauth = True
configFile = self.setupPath + '/nginx/conf/enable-php.conf'; if conf.find(self.setupPath + '/stop') == -1:
conf = public.readFile(configFile); pstatus = True
rep = "php-cgi-([0-9]+)\.sock"; configFile = self.setupPath + '/nginx/conf/enable-php.conf'
rtmp = re.search(rep,conf); conf = public.readFile(configFile)
rep = "php-cgi-([0-9]+)\.sock"
rtmp = re.search(rep, conf)
if rtmp: if rtmp:
phpversion = rtmp.groups()[0]; phpversion = rtmp.groups()[0]
except: except:
pass; pass
elif os.path.exists(self.setupPath + '/apache'): elif os.path.exists(self.setupPath + '/apache'):
data['webserver'] = 'apache' data['webserver'] = 'apache'
serviceName = 'httpd' serviceName = 'httpd'
tmp['setup'] = os.path.exists(self.setupPath +'/apache/bin/httpd'); tmp['setup'] = os.path.exists(self.setupPath + '/apache/bin/httpd')
configFile = self.setupPath + '/apache/conf/extra/httpd-vhosts.conf'; configFile = self.setupPath + '/apache/conf/extra/httpd-vhosts.conf'
try: try:
if os.path.exists(configFile): if os.path.exists(configFile):
conf = public.readFile(configFile); conf = public.readFile(configFile)
rep = "php-cgi-([0-9]+)\.sock"; rep = "php-cgi-([0-9]+)\.sock"
rtmp = re.search(rep,conf); rtmp = re.search(rep, conf)
if rtmp: if rtmp:
phpversion = rtmp.groups()[0]; phpversion = rtmp.groups()[0]
rep = "Listen\s+([0-9]+)\s*\n"; rep = "Listen\s+([0-9]+)\s*\n"
rtmp = re.search(rep,conf); rtmp = re.search(rep, conf)
if rtmp: if rtmp:
phpport = rtmp.groups()[0]; phpport = rtmp.groups()[0]
if conf.find('AUTH_START') != -1: pauth = True; if conf.find('AUTH_START') != -1:
if conf.find(self.setupPath + '/stop') == -1: pstatus = True; pauth = True
if conf.find(self.setupPath + '/stop') == -1:
pstatus = True
except: except:
pass pass
tmp['type'] = data['webserver'] tmp['type'] = data['webserver']
tmp['version'] = public.readFile(self.setupPath + '/'+data['webserver']+'/version.pl'); tmp['version'] = public.readFile(
self.setupPath + '/' + data['webserver'] + '/version.pl')
tmp['status'] = False tmp['status'] = False
result = public.ExecShell('/etc/init.d/' + serviceName + ' status') result = public.ExecShell('/etc/init.d/' + serviceName + ' status')
if result[0].find('running') != -1: tmp['status'] = True if result[0].find('running') != -1:
tmp['status'] = True
data['web'] = tmp data['web'] = tmp
tmp = {} tmp = {}
vfile = self.setupPath + '/phpmyadmin/version.pl'; vfile = self.setupPath + '/phpmyadmin/version.pl'
tmp['version'] = public.readFile(vfile); tmp['version'] = public.readFile(vfile)
tmp['setup'] = os.path.exists(vfile); tmp['setup'] = os.path.exists(vfile)
tmp['status'] = pstatus; tmp['status'] = pstatus
tmp['phpversion'] = phpversion; tmp['phpversion'] = phpversion
tmp['port'] = phpport; tmp['port'] = phpport
tmp['auth'] = pauth; tmp['auth'] = pauth
data['phpmyadmin'] = tmp; data['phpmyadmin'] = tmp
tmp = {} tmp = {}
tmp['setup'] = os.path.exists('/etc/init.d/tomcat'); tmp['setup'] = os.path.exists('/etc/init.d/tomcat')
tmp['status'] = False tmp['status'] = False
if tmp['setup']: if tmp['setup']:
if os.path.exists('/www/server/tomcat/logs/catalina-daemon.pid'): if os.path.exists('/www/server/tomcat/logs/catalina-daemon.pid'):
tmp['status'] = self.getPid('jsvc') tmp['status'] = self.getPid('jsvc')
if not tmp['status']: if not tmp['status']:
tmp['status'] = self.getPid('java') tmp['status'] = self.getPid('java')
tmp['version'] = public.readFile(self.setupPath + '/tomcat/version.pl'); tmp['version'] = public.readFile(self.setupPath + '/tomcat/version.pl')
data['tomcat'] = tmp; data['tomcat'] = tmp
tmp = {} tmp = {}
tmp['setup'] = os.path.exists(self.setupPath +'/mysql/bin/mysql'); tmp['setup'] = os.path.exists(self.setupPath + '/mysql/bin/mysql')
tmp['version'] = public.readFile(self.setupPath + '/mysql/version.pl'); tmp['version'] = public.readFile(self.setupPath + '/mysql/version.pl')
tmp['status'] = os.path.exists('/tmp/mysql.sock') tmp['status'] = os.path.exists('/tmp/mysql.sock')
data['mysql'] = tmp data['mysql'] = tmp
tmp = {} tmp = {}
tmp['setup'] = os.path.exists(self.setupPath +'/redis/runtest'); tmp['setup'] = os.path.exists(self.setupPath + '/redis/runtest')
tmp['status'] = os.path.exists('/var/run/redis_6379.pid'); tmp['status'] = os.path.exists('/var/run/redis_6379.pid')
data['redis'] = tmp; data['redis'] = tmp
tmp = {} tmp = {}
tmp['setup'] = os.path.exists('/usr/local/memcached/bin/memcached'); tmp['setup'] = os.path.exists('/usr/local/memcached/bin/memcached')
tmp['status'] = os.path.exists('/var/run/memcached.pid'); tmp['status'] = os.path.exists('/var/run/memcached.pid')
data['memcached'] = tmp; data['memcached'] = tmp
tmp = {} tmp = {}
tmp['setup'] = os.path.exists(self.setupPath +'/pure-ftpd/bin/pure-pw'); tmp['setup'] = os.path.exists(
tmp['version'] = public.readFile(self.setupPath + '/pure-ftpd/version.pl'); self.setupPath + '/pure-ftpd/bin/pure-pw')
tmp['version'] = public.readFile(
self.setupPath + '/pure-ftpd/version.pl')
tmp['status'] = os.path.exists('/var/run/pure-ftpd.pid') tmp['status'] = os.path.exists('/var/run/pure-ftpd.pid')
data['pure-ftpd'] = tmp data['pure-ftpd'] = tmp
data['panel'] = self.GetPanelInfo() data['panel'] = self.GetPanelInfo()
data['systemdate'] = public.ExecShell('date +"%Y-%m-%d %H:%M:%S %Z %z"')[0].strip(); data['systemdate'] = public.ExecShell(
'date +"%Y-%m-%d %H:%M:%S %Z %z"')[0].strip()
return data return data
# 名取PID # 名取PID
def getPid(self, pname): def getPid(self, pname):
try: try:
if not self.pids: self.pids = psutil.pids() if not self.pids:
self.pids = psutil.pids()
for pid in self.pids: for pid in self.pids:
if psutil.Process(pid).name() == pname: return True; if psutil.Process(pid).name() == pname:
return True
return False
except:
return False return False
except: return False
# 检测指定进程是否存活 # 检测指定进程是否存活
def checkProcess(self, pid): def checkProcess(self, pid):
try: try:
if not self.pids: self.pids = psutil.pids() if not self.pids:
if int(pid) in self.pids: return True self.pids = psutil.pids()
return False; if int(pid) in self.pids:
except: return False return True
return False
except:
return False
def GetPanelInfo(self, get=None): def GetPanelInfo(self, get=None):
# 取面板配置 # 取面板配置
@ -175,23 +193,27 @@ class system:
except: except:
port = public.readFile('data/port.pl') port = public.readFile('data/port.pl')
except: except:
port = '8888'; port = '8888'
domain = '' domain = ''
if os.path.exists('data/domain.conf'): if os.path.exists('data/domain.conf'):
domain = public.readFile('data/domain.conf'); domain = public.readFile('data/domain.conf')
autoUpdate = '' autoUpdate = ''
if os.path.exists('data/autoUpdate.pl'): autoUpdate = 'checked'; if os.path.exists('data/autoUpdate.pl'):
autoUpdate = 'checked'
limitip = '' limitip = ''
if os.path.exists('data/limitip.conf'): limitip = public.readFile('data/limitip.conf'); if os.path.exists('data/limitip.conf'):
limitip = public.readFile('data/limitip.conf')
templates = [] templates = []
for template in os.listdir('templates/'): for template in os.listdir('templates/'):
if os.path.isdir('templates/' + template): templates.append(template); if os.path.isdir('templates/' + template):
template = public.readFile('data/templates.pl'); templates.append(template)
template = public.readFile('data/templates.pl')
check502 = ''; check502 = ''
if os.path.exists('data/502Task.pl'): check502 = 'checked'; if os.path.exists('data/502Task.pl'):
check502 = 'checked'
return {'port': port, 'address': address, 'domain': domain, 'auto': autoUpdate, '502': check502, 'limitip': limitip, 'templates': templates, 'template': template} return {'port': port, 'address': address, 'domain': domain, 'auto': autoUpdate, '502': check502, 'limitip': limitip, 'templates': templates, 'template': template}
def GetPHPConfig(self, version): def GetPHPConfig(self, version):
@ -227,72 +249,76 @@ class system:
return data return data
def GetSystemTotal(self, get, interval=1): def GetSystemTotal(self, get, interval=1):
# 取系统统计信息 # 取系统统计信息
data = self.GetMemInfo(); data = self.GetMemInfo()
cpu = self.GetCpuInfo(interval); cpu = self.GetCpuInfo(interval)
data['cpuNum'] = cpu[1]; data['cpuNum'] = cpu[1]
data['cpuRealUsed'] = cpu[0]; data['cpuRealUsed'] = cpu[0]
data['time'] = self.GetBootTime(); data['time'] = self.GetBootTime()
data['system'] = self.GetSystemVersion(); data['system'] = self.GetSystemVersion()
data['isuser'] = public.M('users').where('username=?',('admin',)).count(); data['isuser'] = public.M('users').where(
data['version'] = web.ctx.session.version; 'username=?', ('admin',)).count()
data['version'] = web.ctx.session.version
return data return data
def GetLoadAverage(self, get): def GetLoadAverage(self, get):
c = os.getloadavg() c = os.getloadavg()
data = {}; data = {}
data['one'] = float(c[0]); data['one'] = float(c[0])
data['five'] = float(c[1]); data['five'] = float(c[1])
data['fifteen'] = float(c[2]); data['fifteen'] = float(c[2])
data['max'] = psutil.cpu_count() * 2; data['max'] = psutil.cpu_count() * 2
data['limit'] = data['max']; data['limit'] = data['max']
data['safe'] = data['max'] * 0.75; data['safe'] = data['max'] * 0.75
return data; return data
def GetAllInfo(self, get): def GetAllInfo(self, get):
data = {} data = {}
data['load_average'] = self.GetLoadAverage(get); data['load_average'] = self.GetLoadAverage(get)
data['title'] = self.GetTitle(); data['title'] = self.GetTitle()
data['network'] = self.GetNetWorkApi(get); data['network'] = self.GetNetWorkApi(get)
data['panel_status'] = not os.path.exists('/www/server/panel/data/close.pl'); data['panel_status'] = not os.path.exists(
'/www/server/panel/data/close.pl')
import firewalls import firewalls
ssh_info = firewalls.firewalls().GetSshInfo(None) ssh_info = firewalls.firewalls().GetSshInfo(None)
data['enable_ssh_status'] = ssh_info['status'] data['enable_ssh_status'] = ssh_info['status']
data['disable_ping_status'] = not ssh_info['ping'] data['disable_ping_status'] = not ssh_info['ping']
data['time'] = self.GetBootTime(); data['time'] = self.GetBootTime()
#data['system'] = self.GetSystemVersion(); #data['system'] = self.GetSystemVersion();
#data['mem'] = self.GetMemInfo(); #data['mem'] = self.GetMemInfo();
data['version'] = web.ctx.session.version; data['version'] = web.ctx.session.version
return data; return data
def GetTitle(self): def GetTitle(self):
titlePl = 'data/title.pl'; titlePl = 'data/title.pl'
title = '宝塔Linux面板'; title = '宝塔Linux面板'
if os.path.exists(titlePl): title = public.readFile(titlePl).strip(); if os.path.exists(titlePl):
return title; title = public.readFile(titlePl).strip()
return title
def GetSystemVersion(self): def GetSystemVersion(self):
# 取操作系统版本 # 取操作系统版本
import public import public
version = public.readFile('/etc/redhat-release') version = public.readFile('/etc/redhat-release')
if not version: if not version:
version = public.readFile('/etc/issue').strip().split("\n")[0].replace('\\n','').replace('\l','').strip(); version = public.readFile(
'/etc/issue').strip().split("\n")[0].replace('\\n', '').replace('\l', '').strip()
else: else:
version = version.replace('release ','').strip(); version = version.replace('release ', '').strip()
return version return version
def GetBootTime(self): def GetBootTime(self):
# 取系统启动时间 # 取系统启动时间
import public,math import public
import math
conf = public.readFile('/proc/uptime').split() conf = public.readFile('/proc/uptime').split()
tStr = float(conf[0]) tStr = float(conf[0])
min = tStr / 60; min = tStr / 60
hours = min / 60; hours = min / 60
days = math.floor(hours / 24); days = math.floor(hours / 24)
hours = math.floor(hours - (days * 24)); hours = math.floor(hours - (days * 24))
min = math.floor(min - (days * 60 * 24) - (hours * 60)); min = math.floor(min - (days * 60 * 24) - (hours * 60))
return public.getMsg('SYS_BOOT_TIME', (str(int(days)), str(int(hours)), str(int(min)))) return public.getMsg('SYS_BOOT_TIME', (str(int(days)), str(int(hours)), str(int(min))))
def GetCpuInfo(self, interval=1): def GetCpuInfo(self, interval=1):
@ -304,19 +330,23 @@ class system:
def GetMemInfo(self, get=None): def GetMemInfo(self, get=None):
# 取内存信息 # 取内存信息
mem = psutil.virtual_memory() mem = psutil.virtual_memory()
memInfo = {'memTotal':mem.total/1024/1024,'memFree':mem.free/1024/1024,'memBuffers':mem.buffers/1024/1024,'memCached':mem.cached/1024/1024} memInfo = {'memTotal': mem.total / 1024 / 1024, 'memFree': mem.free / 1024 / 1024,
memInfo['memRealUsed'] = memInfo['memTotal'] - memInfo['memFree'] - memInfo['memBuffers'] - memInfo['memCached'] 'memBuffers': mem.buffers / 1024 / 1024, 'memCached': mem.cached / 1024 / 1024}
memInfo['memRealUsed'] = memInfo['memTotal'] - \
memInfo['memFree'] - memInfo['memBuffers'] - memInfo['memCached']
return memInfo return memInfo
def GetDiskInfo(self, get=None): def GetDiskInfo(self, get=None):
return self.GetDiskInfo2(); return self.GetDiskInfo2()
# 取磁盘分区信息 # 取磁盘分区信息
diskIo = psutil.disk_partitions(); diskIo = psutil.disk_partitions()
diskInfo = [] diskInfo = []
for disk in diskIo: for disk in diskIo:
if disk[1] == '/mnt/cdrom':continue; if disk[1] == '/mnt/cdrom':
if disk[1] == '/boot':continue; continue
if disk[1] == '/boot':
continue
tmp = {} tmp = {}
tmp['path'] = disk[1] tmp['path'] = disk[1]
tmp['size'] = psutil.disk_usage(disk[1]) tmp['size'] = psutil.disk_usage(disk[1])
@ -325,61 +355,70 @@ class system:
def GetDiskInfo2(self): def GetDiskInfo2(self):
# 取磁盘分区信息 # 取磁盘分区信息
temp = public.ExecShell("df -h -P|grep '/'|grep -v tmpfs")[0]; temp = public.ExecShell("df -h -P|grep '/'|grep -v tmpfs")[0]
tempInodes = public.ExecShell("df -i -P|grep '/'|grep -v tmpfs")[0]; tempInodes = public.ExecShell("df -i -P|grep '/'|grep -v tmpfs")[0]
temp1 = temp.split('\n'); temp1 = temp.split('\n')
tempInodes1 = tempInodes.split('\n'); tempInodes1 = tempInodes.split('\n')
diskInfo = []; diskInfo = []
n = 0 n = 0
cuts = ['/mnt/cdrom','/boot','/boot/efi','/dev','/dev/shm','/run/lock','/run','/run/shm','/run/user']; cuts = ['/mnt/cdrom', '/boot', '/boot/efi', '/dev',
'/dev/shm', '/run/lock', '/run', '/run/shm', '/run/user']
for tmp in temp1: for tmp in temp1:
n += 1 n += 1
inodes = tempInodes1[n-1].split(); inodes = tempInodes1[n - 1].split()
disk = tmp.split(); disk = tmp.split()
if len(disk) < 5: continue; if len(disk) < 5:
if disk[1].find('M') != -1: continue; continue
if disk[1].find('K') != -1: continue; if disk[1].find('M') != -1:
if len(disk[5].split('/')) > 4: continue; continue
if disk[5] in cuts: continue; if disk[1].find('K') != -1:
continue
if len(disk[5].split('/')) > 4:
continue
if disk[5] in cuts:
continue
arr = {} arr = {}
arr['path'] = disk[5]; arr['path'] = disk[5]
tmp1 = [disk[1],disk[2],disk[3],disk[4]]; tmp1 = [disk[1], disk[2], disk[3], disk[4]]
arr['size'] = tmp1; arr['size'] = tmp1
arr['inodes'] = [inodes[1], inodes[2], inodes[3], inodes[4]] arr['inodes'] = [inodes[1], inodes[2], inodes[3], inodes[4]]
if disk[5] == '/': if disk[5] == '/':
bootLog = '/tmp/panelBoot.pl'; bootLog = '/tmp/panelBoot.pl'
if disk[2].find('M') != -1: if disk[2].find('M') != -1:
if os.path.exists(bootLog): os.system('rm -f ' + bootLog); if os.path.exists(bootLog):
os.system('rm -f ' + bootLog)
else: else:
if not os.path.exists(bootLog): os.system('sleep 1 && /etc/init.d/bt reload &'); if not os.path.exists(bootLog):
diskInfo.append(arr); os.system('sleep 1 && /etc/init.d/bt reload &')
return diskInfo; diskInfo.append(arr)
return diskInfo
# 清理系统垃圾 # 清理系统垃圾
def ClearSystem(self, get): def ClearSystem(self, get):
count = total = 0; count = total = 0
tmp_total,tmp_count = self.ClearMail(); tmp_total, tmp_count = self.ClearMail()
count += tmp_count; count += tmp_count
total += tmp_total; total += tmp_total
tmp_total,tmp_count = self.ClearOther(); tmp_total, tmp_count = self.ClearOther()
count += tmp_count; count += tmp_count
total += tmp_total; total += tmp_total
return count, total return count, total
# 清理邮件日志 # 清理邮件日志
def ClearMail(self): def ClearMail(self):
rpath = '/var/spool'; rpath = '/var/spool'
total = count = 0; total = count = 0
import shutil import shutil
con = ['cron','anacron','mail']; con = ['cron', 'anacron', 'mail']
for d in os.listdir(rpath): for d in os.listdir(rpath):
if d in con: continue; if d in con:
continue
dpath = rpath + '/' + d dpath = rpath + '/' + d
time.sleep(0.2); time.sleep(0.2)
num = size = 0; num = size = 0
for n in os.listdir(dpath): for n in os.listdir(dpath):
filename = dpath + '/' + n filename = dpath + '/' + n
fsize = os.path.getsize(filename); fsize = os.path.getsize(filename)
size += fsize size += fsize
if os.path.isdir(filename): if os.path.isdir(filename):
shutil.rmtree(filename) shutil.rmtree(filename)
@ -387,8 +426,8 @@ class system:
os.remove(filename) os.remove(filename)
print '\t\033[1;32m[OK]\033[0m' print '\t\033[1;32m[OK]\033[0m'
num += 1 num += 1
total += size; total += size
count += num; count += num
return total, count return total, count
# 清理其它 # 清理其它
@ -400,20 +439,21 @@ class system:
{'path': '/www/server/panel/install', 'find': '.rpm'} {'path': '/www/server/panel/install', 'find': '.rpm'}
] ]
total = count = 0; total = count = 0
for c in clearPath: for c in clearPath:
for d in os.listdir(c['path']): for d in os.listdir(c['path']):
if d.find(c['find']) == -1: continue; if d.find(c['find']) == -1:
filename = c['path'] + '/' + d; continue
fsize = os.path.getsize(filename); filename = c['path'] + '/' + d
fsize = os.path.getsize(filename)
total += fsize total += fsize
if os.path.isdir(filename): if os.path.isdir(filename):
shutil.rmtree(filename) shutil.rmtree(filename)
else: else:
os.remove(filename) os.remove(filename)
count += 1; count += 1
public.serviceReload(); public.serviceReload()
os.system('echo > /tmp/panelBoot.pl'); os.system('echo > /tmp/panelBoot.pl')
return total, count return total, count
def GetNetWork(self, get=None): def GetNetWork(self, get=None):
@ -424,49 +464,54 @@ class system:
if not hasattr(web.ctx.session, 'otime'): if not hasattr(web.ctx.session, 'otime'):
web.ctx.session.up = networkIo[0] web.ctx.session.up = networkIo[0]
web.ctx.session.down = networkIo[1] web.ctx.session.down = networkIo[1]
web.ctx.session.otime = time.time(); web.ctx.session.otime = time.time()
ntime = time.time(); ntime = time.time()
networkInfo = {} networkInfo = {}
networkInfo['upTotal'] = networkIo[0] networkInfo['upTotal'] = networkIo[0]
networkInfo['downTotal'] = networkIo[1] networkInfo['downTotal'] = networkIo[1]
networkInfo['up'] = round(float(networkIo[0] - web.ctx.session.up) / 1024 / (ntime - web.ctx.session.otime),2) networkInfo['up'] = round(float(
networkInfo['down'] = round(float(networkIo[1] - web.ctx.session.down) / 1024 / (ntime - web.ctx.session.otime),2) networkIo[0] - web.ctx.session.up) / 1024 / (ntime - web.ctx.session.otime), 2)
networkInfo['down'] = round(float(
networkIo[1] - web.ctx.session.down) / 1024 / (ntime - web.ctx.session.otime), 2)
networkInfo['downPackets'] = networkIo[3] networkInfo['downPackets'] = networkIo[3]
networkInfo['upPackets'] = networkIo[2] networkInfo['upPackets'] = networkIo[2]
web.ctx.session.up = networkIo[0] web.ctx.session.up = networkIo[0]
web.ctx.session.down = networkIo[1] web.ctx.session.down = networkIo[1]
web.ctx.session.otime = ntime; web.ctx.session.otime = ntime
networkInfo['cpu'] = self.GetCpuInfo() networkInfo['cpu'] = self.GetCpuInfo()
networkInfo['load'] = self.GetLoadAverage(get); networkInfo['load'] = self.GetLoadAverage(get)
return networkInfo return networkInfo
except: except:
return None return None
def GetNetWorkApi(self, get=None): def GetNetWorkApi(self, get=None):
# 取网络流量信息 # 取网络流量信息
try: try:
tmpfile = 'data/network.temp'; tmpfile = 'data/network.temp'
networkIo = psutil.net_io_counters()[:4] networkIo = psutil.net_io_counters()[:4]
if not os.path.exists(tmpfile): if not os.path.exists(tmpfile):
public.writeFile(tmpfile,str(networkIo[0])+'|'+str(networkIo[1])+'|' + str(int(time.time()))); public.writeFile(tmpfile, str(
networkIo[0]) + '|' + str(networkIo[1]) + '|' + str(int(time.time())))
lastValue = public.readFile(tmpfile).split('|'); lastValue = public.readFile(tmpfile).split('|')
ntime = time.time(); ntime = time.time()
networkInfo = {} networkInfo = {}
networkInfo['upTotal'] = networkIo[0] networkInfo['upTotal'] = networkIo[0]
networkInfo['downTotal'] = networkIo[1] networkInfo['downTotal'] = networkIo[1]
networkInfo['up'] = round(float(networkIo[0] - int(lastValue[0])) / 1024 / (ntime - int(lastValue[2])),2) networkInfo['up'] = round(
networkInfo['down'] = round(float(networkIo[1] - int(lastValue[1])) / 1024 / (ntime - int(lastValue[2])),2) float(networkIo[0] - int(lastValue[0])) / 1024 / (ntime - int(lastValue[2])), 2)
networkInfo['down'] = round(
float(networkIo[1] - int(lastValue[1])) / 1024 / (ntime - int(lastValue[2])), 2)
networkInfo['downPackets'] = networkIo[3] networkInfo['downPackets'] = networkIo[3]
networkInfo['upPackets'] = networkIo[2] networkInfo['upPackets'] = networkIo[2]
public.writeFile(tmpfile,str(networkIo[0])+'|'+str(networkIo[1])+'|' + str(int(time.time()))); public.writeFile(tmpfile, str(
networkIo[0]) + '|' + str(networkIo[1]) + '|' + str(int(time.time())))
#networkInfo['cpu'] = self.GetCpuInfo(0.1) #networkInfo['cpu'] = self.GetCpuInfo(0.1)
return networkInfo return networkInfo
@ -475,160 +520,181 @@ class system:
def GetNetWorkOld(self): def GetNetWorkOld(self):
# 取网络流量信息 # 取网络流量信息
import time; import time
pnet = public.readFile('/proc/net/dev'); pnet = public.readFile('/proc/net/dev')
rep = '([^\s]+):[\s]{0,}(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)'; rep = '([^\s]+):[\s]{0,}(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)'
pnetall = re.findall(rep,pnet); pnetall = re.findall(rep, pnet)
networkInfo = {} networkInfo = {}
networkInfo['upTotal'] = networkInfo['downTotal'] = networkInfo['up'] = networkInfo['down'] = networkInfo['downPackets'] = networkInfo['upPackets'] = 0; networkInfo['upTotal'] = networkInfo['downTotal'] = networkInfo['up'] = networkInfo[
'down'] = networkInfo['downPackets'] = networkInfo['upPackets'] = 0
for pnetInfo in pnetall: for pnetInfo in pnetall:
if pnetInfo[0] == 'io': continue; if pnetInfo[0] == 'io':
networkInfo['downTotal'] += int(pnetInfo[1]); continue
networkInfo['downPackets'] += int(pnetInfo[2]); networkInfo['downTotal'] += int(pnetInfo[1])
networkInfo['upTotal'] += int(pnetInfo[9]); networkInfo['downPackets'] += int(pnetInfo[2])
networkInfo['upPackets'] += int(pnetInfo[10]); networkInfo['upTotal'] += int(pnetInfo[9])
networkInfo['upPackets'] += int(pnetInfo[10])
if not hasattr(web.ctx.session, 'otime'): if not hasattr(web.ctx.session, 'otime'):
web.ctx.session.up = networkInfo['upTotal'] web.ctx.session.up = networkInfo['upTotal']
web.ctx.session.down = networkInfo['downTotal'] web.ctx.session.down = networkInfo['downTotal']
web.ctx.session.otime = time.time(); web.ctx.session.otime = time.time()
ntime = time.time(); ntime = time.time()
tmpDown = networkInfo['downTotal'] - web.ctx.session.down; tmpDown = networkInfo['downTotal'] - web.ctx.session.down
tmpUp = networkInfo['upTotal'] - web.ctx.session.up; tmpUp = networkInfo['upTotal'] - web.ctx.session.up
networkInfo['down'] = str(round(float(tmpDown) / 1024 / (ntime - web.ctx.session.otime),2)); networkInfo['down'] = str(
networkInfo['up'] = str(round(float(tmpUp) / 1024 / (ntime - web.ctx.session.otime),2)); round(float(tmpDown) / 1024 / (ntime - web.ctx.session.otime), 2))
if networkInfo['down'] < 0: networkInfo['down'] = 0; networkInfo['up'] = str(
if networkInfo['up'] < 0: networkInfo['up'] = 0; round(float(tmpUp) / 1024 / (ntime - web.ctx.session.otime), 2))
if networkInfo['down'] < 0:
web.ctx.session.up = networkInfo['upTotal']; networkInfo['down'] = 0
web.ctx.session.down = networkInfo['downTotal']; if networkInfo['up'] < 0:
web.ctx.session.otime = ntime; networkInfo['up'] = 0
web.ctx.session.up = networkInfo['upTotal']
web.ctx.session.down = networkInfo['downTotal']
web.ctx.session.otime = ntime
networkInfo['cpu'] = self.GetCpuInfo() networkInfo['cpu'] = self.GetCpuInfo()
return networkInfo; return networkInfo
def ServiceAdmin(self, get=None): def ServiceAdmin(self, get=None):
# 服务管理 # 服务管理
if get.name == 'mysqld': public.CheckMyCnf(); if get.name == 'mysqld':
public.CheckMyCnf()
if get.name == 'phpmyadmin': if get.name == 'phpmyadmin':
import ajax import ajax
get.status = 'True'; get.status = 'True'
ajax.ajax().setPHPMyAdmin(get); ajax.ajax().setPHPMyAdmin(get)
return public.returnMsg(True,'SYS_EXEC_SUCCESS'); return public.returnMsg(True, 'SYS_EXEC_SUCCESS')
# 检查httpd配置文件 # 检查httpd配置文件
if get.name == 'apache' or get.name == 'httpd': if get.name == 'apache' or get.name == 'httpd':
get.name = 'httpd'; get.name = 'httpd'
if not os.path.exists(self.setupPath+'/apache/bin/apachectl'): return public.returnMsg(True,'SYS_NOT_INSTALL_APACHE'); if not os.path.exists(self.setupPath + '/apache/bin/apachectl'):
return public.returnMsg(True, 'SYS_NOT_INSTALL_APACHE')
vhostPath = self.setupPath + '/panel/vhost/apache' vhostPath = self.setupPath + '/panel/vhost/apache'
if not os.path.exists(vhostPath): if not os.path.exists(vhostPath):
public.ExecShell('mkdir ' + vhostPath); public.ExecShell('mkdir ' + vhostPath)
public.ExecShell('/etc/init.d/httpd start'); public.ExecShell('/etc/init.d/httpd start')
if get.type == 'start': if get.type == 'start':
public.ExecShell('/etc/init.d/httpd stop'); public.ExecShell('/etc/init.d/httpd stop')
public.ExecShell('pkill -9 httpd'); public.ExecShell('pkill -9 httpd')
result = public.ExecShell('ulimit -n 10240 && ' + self.setupPath+'/apache/bin/apachectl -t'); result = public.ExecShell(
'ulimit -n 10240 && ' + self.setupPath + '/apache/bin/apachectl -t')
if result[1].find('Syntax OK') == -1: if result[1].find('Syntax OK') == -1:
public.WriteLog("TYPE_SOFT",'SYS_EXEC_ERR', (str(result),)); public.WriteLog("TYPE_SOFT", 'SYS_EXEC_ERR', (str(result),))
return public.returnMsg(False,'SYS_CONF_APACHE_ERR',(result[1].replace("\n",'<br>'),)); return public.returnMsg(False, 'SYS_CONF_APACHE_ERR', (result[1].replace("\n", '<br>'),))
if get.type == 'restart': if get.type == 'restart':
public.ExecShell('pkill -9 httpd'); public.ExecShell('pkill -9 httpd')
public.ExecShell('/etc/init.d/httpd start'); public.ExecShell('/etc/init.d/httpd start')
# 检查nginx配置文件 # 检查nginx配置文件
elif get.name == 'nginx': elif get.name == 'nginx':
vhostPath = self.setupPath + '/panel/vhost/rewrite' vhostPath = self.setupPath + '/panel/vhost/rewrite'
if not os.path.exists(vhostPath): public.ExecShell('mkdir ' + vhostPath); if not os.path.exists(vhostPath):
public.ExecShell('mkdir ' + vhostPath)
vhostPath = self.setupPath + '/panel/vhost/nginx' vhostPath = self.setupPath + '/panel/vhost/nginx'
if not os.path.exists(vhostPath): if not os.path.exists(vhostPath):
public.ExecShell('mkdir ' + vhostPath); public.ExecShell('mkdir ' + vhostPath)
public.ExecShell('/etc/init.d/nginx start'); public.ExecShell('/etc/init.d/nginx start')
result = public.ExecShell('ulimit -n 10240 && nginx -t -c '+self.setupPath+'/nginx/conf/nginx.conf'); result = public.ExecShell(
'ulimit -n 10240 && nginx -t -c ' + self.setupPath + '/nginx/conf/nginx.conf')
if result[1].find('perserver') != -1: if result[1].find('perserver') != -1:
limit = self.setupPath + '/nginx/conf/nginx.conf'; limit = self.setupPath + '/nginx/conf/nginx.conf'
nginxConf = public.readFile(limit); nginxConf = public.readFile(limit)
limitConf = "limit_conn_zone $binary_remote_addr zone=perip:10m;\n\t\tlimit_conn_zone $server_name zone=perserver:10m;"; limitConf = "limit_conn_zone $binary_remote_addr zone=perip:10m;\n\t\tlimit_conn_zone $server_name zone=perserver:10m;"
nginxConf = nginxConf.replace("#limit_conn_zone $binary_remote_addr zone=perip:10m;",limitConf); nginxConf = nginxConf.replace(
"#limit_conn_zone $binary_remote_addr zone=perip:10m;", limitConf)
public.writeFile(limit, nginxConf) public.writeFile(limit, nginxConf)
public.ExecShell('/etc/init.d/nginx start'); public.ExecShell('/etc/init.d/nginx start')
return public.returnMsg(True,'SYS_CONF_NGINX_REP'); return public.returnMsg(True, 'SYS_CONF_NGINX_REP')
if result[1].find('proxy') != -1: if result[1].find('proxy') != -1:
import panelSite import panelSite
panelSite.panelSite().CheckProxy(get); panelSite.panelSite().CheckProxy(get)
public.ExecShell('/etc/init.d/nginx start'); public.ExecShell('/etc/init.d/nginx start')
return public.returnMsg(True,'SYS_CONF_NGINX_REP'); return public.returnMsg(True, 'SYS_CONF_NGINX_REP')
# return result # return result
if result[1].find('successful') == -1: if result[1].find('successful') == -1:
public.WriteLog("TYPE_SOFT",'SYS_EXEC_ERR', (str(result),)); public.WriteLog("TYPE_SOFT", 'SYS_EXEC_ERR', (str(result),))
return public.returnMsg(False,'SYS_CONF_NGINX_ERR',(result[1].replace("\n",'<br>'),)); return public.returnMsg(False, 'SYS_CONF_NGINX_ERR', (result[1].replace("\n", '<br>'),))
# 执行 # 执行
execStr = "/etc/init.d/" + get.name + " " + get.type execStr = "/etc/init.d/" + get.name + " " + get.type
if execStr == '/etc/init.d/pure-ftpd reload': execStr = self.setupPath+'/pure-ftpd/bin/pure-pw mkdb '+self.setupPath+'/pure-ftpd/etc/pureftpd.pdb' if execStr == '/etc/init.d/pure-ftpd reload':
if execStr == '/etc/init.d/pure-ftpd start': os.system('pkill -9 pure-ftpd'); execStr = self.setupPath + '/pure-ftpd/bin/pure-pw mkdb ' + \
if execStr == '/etc/init.d/tomcat reload': execStr = '/etc/init.d/tomcat stop && /etc/init.d/tomcat start'; self.setupPath + '/pure-ftpd/etc/pureftpd.pdb'
if execStr == '/etc/init.d/tomcat restart': execStr = '/etc/init.d/tomcat stop && /etc/init.d/tomcat start'; if execStr == '/etc/init.d/pure-ftpd start':
os.system('pkill -9 pure-ftpd')
if execStr == '/etc/init.d/tomcat reload':
execStr = '/etc/init.d/tomcat stop && /etc/init.d/tomcat start'
if execStr == '/etc/init.d/tomcat restart':
execStr = '/etc/init.d/tomcat stop && /etc/init.d/tomcat start'
if get.name != 'mysqld': if get.name != 'mysqld':
result = public.ExecShell(execStr); result = public.ExecShell(execStr)
else: else:
os.system(execStr); os.system(execStr)
result = []; result = []
result.append(''); result.append('')
result.append(''); result.append('')
if result[1].find('nginx.pid') != -1: if result[1].find('nginx.pid') != -1:
public.ExecShell('pkill -9 nginx && sleep 1'); public.ExecShell('pkill -9 nginx && sleep 1')
public.ExecShell('/etc/init.d/nginx start'); public.ExecShell('/etc/init.d/nginx start')
if get.type != 'test': if get.type != 'test':
public.WriteLog("TYPE_SOFT", 'SYS_EXEC_SUCCESS',(execStr,)); public.WriteLog("TYPE_SOFT", 'SYS_EXEC_SUCCESS', (execStr,))
if len(result[1]) > 1 and get.name != 'pure-ftpd': return public.returnMsg(False, '<p>警告消息: <p>' + result[1].replace('\n','<br>')); if len(result[1]) > 1 and get.name != 'pure-ftpd':
return public.returnMsg(True,'SYS_EXEC_SUCCESS'); return public.returnMsg(False, '<p>警告消息: <p>' + result[1].replace('\n', '<br>'))
return public.returnMsg(True, 'SYS_EXEC_SUCCESS')
def RestartServer(self, get): def RestartServer(self, get):
if not public.IsRestart(): return public.returnMsg(False,'EXEC_ERR_TASK'); if not public.IsRestart():
public.ExecShell("sync && /etc/init.d/bt stop && init 6 &"); return public.returnMsg(False, 'EXEC_ERR_TASK')
return public.returnMsg(True,'SYS_REBOOT'); public.ExecShell("sync && /etc/init.d/bt stop && init 6 &")
return public.returnMsg(True, 'SYS_REBOOT')
# 释放内存 # 释放内存
def ReMemory(self, get): def ReMemory(self, get):
os.system('sync'); os.system('sync')
scriptFile = 'script/rememory.sh' scriptFile = 'script/rememory.sh'
if not os.path.exists(scriptFile): if not os.path.exists(scriptFile):
public.downloadFile(web.ctx.session.home + '/script/rememory.sh',scriptFile); public.downloadFile(web.ctx.session.home +
public.ExecShell("/bin/bash " + self.setupPath + '/panel/' + scriptFile); '/script/rememory.sh', scriptFile)
return self.GetMemInfo(); public.ExecShell("/bin/bash " + self.setupPath +
'/panel/' + scriptFile)
return self.GetMemInfo()
# 重启面板 # 重启面板
def ReWeb(self, get): def ReWeb(self, get):
#if not public.IsRestart(): return public.returnMsg(False,'EXEC_ERR_TASK'); # if not public.IsRestart(): return
public.ExecShell('/etc/init.d/bt restart &'); # public.returnMsg(False,'EXEC_ERR_TASK');
public.ExecShell('/etc/init.d/bt restart &')
return True return True
# 修复面板 # 修复面板
def RepPanel(self, get): def RepPanel(self, get):
vp = ''; vp = ''
if public.readFile('/www/server/panel/class/common.py').find('checkSafe') != -1: vp = '_pro'; if public.readFile('/www/server/panel/class/common.py').find('checkSafe') != -1:
public.ExecShell("wget -O update.sh " + public.get_url() + "/install/update"+vp+".sh && bash update.sh"); vp = '_pro'
if hasattr(web.ctx.session,'getCloudPlugin'): del(web.ctx.session['getCloudPlugin']); public.ExecShell("wget -O update.sh " + public.get_url() +
return True; "/install/update" + vp + ".sh && bash update.sh")
if hasattr(web.ctx.session, 'getCloudPlugin'):
del(web.ctx.session['getCloudPlugin'])
return True
# 升级到专业版 # 升级到专业版
def UpdatePro(self, get): def UpdatePro(self, get):
public.ExecShell("wget -O update.sh " + public.get_url() + "/install/update_pro.sh && bash update.sh pro"); public.ExecShell("wget -O update.sh " + public.get_url() +
if hasattr(web.ctx.session,'getCloudPlugin'): del(web.ctx.session['getCloudPlugin']); "/install/update_pro.sh && bash update.sh pro")
return True; if hasattr(web.ctx.session, 'getCloudPlugin'):
del(web.ctx.session['getCloudPlugin'])
return True

@ -15,7 +15,6 @@
"pid": "1", "pid": "1",
"update": ["1.14.0", "1.12.2", "1.8.1", "1.15.3", "-Tengine2.2.2", "openresty"], "update": ["1.14.0", "1.12.2", "1.8.1", "1.15.3", "-Tengine2.2.2", "openresty"],
"versions": [ "versions": [
{"status": false, "version": "1.14", "run": false, "no": "", "task": "1"},
{"status": false, "version": "1.14", "run": false, "no": "", "task": "1"}, {"status": false, "version": "1.14", "run": false, "no": "", "task": "1"},
{"status": false, "version": "1.12", "run": false, "no": "", "task": "1"}, {"status": false, "version": "1.12", "run": false, "no": "", "task": "1"},
{"status": false, "version": "1.8", "run": false, "no": "", "task": "1"}, {"status": false, "version": "1.8", "run": false, "no": "", "task": "1"},

File diff suppressed because it is too large Load Diff

@ -14,6 +14,7 @@ reload(sys)
sys.setdefaultencoding('utf-8') sys.setdefaultencoding('utf-8')
import db import db
import public import public
import time
global pre, timeoutCount, logPath, isTask, oldEdate, isCheck global pre, timeoutCount, logPath, isTask, oldEdate, isCheck
@ -327,6 +328,7 @@ def systemTask():
count += 1 count += 1
except Exception, ex: except Exception, ex:
print str(ex) print str(ex)
import time
time.sleep(30) time.sleep(30)
systemTask() systemTask()

Loading…
Cancel
Save