def restart(self): yield self._lock.acquire() try: yield system.system('ifconfig', self.iface, '0.0.0.0') yield system.system('ifconfig', self.iface, 'down') finally: self._lock.release()
def _locked_cb(self, old_state, new_state): if self._iface_status_pub.get() >= IFSTATE.PLUGGED: yield system.system('ip', 'route', 'flush', 'table', self.table, 'dev', self.iface) if new_state: gateway = new_state['gateway'] ip = new_state['ip'] network_slashed = new_state['network_slashed'] yield system.system('ip', 'route', 'add', 'table', self.table, 'default', 'dev', self.iface, 'via', gateway, 'src', ip, 'onlink') yield system.system('ip', 'route', 'add', 'table', self.table, network_slashed, 'dev', self.iface, 'src', ip)
def __init__(self): self.interfaces = {} self.update_event = event.Event() self.update_interval = 1 self.radio_manager = radio_manager.RadioManager() self.inactive_penalty = config.get_parameter('inactive_penalty', 50) self.forced_interface = "" self.tunnel_interface = config.get_parameter('tunnel_interface', "") self.use_tunnel = True self.active_interfaces = [] self.basestation = config.get_parameter('base_station') # print "Resolving basestation IP. (Blocking operation.)" # self.basestation_ip = socket.gethostbyname(config.get_parameter('base_station')) # Add rules to guarantee that local routes go to the main table. # self.local_net_rule = ip_rule.IpRule(RULEID.LOCAL) # for subnet in config.get_parameter('local_networks'): # self.local_net_rule.add('to', subnet, 'lookup', 'main') self.local_net_rules = [] for (i, subnet) in enumerate(config.get_parameter('local_networks')): self.local_net_rules.append(ip_rule.IpRule(RULEID.LOCAL + i)) self.local_net_rules[i].add('to', subnet, 'lookup', 'main') # Add a rule to send through the vpn. if self.tunnel_interface: self.vpn_rule = ip_rule.IpRule(RULEID.DEFAULT) # Use LINK here because netlink_monitor's parsing rules don't # currently work on vpn interfaces. system.system('ip', 'route', 'flush', 'table', str(RULEID.DEFAULT)) netlink_monitor.get_state_publisher( self.tunnel_interface, IFSTATE.LINK).subscribe(self._refresh_default_route) # Create all the interfaces. interface_names = config.get_parameter('interfaces').keys() ifaceid = RULEID.FIRST_IFACE for iface in interface_names: try: new_iface = self.interfaces[iface] = interface.construct( iface, ifaceid) new_iface.score = InterfaceSelector.TERRIBLE_INTERFACE new_iface.prescore = InterfaceSelector.TERRIBLE_INTERFACE ifaceid += 1 except interface.NoType: print >> sys.stderr, "Interface %s has no type." % iface sys.exit(1) except interface.UnknownType, e: print >> sys.stderr, "Interface %s has unknown type %s." % ( iface, e) sys.exit(1) except:
def _locked_cb(self, old_state, new_state): #print "Address", self.iface, new_state if new_state is None or old_state is not None: if self._iface_status_pub.get() >= IFSTATE.PLUGGED: yield system.system('ifconfig', self.iface, '0.0.0.0') if new_state is not None: ip = new_state['ip'] ip_slashed = new_state['ip_slashed'] yield system.system('ip', 'addr', 'add', ip_slashed, 'dev', self.iface) # Send both request and response gratuitous arp. yield system.system('arping', '-q', '-c', '1', '-A', '-I', self.iface, ip) yield system.system('arping', '-q', '-c', '1', '-U', '-I', self.iface, ip)
def blank(pdf): """Add blank pages for every other page in a pdf file""" pages = int(system("pdftk {pdffile} dump_data | grep NumberOfPages".format(pdffile=pdf)).split(":")[1].strip()) cmdstring = "" for page in range(1, pages + 1): cmdstring += " A{page}-{page} B1-1".format(page=page) cmd = "pdftk A={pdffile} B=blank.pdf cat {cmdstring} output {pdffile_core}-blank.pdf".format(pdffile=pdf, cmdstring=cmdstring, pdffile_core=pdf.split(".")[0]) system(cmd)
def __init__(self): self.interfaces = {} self.update_event = event.Event() self.update_interval = 1 self.radio_manager = radio_manager.RadioManager() self.inactive_penalty = config.get_parameter('inactive_penalty', 50) self.forced_interface = "" self.tunnel_interface = config.get_parameter('tunnel_interface', "") self.use_tunnel = True self.active_interfaces = [] self.basestation = config.get_parameter('base_station') # print "Resolving basestation IP. (Blocking operation.)" # self.basestation_ip = socket.gethostbyname(config.get_parameter('base_station')) # Add rules to guarantee that local routes go to the main table. # self.local_net_rule = ip_rule.IpRule(RULEID.LOCAL) # for subnet in config.get_parameter('local_networks'): # self.local_net_rule.add('to', subnet, 'lookup', 'main') self.local_net_rules = [] for (i, subnet) in enumerate(config.get_parameter('local_networks')): self.local_net_rules.append(ip_rule.IpRule(RULEID.LOCAL+i)) self.local_net_rules[i].add('to', subnet, 'lookup', 'main') # Add a rule to send through the vpn. if self.tunnel_interface: self.vpn_rule = ip_rule.IpRule(RULEID.DEFAULT) # Use LINK here because netlink_monitor's parsing rules don't # currently work on vpn interfaces. system.system('ip', 'route', 'flush', 'table', str(RULEID.DEFAULT)) netlink_monitor.get_state_publisher(self.tunnel_interface, IFSTATE.LINK).subscribe(self._refresh_default_route) # Create all the interfaces. interface_names = config.get_parameter('interfaces').keys() ifaceid = RULEID.FIRST_IFACE for iface in interface_names: try: new_iface = self.interfaces[iface] = interface.construct(iface, ifaceid) new_iface.score = InterfaceSelector.TERRIBLE_INTERFACE new_iface.prescore = InterfaceSelector.TERRIBLE_INTERFACE ifaceid += 1 except interface.NoType: print >> sys.stderr, "Interface %s has no type."%iface sys.exit(1) except interface.UnknownType, e: print >> sys.stderr, "Interface %s has unknown type %s."%(iface, e) sys.exit(1) except:
def main(): app = system.system() app.setup() #app.switch_mode(mode.play.play()) app.switch_mode(mode.menu.menu()) app.run()
def config(pdata = None): comReturn = comm.local() if comReturn: return comReturn if request.method == method_get[0] and not pdata: import system,wxapp,config c_obj = config.config() data = system.system().GetConcifInfo() data['lan'] = public.GetLan('config') try: data['wx'] = wxapp.wxapp().get_user_info(None)['msg'] except: data['wx'] = '当前未绑定微信号' data['api'] = '' data['ipv6'] = ''; sess_out_path = 'data/session_timeout.pl' if not os.path.exists(sess_out_path): public.writeFile(sess_out_path,'86400') workers_p = 'data/workers.pl' if not os.path.exists(workers_p): public.writeFile(workers_p,'1') data['workers'] = int(public.readFile(workers_p)) s_time_tmp = public.readFile(sess_out_path) if not s_time_tmp: s_time_tmp = '0' data['session_timeout'] = int(s_time_tmp) if c_obj.get_ipv6_listen(None): data['ipv6'] = 'checked' if c_obj.get_token(None)['open']: data['api'] = 'checked' data['basic_auth'] = c_obj.get_basic_auth_stat(None) data['basic_auth']['value'] = public.GetMsg("CLOSE") if data['basic_auth']['open']: data['basic_auth']['value'] = public.GetMsg("OPEN") data['debug'] = '' if app.config['DEBUG']: data['debug'] = 'checked' data['is_local'] = '' if public.is_local(): data['is_local'] = 'checked' return render_template( 'config.html',data=data) import config defs = ('set_coll_open','get_qrcode_data','check_two_step','set_two_step_auth','get_key','get_php_session_path','set_php_session_path','get_cert_source','set_local','set_debug','get_panel_error_logs','clean_panel_error_logs','get_basic_auth_stat','set_basic_auth','get_cli_php_version','get_tmp_token','set_cli_php_version','DelOldSession', 'GetSessionCount', 'SetSessionConf', 'GetSessionConf','get_ipv6_listen','set_ipv6_status','GetApacheValue','SetApacheValue','GetNginxValue','SetNginxValue','get_token','set_token','set_admin_path','is_pro','get_php_config','get_config','SavePanelSSL','GetPanelSSL','GetPHPConf','SetPHPConf','GetPanelList','AddPanelInfo','SetPanelInfo','DelPanelInfo','ClickPanelInfo','SetPanelSSL','SetTemplates','Set502','setPassword','setUsername','setPanel','setPathInfo','setPHPMaxSize','getFpmConfig','setFpmConfig','setPHPMaxTime','syncDate','setPHPDisable','SetControl','ClosePanel','AutoUpdatePanel','SetPanelLock') return publicObject(config.config(),defs,None,pdata);
def config(pdata=None): comReturn = comm.local() if comReturn: return comReturn if request.method == method_get[0] and not pdata: import system, wxapp, config data = system.system().GetConcifInfo() data['lan'] = public.GetLan('config') data['wx'] = wxapp.wxapp().get_user_info(None)['msg'] data['api'] = '' data['ipv6'] = '' if config.config().get_ipv6_listen(None): data['ipv6'] = 'checked' if config.config().get_token(None)['open']: data['api'] = 'checked' return render_template('config.html', data=data) import config configObject = config.config() defs = ('DelOldSession', 'GetSessionCount', 'SetSessionConf', 'GetSessionConf', 'get_ipv6_listen', 'set_ipv6_status', 'GetApacheValue', 'SetApacheValue', 'GetNginxValue', 'SetNginxValue', 'get_token', 'set_token', 'set_admin_path', 'is_pro', 'get_php_config', 'get_config', 'SavePanelSSL', 'GetPanelSSL', 'GetPHPConf', 'SetPHPConf', 'GetPanelList', 'AddPanelInfo', 'SetPanelInfo', 'DelPanelInfo', 'ClickPanelInfo', 'SetPanelSSL', 'SetTemplates', 'Set502', 'setPassword', 'setUsername', 'setPanel', 'setPathInfo', 'setPHPMaxSize', 'getFpmConfig', 'setFpmConfig', 'setPHPMaxTime', 'syncDate', 'setPHPDisable', 'SetControl', 'ClosePanel', 'AutoUpdatePanel', 'SetPanelLock') return publicObject(configObject, defs, None, pdata)
def eddieguts(Config, eddieHistory): # instantiate a process list log.log( "<eddie>eddieguts(), creating process object", 8 ) directive.plist = proc.procList() # instantiate a disk usage list log.log( "<eddie>eddieguts(), creating df object", 8 ) directive.dlist = df.dfList() # instantiate a netstat list log.log( "<eddie>eddieguts(), creating netstat object", 8 ) directive.nlist = netstat.netstat() # instantiate a system object log.log( "<eddie>eddieguts(), creating system object", 8 ) directive.system = system.system() if module_iostat: # instantiate an iostat object log.log( "<eddie>eddieguts(), creating iostat object", 8 ) directive.iostat = iostat.iostat() # Now do all the checking log.log( "<eddie>eddieguts(), beginning checks", 7 ) check(Config) # Save history (debug.. FS only for now...) eddieHistory.save('FS',directive.dlist)
def UpdateDB(corp, victims) : chars = corp.chars systems = corp.systems NewNotifs = [] for name, char in chars.items() : print("Loading data for " + name + "...") NewNotifs += char.GetNotifications() #NewNotifs = NewNotifs + char.GetNotifications() ProcessKills(NewNotifs, victims) for n in NewNotifs : if n.system not in corp.systems : corp.systems[n.system] = system.system(n.system, corp.ID) if n.type == 'plex' : n.char.addPlex(n) corp.addPlex(n) corp.systems[n.system].addPlex(n) if n.type == 'kill' : corp.systems[n.system].addKill(n) n.char.addKill(n) corp.addKill(n) for i in [chars, systems] : for k, v in i.items() : v.save() corp.save()
def system(pdata = None): comReturn = comm.local() if comReturn: return comReturn import system sysObject = system.system() defs = ('get_io_info','UpdatePro','GetAllInfo','GetNetWorkApi','GetLoadAverage','ClearSystem','GetNetWorkOld','GetNetWork','GetDiskInfo','GetCpuInfo','GetBootTime','GetSystemVersion','GetMemInfo','GetSystemTotal','GetConcifInfo','ServiceAdmin','ReWeb','RestartServer','ReMemory','RepPanel') return publicObject(sysObject,defs,None,pdata);
def __init__(self): if not self.__system: self.__system = system.system() if not self.__plugin: self.__plugin = panelPlugin.panelPlugin() if not self.__ajax: self.__ajax = ajax.ajax()
def checkBackup(self): if cache.get('check_backup'): return None #检查备份脚本是否存在 filePath = public.GetConfigValue('setup_path') + '/panel/script/backup' if not os.path.exists(filePath): public.downloadFile( public.GetConfigValue('home') + '/linux/backup.sh', filePath) #检查日志切割脚本是否存在 filePath = public.GetConfigValue( 'setup_path') + '/panel/script/logsBackup' if not os.path.exists(filePath): public.downloadFile( public.GetConfigValue('home') + '/linux/logsBackup.py', filePath) #检查计划任务服务状态 import system sm = system.system() if os.path.exists('/etc/init.d/crond'): if not public.process_exists('crond'): public.ExecShell('/etc/init.d/crond start') elif os.path.exists('/etc/init.d/cron'): if not public.process_exists('cron'): public.ExecShell('/etc/init.d/cron start') elif os.path.exists('/usr/lib/systemd/system/crond.service'): if not public.process_exists('crond'): public.ExecShell('systemctl start crond') cache.set('check_backup', True, 3600)
def testCpu(self, get, n=1): data = {} data['cpuCount'] = psutil.cpu_count() if not hasattr(get, 'type'): get.type = '0' import re cpuinfo = open('/proc/cpuinfo', 'r').read() rep = "model\s+name\s+:\s+(.+)" tmp = re.search(rep, cpuinfo) data['cpuType'] = "" if tmp: data['cpuType'] = tmp.groups()[0] import system data['system'] = system.system().GetSystemVersion() path = '/www/server/panel/plugin/score/testcpu' if not os.path.exists(path): os.system('gcc ' + path + '.c -o ' + path + ' -lpthread') start = time.time() os.system(path + ' 32 ' + get.type) end = time.time() data['score'] = int(400 * 10 / (end - start)) if not os.path.exists(path): data['score'] = 0 self.writeScore('cpu' + get.type, data['score']) return data pass
def GET(self): import system data = system.system().GetConcifInfo() data['siteCount'] = public.M('sites').count() data['ftpCount'] = public.M('ftps').count() data['databaseCount'] = public.M('databases').count() data['lan'] = public.getLan('index') return render.index(data)
def funObj(self): import system sysObject = system.system() defs = ('ClearSystem', 'GetNetWorkOld', 'GetNetWork', 'GetDiskInfo', 'GetCpuInfo', 'GetBootTime', 'GetSystemVersion', 'GetMemInfo', 'GetSystemTotal', 'GetConcifInfo', 'ServiceAdmin', 'ReWeb', 'RestartServer', 'ReMemory', 'RepPanel') return publicObject(sysObject, defs)
def _cb(self, old_state, new_state): plugged, up = new_state self.state = new_state if plugged and not up and not self._is_shutdown: yield self._lock.acquire() try: yield system.system('ifconfig', self.iface, 'up') finally: self._lock.release()
def _set_or_add(self, remove_old, args): """Changes/adds the rule. Call with no arguments to clear the rule.""" if self.is_shutdown: return yield self._lock.acquire() try: # Are we replacing a rule with itself? if remove_old and self.prev and args == self.prev: return # Add new rule if args: yield system.system('ip', 'rule', 'add', "priority", self.priority, *args) # Add remove old rule if self.prev and remove_old: yield system.system('ip', 'rule', 'del', "priority", self.priority, *self.prev) self.prev = args self.state_pub.set(args) finally: self._lock.release()
def LoadSystems(corpid, fpath = vars.systems) : systems = {} for fname in os.listdir(fpath + corpid + '/systems/') : try : with open(fpath + corpid + '/systems/' + fname, 'r') as file : js = json.load(file) newsys = system.system(js['name'], corpid) systems[js['name']] = newsys finally : pass return systems
def flush(self): self.prev = () # Won't hurt to do it here, just means we might not # delete during ongoing set. Ensures it is set at # end of construction. yield self._lock.acquire() try: retcode = None while not retcode: retcode = yield system.system(system.Quiet, 'ip', 'rule', 'del', 'priority', self.priority) finally: self._lock.release()
def SetSwap(self, get): swapFile = '/www/swap' if os.path.exists(swapFile): os.system('swapoff ' + swapFile) os.system('rm -f ' + swapFile) os.system('sed -i "/' + swapFile.replace('/', '\\/') + '/d" /etc/fstab') if float(get.size) > 1: import system disk = system.system().GetDiskInfo() dsize = 0 isSize = True for d in disk: if d['path'] == '/www': dsize = d['size'][2] if d['path'] == '/': if not dsize: dsize = d['size'][2] if dsize.find('T') != -1: fsize = dsize.replace('T', '') if (float(fsize) * 1024 * 1024) < float(get.size): isSize = False if dsize.find('G') != -1: fsize = dsize.replace('G', '') if (float(fsize) * 1024) < float(get.size): isSize = False if dsize.find('M') != -1: fsize = dsize.replace('M', '') if float(fsize) < float(get.size): isSize = False if not isSize: data = self.GetSwap(get) data['status'] = False data['msg'] = '失败,磁盘空间不足,当前可用空间:' + dsize return data #判断是否使用fallocate #isfall = public.ExecShell("fallocate --version|grep linux")[0] #if len(isfall) > 5: # os.system('fallocate -l %sM %s' %(get.size,swapFile)) #else: os.system('dd if=/dev/zero of=' + swapFile + ' bs=1M count=' + get.size) if not os.path.exists(swapFile): return public.returnMsg(False, '创建swap失败') os.system("chmod 600 " + swapFile) os.system('mkswap -f ' + swapFile) os.system('swapon ' + swapFile) os.system('echo "' + swapFile + ' swap swap defaults 0 0" >> /etc/fstab') data = self.GetSwap(get) data['status'] = True data['msg'] = '设置成功' return data
def GET(self): import system data = system.system().GetConcifInfo() data['siteCount'] = public.M('sites').count() data['ftpCount'] = public.M('ftps').count() data['databaseCount'] = public.M('databases').count() data['lan'] = public.getLan('index') data['endtime'] = time.strftime('%Y-%m-%d',time.localtime(time.time())) if 'vip' in web.ctx.session: data['endtime'] = '<span>'+time.strftime('%Y-%m-%d',time.localtime(web.ctx.session.vip['msg']['endtime']))+'</span><a href="/vpro" class="btlink xufei"> 续费</a>'; if not web.ctx.session.vip['msg']['endtime']: data['endtime'] = '<span style="color: #fc6d26;font-weight: bold;">永久授权</span>'; return render.index(data)
def GetSshInfo(self, get): port = public.get_ssh_port() pid_file = '/run/sshd.pid' if os.path.exists(pid_file): pid = int(public.readFile(pid_file)) status = public.pid_exists(pid) else: import system panelsys = system.system() version = panelsys.GetSystemVersion() if os.path.exists('/usr/bin/apt-get'): if os.path.exists('/etc/init.d/sshd'): status = public.ExecShell( "service sshd status | grep -P '(dead|stop)'|grep -v grep" ) else: status = public.ExecShell( "service ssh status | grep -P '(dead|stop)'|grep -v grep" ) else: if version.find(' 7.') != -1 or version.find( ' 8.') != -1 or version.find('Fedora') != -1: status = public.ExecShell( "systemctl status sshd.service | grep 'dead'|grep -v grep" ) else: status = public.ExecShell( "/etc/init.d/sshd status | grep -e 'stopped' -e '已停'|grep -v grep" ) # return status; if len(status[0]) > 3: status = False else: status = True isPing = True try: file = '/etc/sysctl.conf' conf = public.readFile(file) rep = r"#*net\.ipv4\.icmp_echo_ignore_all\s*=\s*([0-9]+)" tmp = re.search(rep, conf).groups(0)[0] if tmp == '1': isPing = False except: isPing = True data = {} data['port'] = port data['status'] = status data['ping'] = isPing return data
def GetSshInfo(self, get): file = '/etc/ssh/sshd_config' conf = public.readFile(file) if not conf: conf = '' rep = "#*Port\s+([0-9]+)\s*\n" tmp1 = re.search(rep, conf) port = '22' if tmp1: port = tmp1.groups(0)[0] import system panelsys = system.system() version = panelsys.GetSystemVersion() if os.path.exists('/usr/bin/apt-get'): if os.path.exists('/etc/init.d/sshd'): status = public.ExecShell( "service sshd status | grep -P '(dead|stop)'|grep -v grep") else: status = public.ExecShell( "service ssh status | grep -P '(dead|stop)'|grep -v grep") else: if version.find(' 7.') != -1: status = public.ExecShell( "systemctl status sshd.service | grep 'dead'|grep -v grep") else: status = public.ExecShell( "/etc/init.d/sshd status | grep -e 'stopped' -e '已停'|grep -v grep" ) # return status; if len(status[0]) > 3: status = False else: status = True isPing = True try: file = '/etc/sysctl.conf' conf = public.readFile(file) rep = "#*net\.ipv4\.icmp_echo_ignore_all\s*=\s*([0-9]+)" tmp = re.search(rep, conf).groups(0)[0] if tmp == '1': isPing = False except: isPing = True data = {} data['port'] = port data['status'] = status data['ping'] = isPing return data
def submit_error(err_msg = None): try: if os.path.exists('/www/server/panel/not_submit_errinfo.pl'): return False from BTPanel import request import system if not err_msg: err_msg = get_error_info() pdata = {} pdata['err_info'] = err_msg pdata['path_full'] = request.full_path pdata['version'] = 'Linux-Panel-%s' % version() pdata['os'] = system.system().GetSystemVersion() pdata['py_version'] = sys.version pdata['install_date'] = int(os.stat('/www/server/panel/class/common.py').st_mtime) httpPost("http://www.bt.cn/api/panel/s_error",pdata,timeout=3) except: pass
def GetSSHStatus(): if os.path.exists('/usr/bin/apt-get'): status = ExecShell("service ssh status | grep -P '(dead|stop)'") else: import system panelsys = system.system(); version = panelsys.GetSystemVersion(); if version.find(' 7.') != -1: status = ExecShell("systemctl status sshd.service | grep 'dead'") else: status = ExecShell("/etc/init.d/sshd status | grep -e 'stopped' -e '已停'") if len(status[0]) > 3: status = False else: status = True return status
def initialize(): pl.close('all') global info, network, system, traces, torus, sweepingPhasespace reload(model) info = nf.info() network = netw.network(info=info) system = sys.system(info=info, network=network) traces = tra.traces(system, network, info=info) torus = tor.torus(system, network, traces, info=info) network.system = system system.traces = traces ## customize system for web system.setParams(epsilon=0.3) system.ax.set_xlabel(r'Inactivation Variable') system.ax.set_ylabel(r'Voltage Variable') system.ax.set_title('') system.fig.tight_layout() plugins.connect(system.fig, DragPlugin(eventHandlerURL="updatesystem", radioButtonID="systemRadio")) # customize network network.ax.patch.set_facecolor('#777777') network.moveText(2, [0.02, -0.1]) network.moveText(3, [0.02, -0.1]) network.ax.texts[6].set_text('1') network.ax.texts[7].set_text('2') network.ax.texts[8].set_text('3') plugins.connect(network.fig, DragPlugin(eventHandlerURL="updatenetwork", radioButtonID="networkRadio")) # customize traces traces.ax.patch.set_facecolor('#777777') traces.fig.tight_layout() # customize torus torus.ax_traces.set_xlabel(r'phase lag: 1-2') torus.ax_basins.set_xlabel(r'phase lag: 1-2') torus.ax_traces.set_ylabel(r'phase lag: 1-3') torus.fig.tight_layout() torus.switch_processor() # switches on the gpu if available if torus.USE_GPU: torus.setGridsize(24) plugins.connect(torus.fig, ClickPlugin(eventHandlerURL="updatetorus", radioButtonID="torusRadio")) # reload timing variable sweepingPhasespace = False;
def config(pdata=None): comReturn = comm.local() if comReturn: return comReturn if request.method == method_get[0] and not pdata: import system, wxapp data = system.system().GetConcifInfo() data['lan'] = public.GetLan('config') data['wx'] = wxapp.wxapp().get_user_info(None)['msg'] return render_template('config.html', data=data) import config configObject = config.config() defs = ('set_admin_path', 'is_pro', 'get_php_config', 'get_config', 'SavePanelSSL', 'GetPanelSSL', 'GetPHPConf', 'SetPHPConf', 'GetPanelList', 'AddPanelInfo', 'SetPanelInfo', 'DelPanelInfo', 'ClickPanelInfo', 'SetPanelSSL', 'SetTemplates', 'Set502', 'setPassword', 'setUsername', 'setPanel', 'setPathInfo', 'setPHPMaxSize', 'getFpmConfig', 'setFpmConfig', 'setPHPMaxTime', 'syncDate', 'setPHPDisable', 'SetControl', 'ClosePanel', 'AutoUpdatePanel', 'SetPanelLock') return publicObject(configObject, defs, None, pdata)
def SetSwap(self,get): swapFile = '/www/swap' if os.path.exists(swapFile): os.system('swapoff ' + swapFile) os.system('rm -f ' + swapFile) os.system('sed -i "/'+swapFile.replace('/','\\/')+'/d" /etc/fstab') if float(get.size) > 1: import system disk = system.system().GetDiskInfo() dsize = 0 isSize = True for d in disk: if d['path'] == '/www': dsize = d['size'][2] if d['path'] == '/': if not dsize: dsize = d['size'][2] if dsize.find('T') != -1: fsize = dsize.replace('T','') if (float(fsize) * 1024 * 1024) < float(get.size): isSize = False if dsize.find('G') != -1: fsize = dsize.replace('G','') if (float(fsize) * 1024) < float(get.size): isSize = False if dsize.find('M') != -1: fsize = dsize.replace('M','') if float(fsize) < float(get.size): isSize = False if not isSize: data = self.GetSwap(get) data['status'] = False data['msg'] = '失败,磁盘空间不足,当前可用空间:' + dsize return data os.system('dd if=/dev/zero of='+swapFile+' bs=1M count=' + get.size) os.system('mkswap -f ' + swapFile) os.system('swapon ' + swapFile) os.system('echo "'+ swapFile +' swap swap defaults 0 0" >> /etc/fstab') data = self.GetSwap(get) data['status'] = True data['msg'] = '设置成功' return data
def config(pdata=None): comReturn = comm.local() if comReturn: return comReturn if request.method == method_get[0] and not pdata: import system, wxapp, config data = system.system().GetConcifInfo() data['lan'] = public.GetLan('config') try: data['wx'] = wxapp.wxapp().get_user_info(None)['msg'] except: data['wx'] = '当前未绑定微信号' data['api'] = '' data['ipv6'] = '' sess_out_path = 'data/session_timeout.pl' if not os.path.exists(sess_out_path): public.writeFile(sess_out_path, '86400') workers_p = 'data/workers.pl' if not os.path.exists(workers_p): public.writeFile(workers_p, '1') data['workers'] = int(public.readFile(workers_p)) data['session_timeout'] = int(public.readFile(sess_out_path)) if config.config().get_ipv6_listen(None): data['ipv6'] = 'checked' if config.config().get_token(None)['open']: data['api'] = 'checked' return render_template('config.html', data=data) import config configObject = config.config() defs = ('get_cli_php_version', 'get_tmp_token', 'set_cli_php_version', 'DelOldSession', 'GetSessionCount', 'SetSessionConf', 'GetSessionConf', 'get_ipv6_listen', 'set_ipv6_status', 'GetApacheValue', 'SetApacheValue', 'GetNginxValue', 'SetNginxValue', 'get_token', 'set_token', 'set_admin_path', 'is_pro', 'get_php_config', 'get_config', 'SavePanelSSL', 'GetPanelSSL', 'GetPHPConf', 'SetPHPConf', 'GetPanelList', 'AddPanelInfo', 'SetPanelInfo', 'DelPanelInfo', 'ClickPanelInfo', 'SetPanelSSL', 'SetTemplates', 'Set502', 'setPassword', 'setUsername', 'setPanel', 'setPathInfo', 'setPHPMaxSize', 'getFpmConfig', 'setFpmConfig', 'setPHPMaxTime', 'syncDate', 'setPHPDisable', 'SetControl', 'ClosePanel', 'AutoUpdatePanel', 'SetPanelLock') return publicObject(configObject, defs, None, pdata)
def GetSshInfo(self,get): file = '/etc/ssh/sshd_config' conf = public.readFile(file) rep = "#*Port\s+([0-9]+)\s*\n" port = re.search(rep,conf).groups(0)[0] import system panelsys = system.system(); version = panelsys.GetSystemVersion(); if not os.path.exists('/etc/redhat-release'): status = public.ExecShell("service ssh status | grep 'dead'") else: if version.find(' 7.') != -1: status = public.ExecShell("systemctl status sshd.service | grep 'dead'") else: status = public.ExecShell("/etc/init.d/sshd status | grep -e 'stopped' -e '已停'") # return status; if len(status[0]) > 3: status = False else: status = True isPing = True try: file = '/etc/sysctl.conf' conf = public.readFile(file) rep = "#*net\.ipv4\.icmp_echo_ignore_all\s*=\s*([0-9]+)" tmp = re.search(rep,conf).groups(0)[0] if tmp == '1': isPing = False except: isPing = True data = {} data['port'] = port data['status'] = status data['ping'] = isPing return data
def GetDir(self, get): get.path = get.path.encode('utf-8') #if get.path.find('/opt/slemp/wwwroot') == -1: get.path = '/opt/slemp/wwwroot'; if not os.path.exists(get.path): get.path = '/opt/slemp' import pwd dirnames = [] filenames = [] for filename in os.listdir(get.path): try: filePath = (get.path + '/' + filename).encode('utf8') if os.path.islink(filePath): continue stat = os.stat(filePath) accept = str(oct(stat.st_mode)[-3:]) mtime = str(int(stat.st_mtime)) user = '' try: user = pwd.getpwuid(stat.st_uid).pw_name except: user = str(stat.st_uid) size = str(stat.st_size) if os.path.isdir(filePath): dirnames.append(filename + ';' + size + ';' + mtime + ';' + accept + ';' + user) else: filenames.append(filename + ';' + size + ';' + mtime + ';' + accept + ';' + user) except: continue data = {} data['DIR'] = sorted(dirnames) data['FILES'] = sorted(filenames) data['PATH'] = get.path if hasattr(get, 'disk'): import system data['DISK'] = system.system().GetDiskInfo() return data
def funObj(self): import system,json get = web.input() sysObject = system.system() defs = ( 'GetNetWork', 'GetDiskInfo', 'GetCpuInfo', 'GetBootTime', 'GetSystemVersion', 'GetMemInfo', 'GetSystemTotal', 'ServiceAdmin', 'StatusNginx', 'StatusMySQL', 'StatusPHP', 'PHPMyAdminExt', 'RestartServer' ) for key in defs: if key == get.action: fun = 'sysObject.'+key+'()' return public.getJson(eval(fun)) return public.returnJson(False,'Invalid specified parameter!')
def testCpu(self,get,n = 1): data = {} data['cpuCount'] = psutil.cpu_count(); if not hasattr(get,'type'): get.type = '0'; import re; cpuinfo = open('/proc/cpuinfo','r').read(); rep = "model\s+name\s+:\s+(.+)" tmp = re.search(rep,cpuinfo); data['cpuType'] = "" if tmp: data['cpuType'] = tmp.groups()[0]; import system data['system'] = system.system().GetSystemVersion(); path = '/www/server/panel/plugin/score/testcpu'; if not os.path.exists(path): os.system('gcc '+path+'.c -o ' +path + ' -lpthread'); start = time.time(); os.system(path + ' 32 ' + get.type); end = time.time(); data['score'] = int(400 * 10 / (end - start)); if not os.path.exists(path): data['score'] = 0; self.writeScore('cpu'+get.type, data['score']) return data; pass
def funObj(self): import system sysObject = system.system() defs = ('GetLoadAverage','ClearSystem','GetNetWorkOld','GetNetWork','GetDiskInfo','GetCpuInfo','GetBootTime','GetSystemVersion','GetMemInfo','GetSystemTotal','GetConcifInfo','ServiceAdmin','ReWeb','RestartServer','ReMemory','RepPanel') return publicObject(sysObject,defs);
#!/usr/bin/env python import system as sys import traces as tra import info as nf import pylab as pl pos_info = '+0+600' pos_tra = '+300+600' pos_sys = '+0+0' i = nf.info(position=pos_info) s = sys.system(info=i, position=pos_sys) t = tra.traces(s, info=i, position=pos_tra) if pl.get_backend() == 'TkAgg': s.fig.tight_layout() t.fig.tight_layout() pl.show()
#import glob #import shutil import os import sys import files import string import re #import fasta #import alignement import system import sofTraitementBWA import traitementSamtools #from operator #import itemgetter csys = system.system() #from libtools import files def lanceVarfilterEtReliable(inBam,minCov,ref): ficVar=traitementSamtools.lanceFromBamPileupI(inBam,minCov,ref) ficTsv=fromVarfilter2tsvLike(ficVar) extraitReliableSNP(ficTsv,True) os.system("chmod 777 %s" %ficVar) os.system("chmod 777 %s"%ficTsv) def fromVarfilter2tsvLike(ficVar): ficSnp = traitementSamtools.decomposeVarfilter(ficVar) #ficSnp = ficVar #ficSnp = ficVar.replace("varfilter","SNP")
def get_service_info(self,get): import system; serviceInfo = system.system().GetConcifInfo(get); del(serviceInfo['mysql_root']); return serviceInfo;
def GetDir(self, get): if not hasattr(get, 'path'): get.path = '/www/wwwroot' if sys.version_info[0] == 2: get.path = get.path.encode('utf-8') if not os.path.exists(get.path): get.path = '/www' import pwd dirnames = [] filenames = [] search = None if hasattr(get, 'search'): search = get.search.strip().lower() if hasattr(get, 'all'): return self.SearchFiles(get) #包含分页类 import page #实例化分页类 page = page.Page() info = {} info['count'] = self.GetFilesCount(get.path, search) info['row'] = 100 info['p'] = 1 if hasattr(get, 'p'): try: info['p'] = int(get['p']) except: info['p'] = 1 info['uri'] = {} info['return_js'] = '' if hasattr(get, 'tojs'): info['return_js'] = get.tojs if hasattr(get, 'showRow'): info['row'] = int(get.showRow) #获取分页数据 data = {} data['PAGE'] = page.GetPage(info, '1,2,3,4,5,6,7,8') i = 0 n = 0 for filename in os.listdir(get.path): if search: if filename.lower().find(search) == -1: continue i += 1 if n >= page.ROW: break if i < page.SHIFT: continue try: if sys.version_info[0] == 2: filename = filename.encode('utf-8') filePath = get.path + '/' + filename link = '' if os.path.islink(filePath): filePath = os.readlink(filePath) link = ' -> ' + filePath if not os.path.exists(filePath): filePath = get.path + '/' + filePath if not os.path.exists(filePath): continue stat = os.stat(filePath) accept = str(oct(stat.st_mode)[-3:]) mtime = str(int(stat.st_mtime)) user = '' try: user = pwd.getpwuid(stat.st_uid).pw_name except: user = str(stat.st_uid) size = str(stat.st_size) if os.path.isdir(filePath): dirnames.append(filename + ';' + size + ';' + mtime + ';' + accept + ';' + user + ';' + link) else: filenames.append(filename + ';' + size + ';' + mtime + ';' + accept + ';' + user + ';' + link) n += 1 except: continue data['DIR'] = sorted(dirnames) data['FILES'] = sorted(filenames) data['PATH'] = str(get.path) if hasattr(get, 'disk'): import system data['DISK'] = system.system().GetDiskInfo() return data
def restart_panel(): import system return system.system().ReWeb(None)
def GET(self): import system data = system.system().GetConcifInfo() data['lan'] = public.getLan('soft') return render.soft(data)
import system as sys import network3N as netw import traces as tra import info as nf import torus as tor import pylab as pl pos_info = '+0+600' pos_tra = '+300+600' pos_net = '+300+0' pos_sys = '+0+0' pos_torus = '+800+0' info = nf.info(position=pos_info) net = netw.network(g_inh=0.015, info=info, position=pos_net) system = sys.system(info=info, position=pos_sys, network=net) traces = tra.traces(system, net, info=info, position=pos_tra) torus = tor.torus(system, net, traces, info=info, position=pos_torus) net.system = system system.traces = traces if pl.get_backend() == 'TkAgg': system.fig.tight_layout() traces.fig.tight_layout() torus.fig.tight_layout() pl.show()
from parameter import parameter from system import system from selenium import webdriver from selenium.webdriver.common.keys import Keys import time from datetime import datetime from selenium.webdriver.support.ui import WebDriverWait import logging import os system=system() parameter=parameter() parameter.textinput() parameter.tel() driver=webdriver.Firefox() logging.info('open url') driver.get_screenshot_as_file(system.FileName())
def _refresh_default_route(self, old_state, new_state): if new_state: system.system('ip', 'route', 'replace', 'table', str(RULEID.DEFAULT), 'default', "dev", self.tunnel_interface)
def UpdatePanel(self,get): #return public.returnMsg(False,'演示服务器,禁止此操作!'); try: if not public.IsRestart(): return public.returnMsg(False,'EXEC_ERR_TASK'); import web,json if int(web.ctx.session.config['status']) == 0: public.httpGet(web.ctx.session.home+'/Api/SetupCount?type=Linux'); public.M('config').where("id=?",('1',)).setField('status',1); #取回远程版本信息 if hasattr(web.ctx.session,'updateInfo') == True and hasattr(get,'check') == False: updateInfo = web.ctx.session.updateInfo; else: login_temp = 'data/login.temp'; if os.path.exists(login_temp): logs = public.readFile(login_temp) os.remove(login_temp); else: logs = ''; import psutil,panelPlugin,system; mem = psutil.virtual_memory(); mplugin = panelPlugin.panelPlugin(); mplugin.ROWS = 10000; panelsys = system.system(); data = {} data['sites'] = str(public.M('sites').count()); data['ftps'] = str(public.M('ftps').count()); data['databases'] = str(public.M('databases').count()); data['system'] = panelsys.GetSystemVersion() + '|' + str(mem.total / 1024 / 1024) + 'MB|' + public.getCpuType() + '*' + str(psutil.cpu_count()) + '|' + public.get_webserver() + '|' + web.ctx.session.version; data['system'] += '||'+self.GetInstalleds(mplugin.getPluginList(None)); data['logs'] = logs data['oem'] = '' data['intrusion'] = self.get_ssh_intrusion(); msg = public.getMsg('PANEL_UPDATE_MSG'); sUrl = web.ctx.session.home + '/Api/updateLinux'; betaIs = 'data/beta.pl'; betaStr = public.readFile(betaIs); if betaStr: if betaStr.strip() != 'False': sUrl = web.ctx.session.home + '/Api/updateLinuxBeta'; msg = public.getMsg('PANEL_UPDATE_MSG_TEST'); betaIs = 'plugin/beta/config.conf'; betaStr = public.readFile(betaIs); if betaStr: if betaStr.strip() != 'False': sUrl = web.ctx.session.home + '/Api/updateLinuxBeta'; msg = public.getMsg('PANEL_UPDATE_MSG_TEST'); updateInfo = json.loads(public.httpPost(sUrl,data)); if not updateInfo: return public.returnMsg(False,"CONNECT_ERR"); updateInfo['msg'] = msg; web.ctx.session.updateInfo = updateInfo; #检查是否需要升级 if updateInfo['version'] == web.ctx.session.version: try: return public.returnMsg(False,updateInfo['msg']); except: return public.returnMsg(False,'PANEL_UPDATE_ERR_NEW'); #是否执行升级程序 if(updateInfo['force'] == True or hasattr(get,'toUpdate') == True or os.path.exists('data/autoUpdate.pl') == True): setupPath = web.ctx.session.setupPath; uptype = 'update'; betaIs = 'plugin/beta/config.conf'; betaStr = public.readFile(betaIs); if betaStr: if betaStr.strip() != 'False': uptype = 'updateTest'; betaIs = 'data/beta.pl'; betaStr = public.readFile(betaIs); if betaStr: if betaStr.strip() != 'False': uptype = 'updateTest'; httpUrl = public.get_url(); if httpUrl: updateInfo['downUrl'] = httpUrl + '/install/' + uptype + '/LinuxPanel-' + updateInfo['version'] + '.zip'; public.downloadFile(updateInfo['downUrl'],'panel.zip'); if os.path.getsize('panel.zip') < 1048576: return public.returnMsg(False,"PANEL_UPDATE_ERR_DOWN"); public.ExecShell('unzip -o panel.zip -d ' + setupPath + '/'); import compileall if os.path.exists(setupPath + '/panel/main.py'): public.ExecShell('rm -f ' + setupPath + '/panel/*.pyc'); if os.path.exists(setupPath + '/panel/class/common.py'): public.ExecShell('rm -f ' + setupPath + '/panel/class/*.pyc'); compileall.compile_dir(setupPath + '/panel'); compileall.compile_dir(setupPath + '/panel/class'); public.ExecShell('rm -f panel.zip'); web.ctx.session.version = updateInfo['version'] return public.returnMsg(True,'PANEL_UPDATE',(updateInfo['version'],)); #输出新版本信息 data = { 'status' : True, 'version': updateInfo['version'], 'updateMsg' : updateInfo['updateMsg'] }; public.ExecShell('rm -rf /www/server/phpinfo/*'); return data; except Exception,ex: return public.returnMsg(False,"CONNECT_ERR");
def GET(self): import system data = system.system().GetConcifInfo(); data['lan'] = public.getLan('config'); return render.config(data);
state6 = statements.get_takeValue('L1') state7 = statements.get_takeValue('L2') state8 = statements.get_takeValue('L3') state9 = statements.get_takeValue('L4') boolStatements = [state2,state3,state4,state5] numStatements = [state0,state1,state6,state7,state8,state9] slist = [createSample_prejudiced() for i in range(1000)] numparams= ['A','B','L1','L2','L3','L4'] boolparams = ['O','C1','C2','G'] keyparams = ['R','C'] import time import system t = time.time() sys = system.system(keyparams,boolparams,numparams,slist,6000,300,15) keyStates =sys.keyStatements import helpers sysLog = helpers.logWriter() sysDump = helpers.logWriter() sys.setLogWriter(sysLog) sys.setDumpWriter(sysDump) def runSimulation(rounds = 100,tests = 500): sys.initialise() sysLog.printToConsole() num = tests flog = open("lastLog.log",'w') fdump = open("lastDump.log",'w')
def GetInstalled(self,get): import system data = system.system().GetConcifInfo() return data;
def get_system_info(self,get): import system; s = system.system(); data = s.GetSystemTotal(get,0.1); data['disk'] = s.GetDiskInfo2(); return data;
#-*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.keys import Keys import time from datetime import datetime from selenium.webdriver.support.ui import WebDriverWait import logging import os from parameter import parameter from system import system para=parameter() syst=system() lis=0 if not os.path.isdir('c:\\TEST_log\\iheimalog\\'): os.makedirs('c:\\TEST_log\\iheimalog\\') logFileName = 'c:\\TEST_log\\iheimalog\\%s.log' %time.strftime("%m-%d-%H-%M-%S",time.localtime(time.time())) logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', filename=logFileName, level=logging.DEBUG) logging.info('####################') logging.info('# Begin Test #') logging.info('####################') def strB2Q(ustring): """半角转全角""" rstring = "" for uchar in ustring: inside_code=ord(uchar) if inside_code == 32: #半角空格直接转化
import network as netw import traces as tra import info as nf import torus as tor import pylab as pl #root = Tkinter.Tk() #screen_width = root.winfo_screenwidth() #screen_height = root.winfo_screenheight() pos_info = '+0+600' pos_tra = '+300+600' pos_net = '+300+0' pos_sys = '+0+0' pos_torus = '+800+0' i = nf.info(position=pos_info) n = netw.network(info=i, position=pos_net) s = sys.system(info=i, position=pos_sys, network=n) n.system = s t = tra.traces(s, n, info=i, position=pos_tra) tor = tor.torus(s, n, t, info=i, position=pos_torus) if pl.get_backend() == 'TkAgg': s.fig.tight_layout() #n.fig.tight_layout() t.fig.tight_layout() tor.fig.tight_layout() pl.show()