def del_pgsql_db(self, args): # 删除数据库 del_info = '' args = self.processing_parameter(args) # 处理前端传过来的参数 port = self.get_port(args)['data'] database = args.database del_bak = args.del_bak if int(del_bak) == 1: public.ExecShell("rm -rf {}_*".format(os.path.join(self.db_back_dir, database))) del_info += '删除备份文件成功 ' public.ExecShell('''echo "drop database {};"|su - postgres -c "/www/server/pgsql/bin/psql -p {} " '''.format(database, port)) dbuser_info_path = self.dbuser_info_path dbuser_info = '' if os.path.isfile(dbuser_info_path): with open(dbuser_info_path) as f: for i in f: if not i.strip(): continue if json.loads(i)['database'] == database: public.ExecShell('''echo "drop user {};"|su - postgres -c "/www/server/pgsql/bin/psql -p {} " '''.format(json.loads(i)['username'], port)) continue dbuser_info += i public.WriteFile(dbuser_info_path, dbuser_info, mode='w') # 删除客户端认证相关配置 config_file_path = self.get_data_directory(args)['data'] + "/pg_hba.conf" old_config = public.ReadFile(config_file_path) new_config = re.sub(r'host\s*{}.*'.format(database), '', old_config).strip() public.WriteFile(config_file_path, new_config) public.ExecShell("/etc/init.d/pgsql reload") # 返回数据到前端 return {'data': del_info + "删除数据库成功", "status": True}
def create_user(self, args): # 创建数据库和用户 args = self.processing_parameter(args) # 处理前端传过来的参数 listen_ip = args.listen_ip database = args.database if not re.match(r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}/\d+", listen_ip.strip()): return {'data': "你输入的权限不合法,添加失败!", "status": False} if listen_ip.strip() not in ["127.0.0.1/32", "localhost", "127.0.0.1"]: self.sed_conf("listen_addresses", "'*'") # 修改监听所有地址 public.ExecShell("/etc/init.d/pgsql restart") dbuser_info_path = self.dbuser_info_path if os.path.isfile(dbuser_info_path): with open(dbuser_info_path) as f: for i in f: if not i.strip(): continue if json.loads(i)['database'] == args.database: return {'data': "数据库已经存在", "status": False} if json.loads(i)['username'] == args.username: return {'data': "用户已经存在", "status": False} dbuser_info = {"database": database, "username": args.username, "password": args.password, "listen_ip": listen_ip} public.WriteFile(dbuser_info_path, json.dumps(dbuser_info) + "\n", mode='a') port = self.get_port(args)['data'] public.ExecShell('''echo "create database {} ;"|su - postgres -c "/www/server/pgsql/bin/psql -p {}" '''.format(args.database, port)) public.ExecShell('''echo "create user {};"|su - postgres -c "/www/server/pgsql/bin/psql -p {}" '''.format(args.username, port)) public.ExecShell('''echo "alter user {} with password '{}';"|su - postgres -c "/www/server/pgsql/bin/psql -p {}" '''.format(args.username, args.password, port)) public.ExecShell('''echo "GRANT ALL PRIVILEGES ON DATABASE {} TO {};"|su - postgres -c "/www/server/pgsql/bin/psql -p {}" '''.format(args.database, args.username, port)) config_file_path = self.get_data_directory(args)['data'] + "/pg_hba.conf" public.WriteFile(config_file_path.strip(), "\nhost {} {} {} md5".format(args.database, args.username, args.listen_ip), mode='a') public.ExecShell("/etc/init.d/pgsql reload") # 返回数据到前端 return {'data': "数据库创建成功", "status": True}
def __init__(self): if not os.path.exists(self.logPath): resutl = {} public.WriteFile(self.logPath, json.dumps(resutl)) if not os.path.exists(self.config): resutl = {} public.WriteFile(self.config, json.dumps(resutl))
def sys_config(self, args): if not hasattr(args, 'process'): config = { 'logs': self.__plugin_path + 'logs/', 'siteconf': self.__plugin_path + 'config/Site', 'http_process': 2, 'http_MaxMemory': 0, 'http_MaxCpuTime': 7200, 'http_MaxConnIp': 0 } else: config = { 'logs': self.__plugin_path + 'logs/', 'siteconf': self.__plugin_path + 'config/Site', 'http_process': args.process, 'http_MaxMemory': args.Memory, 'http_MaxCpuTime': args.CpuTime, 'http_MaxConnIp': args.ConnIp } #将config 写入sys.config 文件 public.WriteFile(self.__plugin_path + 'config/sys.config', json.dumps(config)) config = json.loads( public.readFile(self.__plugin_path + 'config/sys.config')) #将config 数组按照指定格式写入 /jws.conf Jws = ''' SiteLogDir=%s SiteConfigDir=%s httpd.processes=%s #: 1-24. (0 is auto) httpd.MaxTotalMemory=%s #: In megabytes. Set to 0 for auto. httpd.MaxCpuTime=%s #: In seconds. Set to 0 for unlimited. httpd.MaxConnPerIp=%s #: 0 is unlimited # httpd.User=www-data # php-fcgi.set=/usr/bin/php-cgi,8 # HTTPS/SSL Global default configuration ########################################## # CertificateFile = /xxxx/xx.crt # CertificateKeyFile = /xxxx/xx.key # SSL_TLS_Version = TLSv1.1 TLSv1.2 # TLSv1.0 TLSv1.1 TLSv1.2, default is SSLv23 # SSL_Ciphers = ECDHE-RSA-AES256-GCM-SHA384:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4:!DH:!DHE fastcgi.add=php|socket:/tmp/php-cgi-73.sock ''' % (config['logs'], config['siteconf'], config['http_process'], config['http_MaxMemory'], config['http_MaxCpuTime'], config['http_MaxConnIp']) public.WriteFile('/www/server/jexus/jws.conf', Jws) if not self.sys_status(): self.Site_SetDefault() os.popen('sudo -i /www/server/jexus/jws start') os.popen('sudo -i /www/server/jexus/jws restart') self.Site_ConfigAllStart() return json.dumps({ 'status': 'Success', 'mes': 'Set Jexus Gobal Config Success!' })
def save(self, get): try: data = json.loads(get['json']) os.system('mkdir -p ' + pluginPath + '/conf') public.WriteFile(pluginPath + '/conf/config.json', get['json'], mode='w+') keys = { "bindAddr": "bind_addr", "bindPort": "bind_port", "bindUdpPort": "bind_udp_port", "kcpBindPort": "kcp_bind_port", "proxyBindAddr": "proxy_bind_addr", "vhostHttpPort": "vhost_http_port", "vhostHttpsPort": "vhost_https_port", "vhostHttpTimeout": "vhost_http_timeout", "dashboardAddr": "dashboard_addr", "dashboardPort": "dashboard_port", "dashboardUser": "******", "dashboardPwd": "dashboard_pwd", # "assetsDir": "assets_dir", # "logFile": "log_file", "logLevel": "log_level", "logMaxDays": "log_max_days", "token": "token", "heartbeatTimeout": "heartbeat_timeout", # "allowPorts": "allow_ports", "maxPoolCount": "max_pool_count", "maxPortsPerClient": "max_ports_per_client", "subdomainHost": "subdomain_host", "tcpMux": "tcp_mux", "disableLogColor": "disable_log_color", # "custom404Page": "custom_404_page" } config = '[common]\n' for key in keys.keys(): if type(data[key]) == bool: if data[key] == True: data[key] = 'true' else: data[key] = 'false' if str(data[key]) != '': config += '%s = %s\n' % (keys[key], str(data[key])) if type(data['allowPorts']) == list and len( data['allowPorts']) > 0: config += 'allow_ports = %s\n' % ','.join(data['allowPorts']) config += 'log_file = %s/temp/frps.log\n' % pluginPath filename = pluginPath + '/conf/404.html' if not os.path.isfile(filename): public.WriteFile(filename, '', mode='w+') if data['enabledCustom404Page'] == True and os.path.getsize( filename) > 0: config += 'custom_404_page = %s\n' % filename public.WriteFile(frpsIniPath, config, mode='w+') return public.returnMsg(True, '保存成功') except ValueError: return public.returnMsg(False, '请求错误,请刷新页面重试')
def stop_jian(self,get): data = public.ReadFile(self.return_bashrc()) if re.search(self.return_python()+' /www/server/panel/class/ssh_security.py', data): public.WriteFile(self.return_bashrc(),data.replace(self.return_python()+' /www/server/panel/class/ssh_security.py login','')) if os.path.exists('/etc/bashrc'): if re.search('python /www/server/panel/class/ssh_security.py', data): public.WriteFile(self.return_bashrc(),data.replace(self.return_python()+' /www/server/panel/class/ssh_security.py login','')) return public.returnMsg(True, 'Closed successfully') else: return public.returnMsg(True, 'Closed successfully')
def __init__(self): if not os.path.exists(self.logPath): resutl={} public.WriteFile(self.logPath,json.dumps(resutl)) if not os.path.exists(self.config): resutl = {} public.WriteFile(self.config, json.dumps(resutl)) if os.path.exists(self.repair_json): self.__repair=json.loads(public.ReadFile(self.repair_json))
def sed_conf(self, name, val): # 替换配置文件 data_directory = self.get_data_directory("")['data'].strip() modify = '' conf_str = '' with open("{}/postgresql.conf".format(data_directory)) as f: for i in f: if i.strip().startswith(name): i = "{} = {} \n".format(name, val) modify = True conf_str += i public.WriteFile("{}/postgresql.conf".format(data_directory), conf_str, mode='w') if not modify: public.WriteFile("{}/postgresql.conf".format(data_directory), "\n{} = {}".format(name, val), mode='a+')
def Site_add(self, args): if os.path.exists(self.__plugin_path + 'config/Info/' + args.Name + '.json'): return json.dumps({'status': 'Failed', 'msg': '添加新站点失败,已经存在同名站点'}) else: Info = json.dumps({ 'SiteName': args.Name, 'SitePath': args.Path, 'SiteDomain': args.Domain, 'SiteStatus': 'new', 'SiteId': '' }) # 写入到Info文件夹 public.WriteFile( self.__plugin_path + 'config/Info/' + args.Name + '.json', Info) domian = args.Domain.split('\n') Domain = '' list = [] num = 0 for _domain in domian: if Domain == "": Domain = _domain else: Domain = Domain + ',' + _domain if not num == 0: list.append(_domain) num = num + 1 # 写入到Jexus的网站配置文件夹 Config = ''' port=2333 root=/ %s indexs=index.aspx host=%s nofile= /404.html nolog=no fastcgi.add=php|socket:/tmp/php-cgi-73.sock ''' % (args.Path, Domain) public.WriteFile(self.__plugin_path + 'config/Site/' + args.Name, Config) count = num - 1 webname = {'domain': domian[0], "domainlist": list, "count": count} return json.dumps({ 'status': 'Success', 'msg': '添加新站点成功', 'webname': webname, 'sitename': domian[0] })
def set_token(self, get): if 'request_token' in get: return public.returnMsg(False, 'CANT_SET_API_WIFTH_API') save_path = '/www/server/panel/config/api.json' data = json.loads(public.ReadFile(save_path)) if get.t_type == '1': token = public.GetRandomString(32) data['token'] = public.md5(token) public.WriteLog('SET_API', 'REGENERATE_API_TOKEN') elif get.t_type == '2': data['open'] = not data['open'] stats = { True: public.GetMsg("TURN_ON"), False: public.GetMsg("CLOSE") } public.WriteLog('SET_API', 'API_INTERFACE', (stats[data['open']], )) token = stats[data['open']] + public.GetMsg("SUCCESS") elif get.t_type == '3': data['limit_addr'] = get.limit_addr.split('\n') public.WriteLog('SET_API', 'CHANGE_IP_LIMIT', (get.limit_addr)) token = public.GetMsg("SAVE_SUCCESS") public.WriteFile(save_path, json.dumps(data)) return public.returnMsg(True, token)
def stop_jian(self,get): data = public.ReadFile('/etc/bashrc') if re.search('{}\/www\/server\/panel\/class\/ssh_security.py'.format(".*python\s+"), data): public.WriteFile('/etc/bashrc',re.sub('\n.*python\s+\/www\/server\/panel\/class\/ssh_security.py.*','',data)) return public.returnMsg(True, 'Closed successfully') else: return public.returnMsg(True, 'Closed successfully')
def save_conf(self, args): # 保存配置文件 # 处理前端传过来的参数 args = self.processing_parameter(args) config_file_path = self.get_data_directory(args)['data'] + "/postgresql.conf" result = public.WriteFile(config_file_path.strip(), args.text_conf, mode='w') # 返回数据到前端 return {'data': "保存成功", "status": True}
def get_api_config(self): tmp = public.ReadFile(self.save_path) if not tmp or not os.path.exists(self.save_path): data = {"open": False, "token": "", "limit_addr": []} public.WriteFile(self.save_path, json.dumps(data)) public.ExecShell("chmod 600 " + self.save_path) tmp = public.ReadFile(self.save_path) data = json.loads(tmp) is_save = False if not 'binds' in data: data['binds'] = [] is_save = True if not 'apps' in data: data['apps'] = [] is_save = True data['binds'] = sorted(data['binds'], key=lambda x: x['time'], reverse=True) if len(data['binds']) > 5: data['binds'] = data['binds'][:5] is_save = True if is_save: self.save_api_config(data) return data
def check_authorization_status(self, authorization_url, desired_status=None, dns_names_to_delete=[]): """ 检查授权的状态,验证dns有没有添加txt解析记录 """ print("Check authorization status") time.sleep(self.ACME_AUTH_STATUS_WAIT_PERIOD) # 等待 desired_status = desired_status or ["pending", "valid"] number_of_checks = 0 while True: headers = {"User-Agent": self.User_Agent} i = 0 while i < 3: try: check_authorization_status_response = requests.get( authorization_url, timeout=self.ACME_REQUEST_TIMEOUT, headers=headers) except Exception: i += 1 else: break else: sys.exit(json.dumps({"data": public.GetMsg("ACME_ERR3")})) authorization_status = check_authorization_status_response.json( )["status"] number_of_checks = number_of_checks + 1 if number_of_checks == self.ACME_AUTH_STATUS_MAX_CHECKS: msg = public.GetMsg( "SSL_CHECK_TIPS", (number_of_checks, self.ACME_AUTH_STATUS_MAX_CHECKS, self.ACME_AUTH_STATUS_WAIT_PERIOD)) print(msg) for i in dns_names_to_delete: # 验证失败后也删除添加的dns self.dns_class.delete_dns_record(i["dns_name"], i["domain_dns_value"]) sys.exit( json.dumps({ "status": False, "data": public.GetMsg("CHECK_TXT_ERR5"), "msg": msg, })) if authorization_status in desired_status: break else: print( "Failed to verify model txt wait {} seconds to re-verify model, returned information:" .format(self.ACME_AUTH_STATUS_WAIT_PERIOD)) print(check_authorization_status_response.json()) public.WriteFile(os.path.join( ssl_home_path, "check_authorization_status_response"), check_authorization_status_response.text, mode="w") # 等待 time.sleep(self.ACME_AUTH_STATUS_WAIT_PERIOD) print("End of checking authorization status") return check_authorization_status_response
def save_get_clint_conf(self, args): # 保存 pg_hba.conf 客户端认证配置文件 args = self.processing_parameter(args) # 处理前端传过来的参数 config_file_path = self.get_data_directory(args)['data'] + "/pg_hba.conf" public.WriteFile(config_file_path.strip(), args.text_conf, mode='w') public.ExecShell("/etc/init.d/pgsql reload") # 返回数据到前端 return {'data': "保存成功", "status": True}
def start(self, get): pid = self.__pid() if pid != False: return public.returnMsg(True, 'frps 已开启,PID:%s' % pid) service = '''[Unit] Description=Frp Server Service After=network.target [Service] Type=simple User=root Restart=on-failure RestartSec=5s ExecStart=%s -c %s [Install] WantedBy=multi-user.target''' % (frpsPath, frpsIniPath) # 使用 systemd 管理自启动 filename = '/etc/systemd/system/btp_frps.service' if os.path.isdir( '/etc/systemd/system') and not os.path.isfile(filename): public.WriteFile(filename, service, mode='w+') os.system('chown root:root %s' % filename) os.system('chmod 755 %s' % filename) if os.path.isfile(filename): os.system('systemctl enable btp_frps') os.system('systemctl start btp_frps') else: os.system('nohup %s -c %s &' % (frpsPath, frpsIniPath)) time.sleep(1) pid = self.__pid() if pid != False: return public.returnMsg(True, '开启成功,PID:%s' % pid) return public.returnMsg(False, '开启失败')
def apply_for_cert_issuance(self): print("申请颁发证书") identifiers = [] for domain_name in self.all_domain_names: identifiers.append({"type": "dns", "value": domain_name}) payload = {"identifiers": identifiers} url = self.ACME_NEW_ORDER_URL apply_for_cert_issuance_response = self.make_signed_acme_request( url=url, payload=payload) if apply_for_cert_issuance_response.status_code != 201: public.WriteFile(os.path.join(ssl_home_path, "apply_for_cert_issuance_response"), apply_for_cert_issuance_response.text, mode="w") raise ValueError( "申请证书颁发时出错: status_code={status_code} response={response}". format( status_code=apply_for_cert_issuance_response.status_code, response=self.log_response( apply_for_cert_issuance_response), )) apply_for_cert_issuance_response_json = apply_for_cert_issuance_response.json( ) finalize_url = apply_for_cert_issuance_response_json["finalize"] authorizations = apply_for_cert_issuance_response_json[ "authorizations"] print("申请颁发证书成功") return authorizations, finalize_url
def check_authorization_status(self, authorization_url, desired_status=None, dns_names_to_delete=[]): """ 检查授权的状态,验证dns有没有添加txt解析记录 """ print("检查授权状态") time.sleep(self.ACME_AUTH_STATUS_WAIT_PERIOD) # 等待 desired_status = desired_status or ["pending", "valid"] number_of_checks = 0 while True: headers = {"User-Agent": self.User_Agent} i = 0 while i < 3: try: check_authorization_status_response = requests.get( authorization_url, timeout=self.ACME_REQUEST_TIMEOUT, headers=headers) except Exception: i += 1 else: break else: sys.exit(json.dumps({"data": "与 Let's Encrypt 的网络请求超时"})) authorization_status = check_authorization_status_response.json( )["status"] number_of_checks = number_of_checks + 1 if number_of_checks == self.ACME_AUTH_STATUS_MAX_CHECKS: msg = "检查完成={0}.允许最大检查={1}. 检查之间的间隔={2}秒.".format( number_of_checks, self.ACME_AUTH_STATUS_MAX_CHECKS, self.ACME_AUTH_STATUS_WAIT_PERIOD, ) print(msg) for i in dns_names_to_delete: # 验证失败后也删除添加的dns self.dns_class.delete_dns_record(i["dns_name"], i["domain_dns_value"]) sys.exit( json.dumps({ "status": False, "data": "验证txt解析失败", "msg": msg, })) if authorization_status in desired_status: break else: print("验证dns txt 失败等待{}秒重新验证dns,返回的信息:".format( self.ACME_AUTH_STATUS_WAIT_PERIOD)) print(check_authorization_status_response.json()) public.WriteFile(os.path.join( ssl_home_path, "check_authorization_status_response"), check_authorization_status_response.text, mode="w") # 等待 time.sleep(self.ACME_AUTH_STATUS_WAIT_PERIOD) print("检查授权状态结束") return check_authorization_status_response
def create_task(self, task_name, task_type, task_shell, other=''): self.clean_log() public.M(self.__table).add('name,type,shell,other,addtime,status', (task_name, task_type, task_shell, other, int(time.time()), 0)) public.WriteFile(self.__task_tips, 'True') public.ExecShell("/etc/init.d/bt start") return True
def acme_register(self): print("acme注册") if self.PRIOR_REGISTERED: payload = {"onlyReturnExisting": True} elif self.contact_email: payload = { "termsOfServiceAgreed": True, "contact": ["mailto:{0}".format(self.contact_email)], } else: payload = {"termsOfServiceAgreed": True} url = self.ACME_NEW_ACCOUNT_URL acme_register_response = self.make_signed_acme_request(url=url, payload=payload) if acme_register_response.status_code not in [201, 200, 409]: public.WriteFile(os.path.join(ssl_home_path, "apply_for_cert_issuance_response"), acme_register_response.text, mode="w") raise ValueError( "注册时出错: status_code={status_code} response={response}".format( status_code=acme_register_response.status_code, response=self.log_response(acme_register_response), )) kid = acme_register_response.headers["Location"] setattr(self, "kid", kid) print("acme_注册_成功") return acme_register_response
def GetLocalIp(self): # 取本地外网IP try: filename = '/www/server/panel/data/iplist.txt' ipaddress = public.readFile(filename) if not ipaddress: try: import urllib2 except: import urllib as urllib2 urllib2 = urllib2.request url = 'http://pv.sohu.com/cityjson?ie=utf-8' opener = urllib2.urlopen(url) m_str = opener.read() if isinstance(m_str, bytes): ipaddress = re.search('\d+.\d+.\d+.\d+', m_str.decode('utf-8')).group(0) else: ipaddress = re.search('\d+.\d+.\d+.\d+', m_str).group(0) public.WriteFile(filename, ipaddress) c_ip = public.check_ip(ipaddress) if not c_ip: a, e = public.ExecShell("curl ifconfig.me") return a return ipaddress except: try: url = public.GetConfigValue('home') + '/Api/getIpAddress' return public.HttpGet(url) except: return public.GetHost()
def get_tmp_token(self,get): save_path = '/www/server/panel/config/api.json' if not 'request_token' in get: return public.returnMsg(False,'只能通过API接口获取临时密钥') data = json.loads(public.ReadFile(save_path)) data['tmp_token'] = public.GetRandomString(64) data['tmp_time'] = time.time() public.WriteFile(save_path,json.dumps(data)) return public.returnMsg(True,data['tmp_token'])
def get_tmp_token(self,get): save_path = '/www/server/panel/config/api.json' if not 'request_token' in get: return public.returnMsg(False,'Temporary key can only be obtained through the API interface') data = json.loads(public.ReadFile(save_path)) data['tmp_token'] = public.GetRandomString(64) data['tmp_time'] = time.time() public.WriteFile(save_path,json.dumps(data)) return public.returnMsg(True,data['tmp_token'])
def __init__(self): if not os.path.exists(self.__ClIENT_IP): public.WriteFile(self.__ClIENT_IP,json.dumps([])) self.__mail=send_mail.send_mail() self.__mail_config=self.__mail.get_settings() try: self.__ip_data = json.loads(public.ReadFile(self.__ClIENT_IP)) except: self.__ip_data=[]
def uploadExcel(self, args, path): file = self.UploadFile(args) df = pd.read_excel(file) json = df.to_json(orient='records') if os.path.exists(path): os.remove(path) if not os.path.exists(path): public.WriteFile(path, json) return {"data": json, "path": path}
def get_token(self, get): save_path = '/www/server/panel/config/api.json' if not os.path.exists(save_path): data = {"open": False, "token": "", "limit_addr": []} public.WriteFile(save_path, json.dumps(data)) public.ExecShell("chmod 600 " + save_path) data = json.loads(public.ReadFile(save_path)) data['token'] = "***********************************" data['limit_addr'] = '\n'.join(data['limit_addr']) return data
def start_jian(self, get): data = public.ReadFile('/etc/bashrc') if not re.search('python /www/server/panel/class/ssh_security.py', data): public.WriteFile( '/etc/bashrc', data.strip() + '\npython /www/server/panel/class/ssh_security.py login\n') return public.returnMsg(True, '开启成功') return public.returnMsg(False, '开启失败')
def __set_config(self,key=None,value=None): #是否需要初始化配置项 if not self.__config: self.__config = {} #是否需要设置配置值 if key: self.__config[key] = value #写入到配置文件 config_file = self.__plugin_path + 'config.json' public.WriteFile(config_file,json.dumps(self.__config)) return True
def Site_ConfigAllStart(self): for file in os.walk(self.__plugin_path + "config/Info/"): files = file[2] for SiteName in files: config = json.loads( public.readFile(self.__plugin_path + "config/Info/" + SiteName)) config['SiteStatus'] = 'start' public.WriteFile(self.__plugin_path + "config/Info/" + SiteName, json.dumps(config))
def start_jian(self, get): data = public.ReadFile(self.return_bashrc()) if not re.search( '{}\/www\/server\/panel\/class\/ssh_security.py'.format( ".*python\s+"), data): public.WriteFile( self.return_bashrc(), data.strip() + '\n' + self.return_python() + ' /www/server/panel/class/ssh_security.py login\n') return public.returnMsg(True, 'Open successfully') return public.returnMsg(False, 'Open failed')