def build_object_json(data_s): obj = public.dict_obj() obj.siteName = data_s['siteName'] obj.first_domain = data_s['siteName'] obj.key = data_s['key'] obj.csr = data_s['csr'] return obj
def set_crond(self): try: echo = public.md5(public.md5('renew_lets_ssl_bt')) cron_id = public.M('crontab').where('echo=?', (echo, )).getField('id') import crontab args_obj = public.dict_obj() if not cron_id: cronPath = public.GetConfigValue( 'setup_path') + '/cron/' + echo shell = 'python %s/panel/class/panelLets.py renew_lets_ssl ' % ( self.setupPath) public.writeFile(cronPath, shell) args_obj.id = public.M('crontab').add( 'name,type,where1,where_hour,where_minute,echo,addtime,status,save,backupTo,sType,sName,sBody,urladdress', ("续签Let's Encrypt证书", 'day', '', '0', '10', echo, time.strftime('%Y-%m-%d %X', time.localtime()), 0, '', 'localhost', 'toShell', '', shell, '')) crontab.crontab().set_cron_status(args_obj) else: cron_path = public.get_cron_path() if os.path.exists(cron_path): cron_s = public.readFile(cron_path) if cron_s.find(echo) == -1: public.M('crontab').where('echo=?', (echo, )).setField( 'status', 0) args_obj.id = cron_id crontab.crontab().set_cron_status(args_obj) except: pass
def PathDownload(self,fpath,dpath): #获得指定目录的信息 path = public.dict_obj() path.path = fpath path.start = "0" PDir =json.loads(self.Get_PathDir(path)) if not os.path.exists(dpath): os.mkdir(dpath) # 递归下载目录下的文件 for Dir in PDir["list"]: # 目标对象是文件夹 if Dir["isdir"] == 1: ndir = public.dict_obj() ndir.path = Dir["path"] ndir.start = "0" self.PathDownload(ndir, dpath + "/" + Dir["server_filename"]) else: # 下载目标文件 self.FileDownLoad(dpath + "/" + Dir["server_filename"], str(Dir["fs_id"]))
def connect(self, ssh_info=None): if ssh_info: self._ssh_info = ssh_info if not self._host: self._host = self._ssh_info['host'] # print('----------连接时的ssh_info--------------') if self._ssh_info['host'] in self._my_terms: if time.time() - self._my_terms[self._host].last_time < 86400: return True try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 262144) sock.connect((self._ssh_info['host'], int(self._ssh_info['port']))) except Exception as e: self._web_socket.send("\rServer connection failed!\r") return False # 使用Transport连接 p1 = paramiko.Transport(sock) p1.start_client() if not 'pkey' in self._ssh_info: self._ssh_info['pkey'] = None if not 'c_type' in self._ssh_info: self._ssh_info['c_type'] = None try: # 如果有pkey时则使用RSA私钥登录 if self._ssh_info['pkey'] and self._ssh_info['c_type']: # print('------使用私钥登陆---------') # 将RSA私钥转换为io对象,然后生成rsa_key对象 p_file = StringIO(self._ssh_info['pkey']) pkey = paramiko.RSAKey.from_private_key(p_file) p1.auth_publickey(username=self._ssh_info['username'].strip(), key=pkey) else: # print('-----------使用密码登陆-----------') p1.auth_password(username=self._ssh_info['username'].strip(), password=self._ssh_info['password']) except Exception as e: self._web_socket.send("\rWrong user name or password!\r") p1.close() return False self._my_terms[self._host] = public.dict_obj() self._my_terms[self._host].last_time = time.time() self._my_terms[self._host].connect_time = time.time() # 打开会话 self._my_terms[self._host].tty = p1.open_session() # 获取终端对象 self._my_terms[self._host].tty.get_pty(term='xterm', width=100, height=34) self._my_terms[self._host].tty.invoke_shell() # 记录登陆记录 #public.M('ssh_records').add('coll_user,ssh_user,host,cmd,addtime', (self._coll_user, self._ssh_info['username'], self._ssh_info['host'], 'login', int(time.time()))) #print("登录成功") self._my_terms[self._host].last_send = [] self._send_last = True self._connect_time = time.time() return True
def start(self): ''' @name 启动所有启动项 @author hwliang<2021-08-06> @param @return bool ''' run_list = self.get_run_list(public.dict_obj()) for run_name in run_list: if not self.is_run(run_name): self.start_run(run_name) return True
def uninstall(): # 备份数据库文件至目录 ${setup_path}/panel/data/plugin_encryption365_backup.db # 防止证书数据丢失, 待下次安装/升级插件时自动导入旧的数据库文件 public.ExecShell('cp -f /www/server/panel/plugin/encryption365/databases/main.db /www/server/panel/data/plugin_encryption365_backup.db') print('已完成数据库备份') # 调用Baota API删除已创建的CronTab db = get_baota_database().cursor() c = db.execute('select `id` from crontab where `echo` = "5eeb48072b7a0fc713483bd5ade1d59d"') cron_id = c.fetchall()[0][0] gets = public.dict_obj() gets.id = cron_id crontab().DelCrontab(gets) print('已删除 Encryption365 定时任务')
def get_verify_result(self, args): self.__PDATA['data']['oid'] = args.oid verify_info = self.request('get_verify_result') if verify_info['status'] in ['COMPLETE', False]: return verify_info is_file_verify = 'CNAME_CSR_HASH' != verify_info['data']['dcvList'][0][ 'dcvMethod'] verify_info['paths'] = [] verify_info['hosts'] = [] if verify_info['data']['application']['status'] == 'ongoing': return public.returnMsg(False, '订单出现问题,CA正在人工验证,若24小时内依然出现此提示,请联系宝塔') for dinfo in verify_info['data']['dcvList']: is_https = dinfo['dcvMethod'] == 'HTTPS_CSR_HASH' if is_https: is_https = 's' else: is_https = '' domain = dinfo['domainName'] if domain[:2] == '*.': domain = domain[2:] dinfo['domainName'] = domain if is_file_verify: siteRunPath = self.get_domain_run_path(domain) if domain[:4] == 'www.': domain = domain[4:] status = 0 url = 'http' + is_https + '://' + domain + '/.well-known/pki-validation/' + verify_info[ 'data']['DCVfileName'] get = public.dict_obj() get.url = url get.content = verify_info['data']['DCVfileContent'] status = self.check_url_txt(get) verify_info['paths'].append({'url': url, 'status': status}) if not siteRunPath: continue verify_path = siteRunPath + '/.well-known/pki-validation' if not os.path.exists(verify_path): os.makedirs(verify_path) verify_file = verify_path + '/' + verify_info['data'][ 'DCVfileName'] if os.path.exists(verify_file): continue public.writeFile(verify_file, verify_info['data']['DCVfileContent']) else: if domain[:4] == 'www.': domain = domain[4:] verify_info['hosts'].append(verify_info['data']['DCVdnsHost'] + '.' + domain) return verify_info
def install(): print("开始执行安装流程") if not os.path.exists(__plugin_path): os.makedirs(__plugin_path) copyfile(__plugin_path + "/icon.png", panelPath + "/BTPanel/static/img/soft_ico/ico-encryption365.png") print("检查并恢复备份的数据库文件...") backup_file = panelPath + '/data/plugin_encryption365_backup.db' new_database_file = panelPath + '/plugin/encryption365/databases/main.db' if os.path.isfile(backup_file) and not os.path.isfile(new_database_file): print("正在恢复备份的数据库文件...") copyfile(backup_file, new_database_file) os.remove(backup_file) # 增加Crone任务 PyEnv = get_python_env() print("PyEnv: ", get_python_env()) gets = public.dict_obj() gets.name = "Encryption365™ 证书自动化" gets.type = "minute-n" gets.where1 = "1" gets.hour = "" gets.minute = "" gets.week = "" gets.sName = "" gets.save = "" gets.sType = "toShell" gets.sBody = PyEnv + " " + __plugin_path + "/src/AutoRenew.py" gets.backupTo = "localhost" gets.urladdress = "undefined" gets.save_local = "undefined" gets.notice = "undefined" gets.notice_channel = "undefined" cronres = crontab().AddCrontab(gets) gets.notice = "0" gets.notice_channel = "" gets.save_local = "0" gets.urladdress = "" gets.id = cronres['id'] crontab().modify_crond(gets) print("安装完成咯!")
def connect_ssh(self): import paramiko self.ssh = paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: self.ssh.connect('127.0.0.1', public.GetSSHPort()) except: if public.GetSSHStatus(): try: self.ssh.connect('localhost', public.GetSSHPort()) except: return False import firewalls fw = firewalls.firewalls() get = public.dict_obj() get.status = '0' fw.SetSshStatus(get) self.ssh.connect('127.0.0.1', public.GetSSHPort()) get.status = '1' fw.SetSshStatus(get) self.shell = self.ssh.invoke_shell(term='xterm', width=100, height=29) self.shell.setblocking(0) return True
#coding: utf-8 import os,sys,time os.chdir('/www/server/panel/') sys.path.insert(0,"class/") import public oldEdate = public.readFile('data/edate.pl') if not oldEdate: oldEdate = '0000-00-00' mEdate = time.strftime('%Y-%m-%d',time.localtime()) edateSites = public.M('sites').where('edate>? AND edate<? AND (status=? OR status=?)',('0000-00-00',mEdate,1,u'正在运行')).field('id,name').select() import panelSite siteObject = panelSite.panelSite() for site in edateSites: get = public.dict_obj() get.id = site['id'] get.name = site['name'] siteObject.SiteStop(get) oldEdate = mEdate public.writeFile('data/edate.pl',mEdate)
def model(self,args): ''' @name 调用指定项目模型 @author hwliang<2021-07-15> @param args<dict_obj> { mod_name: string<模型名称> def_name: string<方法名称> data: JSON } ''' try: # 表单验证 if args['mod_name'] in ['base']: return public.return_status_code(1000,'错误的调用!') public.exists_args('def_name,mod_name',args) if args['def_name'].find('__') != -1: return public.return_status_code(1000,'调用的方法名称中不能包含“__”字符') if not re.match(r"^\w+$",args['mod_name']): return public.return_status_code(1000,'调用的模块名称中不能包含\w以外的字符') if not re.match(r"^\w+$",args['def_name']): return public.return_status_code(1000,'调用的方法名称中不能包含\w以外的字符') except: return public.get_error_object() # 参数处理 mod_name = "{}Model".format(args['mod_name'].strip()) def_name = args['def_name'].strip() # 指定模型是否存在 mod_file = "{}/projectModel/{}.py".format(public.get_class_path(),mod_name) if not os.path.exists(mod_file): return public.return_status_code(1003,mod_name) # 实例化 def_object = public.get_script_object(mod_file) if not def_object: return public.return_status_code(1000,'没有找到{}模型'.format(mod_name)) run_object = getattr(def_object.main(),def_name,None) if not run_object: return public.return_status_code(1000,'没有在{}模型中找到{}方法'.format(mod_name,def_name)) if not hasattr(args,'data'): args.data = {} if args.data: if isinstance(args.data,str): try: # 解析为dict_obj pdata = public.to_dict_obj(json.loads(args.data)) except: return public.get_error_object() else: pdata = args.data else: pdata = public.dict_obj() # 前置HOOK hook_index = '{}_{}_LAST'.format(mod_name.upper(),def_name.upper()) hook_result = public.exec_hook(hook_index,pdata) if isinstance(hook_result,public.dict_obj): pdata = hook_result # 桥接 elif isinstance(hook_result,dict): return hook_result # 响应具体错误信息 elif isinstance(hook_result,bool): if not hook_result: # 直接中断操作 return public.return_data(False,{},error_msg='前置HOOK中断操作') # 调用处理方法 result = run_object(pdata) # 后置HOOK hook_index = '{}_{}_END'.format(mod_name.upper(),def_name.upper()) hook_data = public.to_dict_obj({ 'args': pdata, 'result': result }) hook_result = public.exec_hook(hook_index,hook_data) if isinstance(hook_result,dict): result = hook_result['result'] return result