def showDetail(self, hosts=None): dlg = ui.Dlg_addHosts(self) if hosts: # 初始化值 dlg.m_radioBtn_local.SetValue(not hosts.is_online) dlg.m_radioBtn_online.SetValue(hosts.is_online) dlg.m_radioBtn_local.Enable(False) dlg.m_radioBtn_online.Enable(False) dlg.m_textCtrl_title.SetValue(hosts.title) if hosts.url: dlg.m_textCtrl_url.SetValue(hosts.url) dlg.m_textCtrl_url.Enable(True) if dlg.ShowModal() != wx.ID_OK: dlg.Destroy() return dlg.Destroy() is_online = dlg.m_radioBtn_online.GetValue() title = dlg.m_textCtrl_title.GetValue().strip() url = dlg.m_textCtrl_url.GetValue().strip() if not title: wx.MessageBox(u"方案名不能为空!", caption=u"出错啦!") return for h in self.hostses: if h != hosts and h.title == title: wx.MessageBox(u"已经有名为 '%s' 的方案了!" % title, caption=u"出错啦!") return if not hosts: # 新建 hosts fn = self.makeNewHostsFileName() if not fn: wx.MessageBox(u"hosts 文件数超出限制,无法再创建新 hosts 了!", caption=u"出错啦!") return path = os.path.join(self.hosts_path, fn) hosts = Hosts(path, title=title, url=url if is_online else None) hosts.content = u"# %s" % title if hosts.is_online: self.getHostsContent(hosts) self.addHosts(hosts, show_after_add=True) else: # 修改 hosts hosts.is_online = is_online hosts.title = title hosts.url = url if is_online else None self.updateHostsTitle(hosts) self.saveHosts(hosts)
def getForeverHosts(self): u"""获取永久生效的hosts""" path = os.path.join(self.hosts_path, 'hosts.forever') hosts = Hosts(path=path, title=lang.trans("forever_hosts"), is_forever=True) if not os.path.isfile(path): title = lang.trans("forever_hosts") hosts = Hosts(path=path, title=title, is_forever=True) hosts.content = u"# %s" % title self.saveHosts(hosts) self.forever_hostses = [hosts] self.addHosts(hosts)
def getUPSTypeFromProvider(provider): if provider is None: return None if provider.building is None or provider.TR is None: raise AttributeError( "getUPSTypeFromProvider requires a valid building and room") buildingList = Hosts.getBuildings(provider.building) if provider.building not in buildingList: raise ValueError("Invalid Building, unable to get host") # search by room and switch filtered = Hosts.filter(buildingList, str(provider.TR), ups=True) if filtered[provider.building] is None: return None # convert host (stew-115b-apc5000rm-01.tcom.purdue.edu) to device (apc5000rm) return Hosts.hostToUPSDevice(filtered[provider.building][0])
def init2(self): self.showing_rnd_id = random.random() self.is_switching_text = False self.current_using_hosts = None self.current_showing_hosts = None self.current_tree_hosts = None self.current_dragging_hosts = None self.current_tree_item = None # 当前选中的树无素 self.origin_hostses = [] self.common_hostses = [] self.hostses = [] self.fn_common_hosts = "COMMON.hosts" self.configs = {} self.loadConfigs() common_host_file_path = os.path.join(self.hosts_path, self.fn_common_hosts) if not os.path.isfile(common_host_file_path): common_file = open(common_host_file_path, "w") common_file.write("# common") common_file.close() hosts = Hosts(path=common_host_file_path, is_common=True) self.addHosts(hosts) self.getSystemHosts() self.scanSavedHosts() if not os.path.isdir(self.hosts_path): os.makedirs(self.hosts_path)
def scanSavedHosts(self): u"""扫描目前保存的各个hosts""" fns = glob.glob(os.path.join(self.hosts_path, "*.hosts")) fns = [os.path.split(fn)[1] for fn in fns] if self.fn_common_hosts in fns: fns.remove(self.fn_common_hosts) cfg_hostses = self.configs.get("hostses", []) # 移除不存在的 hosts tmp_hosts = [] for fn in cfg_hostses: if fn in fns: tmp_hosts.append(fn) cfg_hostses = tmp_hosts # 添加新的 hosts for fn in fns: if fn not in cfg_hostses: cfg_hostses.append(fn) self.configs["hostses"] = cfg_hostses self.saveConfigs() for fn in self.configs["hostses"]: path = os.path.join(self.hosts_path, fn) hosts = Hosts(path) if hosts.content: pass self.addHosts(hosts)
def getHostFromProvider(provider): if provider is None: return None if provider.building is None or provider.TR is None or provider.switchType is None: raise AttributeError( "getHostFromProvider requires a valid building, room, and switchType" ) buildingList = Hosts.getBuildings(provider.building) if provider.building not in buildingList: raise ValueError("Invalid Building, unable to get host") # search by room and switch filtered = Hosts.filter(buildingList, str(provider.TR), switches=True) for host in filtered[provider.building]: if Hosts.isEqual(host, provider.building, provider.TR, provider.switchType, provider.stack): return host return None
def __init__(self, data): """ Initialize the QuadsData object. """ self.hosts = Hosts(data) self.clouds = Clouds(data) self.history = History(data) self.cloud_history = CloudHistory(data)
def getSystemHosts(self): path = self.sys_hosts_path if path: hosts = Hosts(path=path, title=lang.trans("origin_hosts"), is_origin=True) self.origin_hostses = [hosts] self.addHosts(hosts) self.highLightHosts(hosts) self.updateBtnStatus(hosts)
def saveNewHostFile(self, title, url, is_online, fn = "" ): if not fn: fn = self.makeNewHostsFileName() if not fn: wx.MessageBox(u"hosts 文件数超出限制,无法再创建新 hosts 了!", caption=u"出错啦!") return path = os.path.join(self.hosts_path, fn) hosts = Hosts(path, title=title, url=url if is_online else None) hosts.content = u"# %s" % title if hosts.is_online: self.getHostsContent(hosts) self.addHosts(hosts, show_after_add=True) return hosts
def saveNewHostFile(self, title, url, is_online, fn=""): if not fn: fn = self.makeNewHostsFileName() if not fn: wx.MessageBox(u"hosts 文件数超出限制,无法再创建新 hosts 了!", caption=u"出错啦!") return path = os.path.join(self.hosts_path, fn) hosts = Hosts(path, title=title, url=url if is_online else None) hosts.content = u"# %s" % title if hosts.is_online: self.getHostsContent(hosts) self.addHosts(hosts, show_after_add=True) return hosts
def getHostsFromPatch(patch): if patch is None: return None if patch.building is None or patch.room is None: raise AttributeError( "getHostsFromPatch requires a valid building and room") buildingList = Hosts.getBuildings(patch.building) if patch.building not in buildingList: raise ValueError("Invalid Building, unable to get host") # search by room and switch filtered = Hosts.filter(buildingList, str(patch.room), switches=True) hosts = [] for host in filtered[patch.building]: if Hosts.isEqual(host, patch.building, patch.room, None, None): hosts.append(host) if len(hosts) == 0: return None else: return hosts
def get_setup_details(ip_to_swarm=None): logger.info(" [ INFO ] Gatherer Run Started.") run_time_start = datetime.datetime.now() time={} i=0 fail_ip = {} fail_ips = [] h = Hosts() for ip in ip_to_swarm: fail_ip = {} try: st_time=datetime.datetime.now() product = "Hosts" print "Gather Details From {0} ".format(ip) if h: print "Fetching details" setup_details = h.get_setup_details(ip) data = { "ip": ip, "details": setup_details["process_info"], "machine_info": setup_details["machine_info"], "active":1, "env": None, "last_run":str(now) } end_time=datetime.datetime.now() tot_time = end_time - st_time time[i]="{0} : time : {1}".format(ip,str(divmod(tot_time.total_seconds(),60))) i=i+1 is_conf_created = icinga_conf_creator.exec_manual(ip,data) logger.info(str(is_conf_created)) except Exception, e: errorMsg= "[ Gatherer Production ] Exception :: Running Gatherer on {0}".format(ip) fail_ip["ip"] = ip fail_ip["exception"] = str(e) fail_ips.append(fail_ip) logger.error(errorMsg) logger.exception(traceback.print_exc()) raise Exception(e)
def isValidUPSName(self, name): # of type yong-664-trp1500-01 # check building name is same, check tr is same # check ups model is a valid model # ['yong', '664', 'trp1500', '01'] nameSplit = name.split('-') if nameSplit is None or len(nameSplit) < 3: return False if nameSplit[0] != self.building: return False if nameSplit[1] != self.TR: return False if nameSplit[2] not in Hosts.getUPSList(): return False return True
def showDetailEditor(self, hosts=None, default_is_online=False): u"""显示详情编辑窗口""" dlg = ui.Dlg_addHosts(self) if hosts: # 初始化值 dlg.m_radioBtn_local.SetValue(not hosts.is_online) dlg.m_radioBtn_online.SetValue(hosts.is_online) dlg.m_radioBtn_local.Enable(False) dlg.m_radioBtn_online.Enable(False) dlg.m_textCtrl_title.SetValue(hosts.title) if hosts.url: dlg.m_textCtrl_url.SetValue(hosts.url) dlg.m_textCtrl_url.Enable(True) else: dlg.m_radioBtn_local.SetValue(not default_is_online) dlg.m_radioBtn_online.SetValue(default_is_online) dlg.m_textCtrl_url.Enabled = default_is_online if dlg.ShowModal() != wx.ID_OK: dlg.Destroy() return dlg.Destroy() is_online = dlg.m_radioBtn_online.GetValue() title = dlg.m_textCtrl_title.GetValue().strip() url = dlg.m_textCtrl_url.GetValue().strip() if not title: wx.MessageBox(u"方案名不能为空!", caption=u"出错啦!") return for h in self.hostses: if h != hosts and h.title == title: wx.MessageBox(u"已经有名为 '%s' 的方案了!" % title, caption=u"出错啦!") return if not hosts: # 新建 hosts fn = self.makeNewHostsFileName() if not fn: wx.MessageBox(u"hosts 文件数超出限制,无法再创建新 hosts 了!", caption=u"出错啦!") return path = os.path.join(self.hosts_path, fn) hosts = Hosts(path, title=title, url=url if is_online else None) hosts.content = u"# %s" % title if hosts.is_online: self.getHostsContent(hosts) self.addHosts(hosts, show_after_add=True) else: # 修改 hosts hosts.is_online = is_online hosts.title = title hosts.url = url if is_online else None self.updateHostsTitle(hosts) self.saveHosts(hosts)
import platform, os, atexit, threading, wx, wx.xrc, sched, time, sys, About, Help from datetime import datetime from Hosts import Hosts hostsFilepath = '/etc/hosts' if platform.system() == 'Windows': hostsFilepath = 'C:\Windows\System32\Drivers\etc\hosts' savedHosts = Hosts(os.path.join(os.getcwd(), 'data.txt')) hosts = Hosts(hostsFilepath) def onExit(): dlg = wx.MessageDialog(None, 'Will stop blocking', 'Exiting') dlg.ShowModal() for host in hosts.getHosts(): hosts.disableHost(host) hosts.write() dlg.Destroy() atexit.register(onExit) class MainFrame(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=u"Website blocker", pos=wx.DefaultPosition, size=wx.Size(560, 350), style=wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX | wx.RESIZE_BORDER | wx.SYSTEM_MENU | wx.TAB_TRAVERSAL) self.SetSizeHints(wx.Size(560, 350), wx.DefaultSize) self.SetBackgroundColour(wx.Colour(240, 240, 240))
import unittest import os from Hosts import Hosts hostsFilepath = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data.txt') hosts = Hosts(hostsFilepath) class TestHostsMethods(unittest.TestCase): def test_default_value(self): self.assertEqual(hosts.getHosts(), []) def test_adding_host(self): hosts.addHost('google.com') self.assertEqual(hosts.getHosts(), ['google.com']) hosts.deleteHost('google.com') def test_deleting_host(self): hosts.addHost('google.com') hosts.deleteHost('google.com') self.assertEqual(hosts.getHosts(), []) def test_disable_host(self): hosts.addHost('google.com') hosts.disableHost('google.com') self.assertEqual(hosts.hosts, [['127.0.0.1', 'google.com', False]]) hosts.deleteHost('google.com') def test_enable_host(self): hosts.addHost('google.com')