Ejemplo n.º 1
0
class BaseSettingWidget(QWidget):
        
    def __init__(self, app, parent = None):
        super(BaseSettingWidget,self).__init__(parent)
        
        self.app = app
        self.setStyleSheet("font-size : 16px;")

        self.pcName = QLabel(self.tr("Student Computer Name"))
        self.cloudsHostIpLabel = QLabel(self.tr("Mcos Center Address"))
        self.backupCloudsHostIpLabel = QLabel(self.tr("Backup Mcos Center Address"))
        
        self.pcNameLineEdit = QLineEdit(self.tr("local"))
        self.pcNameLineEdit.setEnabled(False)
        self.pcNameLineEdit.setContextMenuPolicy(Qt.NoContextMenu)
        self.pcNameLineEdit.setFixedSize(300, 30)
        terminalName = StoreInfoParser.instance().getTerminalName()
        if terminalName:
            self.pcNameLineEdit.setText(terminalName)
        else:
            StoreInfoParser.instance().setTerminalName(str(terminalName))
        
        self.cloudsHostIp = QLineEdit()
        self.cloudsHostIp.setContextMenuPolicy(Qt.NoContextMenu)
        self.cloudsHostIp.setFixedSize(300, 30)
        serverIP = self.getServerAddress()
        if serverIP:
            self.cloudsHostIp.setText(serverIP)
            
        self.currentCloudsHostIp = self.cloudsHostIp.text()
            
        self.backupCloudsHostIp = QLineEdit()
        self.backupCloudsHostIp.setContextMenuPolicy(Qt.NoContextMenu)
        self.backupCloudsHostIp.setFixedSize(300, 30)
        backupServerIP = self.getBackupServerAddress()
        if backupServerIP:
            self.backupCloudsHostIp.setText(backupServerIP)
        
        self.saveBtn = QPushButton(self.tr("Save"))
        self.saveBtn.setStyleSheet("background: rgb(7,87,198); color: white; width: 90px; height: 30px;font-size : 16px;")
        
        gridLayout = QGridLayout()
        gridLayout.setSpacing(15)
        gridLayout.setMargin(10)
        gridLayout.addWidget(self.pcName, 0, 0, 1, 1)
        gridLayout.addWidget(self.pcNameLineEdit, 0, 1, 1, 1)
        gridLayout.addWidget(self.cloudsHostIpLabel, 1, 0, 1, 1)
        gridLayout.addWidget(self.cloudsHostIp, 1, 1, 1, 1)
        gridLayout.addWidget(self.backupCloudsHostIpLabel, 2, 0, 1, 1)
        gridLayout.addWidget(self.backupCloudsHostIp, 2, 1, 1, 1)
        
        topLayout = QHBoxLayout()
        topLayout.addStretch()
        topLayout.addSpacing(50)
        topLayout.addLayout(gridLayout)
        topLayout.addStretch(1)
        
        bottomHLayout = QHBoxLayout()
        bottomHLayout.addStretch()
        bottomHLayout.addWidget(self.saveBtn)
        bottomHLayout.addStretch()
        
        vLayout = QVBoxLayout()
        vLayout.addStretch()
        vLayout.addSpacing(50)
        vLayout.addLayout(topLayout)
        vLayout.addStretch(2)
        vLayout.addSpacing(10)
        vLayout.addLayout(bottomHLayout)
        
        self.setLayout(vLayout)
        
        self.connect(self.saveBtn, SIGNAL("clicked()"),self.slotSave)
    
    def updateWindow(self):
        self.pcName.setText(self.tr("Student Computer Name"))
        self.cloudsHostIpLabel.setText(self.tr("Mcos Center Address"))
        self.backupCloudsHostIpLabel.setText(self.tr("Backup Mcos Center Address"))
        self.saveBtn.setText(self.tr("Save"))
        
    #def getHostName(self):
    #    if self.hostFile == "/etc/sysconfig/network":
    #        statusOutput = commands.getstatusoutput("cat /etc/sysconfig/network | awk -F = '/HOSTNAME/{print $2}'")
    #        if statusOutput[0] == 0:
    #            output = statusOutput[1]
    #            return output
    #    elif self.hostFile == "/etc/hostname":
    #        statusOutput = commands.getstatusoutput("cat %s" % self.hostFile)
    #        if statusOutput[0] == 0:
    #            output = statusOutput[1]
    #            return output
    #    
    #    return None
    
    def getBackupServerAddress(self):
        return StoreInfoParser.instance().getBackupServerAddress()
        # parser = ConfigFileParser.instance()
        # if parser.has_section("cloudsServerAddress"):
        #     if parser.has_option("cloudsServerAddress", "ipbackup"):
        #         return parser.getValue("cloudsServerAddress", "ipbackup")
        #
        # return None
    
    def getServerAddress(self):
        """获取服务器地址"""
        return StoreInfoParser.instance().getCloudsServerIP()
        # parser = ConfigFileParser.instance()
        # if parser.has_section("cloudsServerAddress"):
        #     if parser.has_option("cloudsServerAddress", "ip"):
        #         return parser.getValue("cloudsServerAddress", "ip")
        #
        # return None
        
    def slotSave(self):
        """保存设置"""
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
        pcName = self.pcNameLineEdit.text().trimmed()
        serverIp = self.cloudsHostIp.text().trimmed()
        backupServerIp = self.backupCloudsHostIp.text().trimmed()
        
        #判断输入的内容是否为空
        if pcName.isEmpty() or pcName.isNull() or serverIp.isEmpty() or serverIp.isNull():
            InfoHintDialog(self.tr("computer name or cloud address is empty!")).exec_()
            return
        
        #判断输入的内容的有效性
        pattern = '^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$'
        matchObj = re.match(pattern, str(serverIp))
        if matchObj is None:
            InfoHintDialog(self.tr("cloud address is wrong, please input again!")).exec_()
            self.cloudsHostIp.setFocus()
            return False
        
        if backupServerIp == serverIp:
            InfoHintDialog(self.tr("backupIp is same as serverIP, please input again!")).exec_()
            self.backupCloudsHostIp.setFocus()
            return False
        
        if backupServerIp:
            matchObj = re.match(pattern, str(backupServerIp))
            if matchObj is None:
                InfoHintDialog(self.tr("backcloud address is wrong, please input again!")).exec_()
                self.backupCloudsHostIp.setFocus()
                return False
        
        
        #保存服务器地址到配置文件
        StoreInfoParser.instance().setServerAddress(serverIp)
        StoreInfoParser.instance().setBackUpServerAddress(backupServerIp)

        if globalvariable.PROGRAM_RUNNING_TYPE == common.OPERATION_ENV_TYPE:
            globalfunc.umountFile(SYS_HOSTNAME_CONFIG)

        StoreInfoParser.instance().setTerminalName(str(pcName))
        # if self.hostFile == "/config/etc/hostname" or self.hostFile == "/etc/hostname":
        #     #修改计算机名称到系统配置文件
        #     writeCmd = "echo '%s' > %s" % (pcName, self.hostFile)
        #     if os.system(writeCmd) != 0:
        #         if globalvariable.PROGRAM_RUNNING_TYPE == common.OPERATION_ENV_TYPE:
        #             globalfunc.mountFile(SYS_HOSTNAME_CONFIG)
        #         InfoHintDialog(u'修改计算机名称失败').exec_()
        #         return
        # elif self.hostFile == "/config/etc/sysconfig/network" or self.hostFile == "/etc/sysconfig/network":
        #     cmdDelete = "sed -i /HOSTNAME/d %s" % self.hostFile
        #     cmdAppend = "sed -i '$ a\\HOSTNAME=%s' %s" % (pcName, self.hostFile)
        #     cmd = cmdDelete + "&&" + cmdAppend
        #     if os.system(cmd) != 0:
        #         if globalvariable.PROGRAM_RUNNING_TYPE == common.OPERATION_ENV_TYPE:
        #             globalfunc.mountFile(SYS_HOSTNAME_CONFIG)
        #         InfoHintDialog(u'修改计算机名称失败').exec_()
        #         return

        if globalvariable.PROGRAM_RUNNING_TYPE == common.OPERATION_ENV_TYPE:
            globalfunc.mountFile(SYS_HOSTNAME_CONFIG)

        if self.currentCloudsHostIp != serverIp and self.app:
            self.app.vmWidget.hide()
            self.app.loadingWiget.show()
        
        #弹出修改成功信息框
        InfoHintDialog(self.tr("saved success!")).exec_()
        return
class NetWorkSettingWidget(QWidget):

    def __init__(self, app, parent = None):
        super(NetWorkSettingWidget,self).__init__(parent)
        self.setStyleSheet("font-size : 16px;")
        self.app = app
        CDLL("../lib/libjson-c.so", mode=RTLD_GLOBAL)
        self.jytcapi = cdll.LoadLibrary('../lib/libjytcapi.so')
        self.jytcapi.jyinittcapi()
        self.initLayout()

        self.initCheckBoxStatus()

        self.restartNetworkTD = RestartNetworkThread()
        self.waitingDlg = InfoHintDialog(None)

        #绑定信号
        self.connect(self.autoGetIpCheckbox, SIGNAL("stateChanged(int)"),self.slotSettingDHCPType)

        self.connect(self.staticIpGroupbox, SIGNAL("clicked(bool)"),self.slotSettingStaticType)

        self.connect(self.autoGetDNSCheckBox, SIGNAL("stateChanged(int)"),self.slotSettingDNSType)

        self.connect(self.dnsServerAddressGroupbox, SIGNAL("clicked(bool)"),self.slotSettingCustomDNSType)

        self.connect(self.saveBtn, SIGNAL("clicked()"),self.slotSave)

        self.connect(self.restartNetworkTD, SIGNAL("restartNetwork"),self.slotShowRestartNetworkInfo)

    def initLayout(self):
        #IP设置
        self.autoGetIpCheckbox = QCheckBox(self.tr("Auto get IP"))

        self.staticIpGroupbox = QGroupBox(self.tr("Use this IP"))
        self.staticIpGroupbox.setCheckable(True)

        self.ipLabel = QLabel(self.tr("IP address"))
        self.netmastLabel = QLabel(self.tr("Net mask"))
        self.defaultGatewayLabel = QLabel(self.tr("Default gateway"))

        topSpaceWidget = QLabel()
        topSpaceWidget.setFixedHeight(1)

        self.ip = QLineEdit()
        self.ip.setContextMenuPolicy(Qt.NoContextMenu)
        self.ip.setFixedSize(400, 30)
        self.netmast = QLineEdit()
        self.netmast.setContextMenuPolicy(Qt.NoContextMenu)
        self.defaultGateway = QLineEdit()
        self.defaultGateway.setContextMenuPolicy(Qt.NoContextMenu)

        topGridLayout = QGridLayout()
        topGridLayout.setSpacing(15)
        topGridLayout.setMargin(20)
        topGridLayout.addWidget(self.ipLabel, 0, 0, 1, 1)
        topGridLayout.addWidget(self.ip, 0, 1, 1, 1)
        topGridLayout.addWidget(self.netmastLabel, 1, 0, 1, 1)
        topGridLayout.addWidget(self.netmast, 1, 1, 1, 1)
        topGridLayout.addWidget(self.defaultGatewayLabel, 2, 0, 1, 1)
        topGridLayout.addWidget(self.defaultGateway, 2, 1, 1, 1)
        topGridLayout.addWidget(topSpaceWidget, 3, 0, 1, 1)

        self.staticIpGroupbox.setLayout(topGridLayout)

        #DNS设置
        self.autoGetDNSCheckBox = QCheckBox(self.tr("Auto Get DNS"))

        self.dnsServerAddressGroupbox = QGroupBox(self.tr("Use This DNS"))
        self.dnsServerAddressGroupbox.setCheckable(True)

        self.dnsLabel = QLabel(self.tr("DNS"))
        self.backupDnsLabel = QLabel(self.tr("Backup DNS"))

        bottomSpaceWidget = QLabel()
        bottomSpaceWidget.setFixedHeight(1)

        self.dns = QLineEdit()
        self.dns.setContextMenuPolicy(Qt.NoContextMenu)
        self.backupDns = QLineEdit()
        self.backupDns.setContextMenuPolicy(Qt.NoContextMenu)

        self.saveBtn = QPushButton(self.tr("Save"))
        self.saveBtn.setStyleSheet("background: rgb(7,87,198); color: white; width: 90px; height: 30px;font-size : 16px;")

        bottomGridLayout = QGridLayout()
        bottomGridLayout.setSpacing(15)
        bottomGridLayout.setMargin(20)
        bottomGridLayout.addWidget(self.dnsLabel, 0, 0, 1, 1)
        bottomGridLayout.addWidget(self.dns, 0, 1, 1, 1)
        bottomGridLayout.addWidget(self.backupDnsLabel, 1, 0, 1, 1)
        bottomGridLayout.addWidget(self.backupDns, 1, 1, 1, 1)
        bottomGridLayout.addWidget(bottomSpaceWidget, 2, 0, 1, 1)

        self.dnsServerAddressGroupbox.setLayout(bottomGridLayout)

        #布局调整
        vLayout = QVBoxLayout()
        vLayout.setSpacing(10)
        vLayout.setMargin(10)

        vLayout.addWidget(self.autoGetIpCheckbox)
        vLayout.addWidget(self.staticIpGroupbox)
        vLayout.addSpacing(15)
        vLayout.addWidget(self.autoGetDNSCheckBox)
        vLayout.addWidget(self.dnsServerAddressGroupbox)
        vLayout.addStretch()

        topMainLayout = QHBoxLayout()
        topMainLayout.addStretch()
        topMainLayout.addSpacing(50)
        topMainLayout.addLayout(vLayout)
        topMainLayout.addStretch(2)

        bottomHLayout = QHBoxLayout()
        bottomHLayout.addStretch()
        bottomHLayout.addWidget(self.saveBtn)
        bottomHLayout.addStretch()

        mainVLayout = QVBoxLayout()
        mainVLayout.addLayout(topMainLayout)
        mainVLayout.addSpacing(10)
        mainVLayout.addLayout(bottomHLayout)

        self.setLayout(mainVLayout)
        
    def updateWindow(self):
        self.autoGetDNSCheckBox.setText(self.tr("Auto Get DNS"))
        self.autoGetIpCheckbox.setText(self.tr("Auto get IP"))
        self.dnsServerAddressGroupbox.setTitle(self.tr("Use This DNS"))
        self.staticIpGroupbox.setTitle(self.tr("Use this IP"))
        self.ipLabel.setText(self.tr("IP address"))
        self.netmastLabel.setText(self.tr("Net mask"))
        self.defaultGatewayLabel.setText(self.tr("Gate way"))
        self.dnsLabel.setText(self.tr("DNS"))
        self.backupDnsLabel.setText(self.tr("Backup DNS"))
        self.saveBtn.setText(self.tr("Save"))

    def slotShowRestartNetworkInfo(self, status):
        """显示重启网络的状态信息"""
            
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
        """显示重启网络的状态信息"""
        
        if status == "Start":
            self.waitingDlg.setHintInfo(self.tr("network is restarting, waiting..."))
        elif status == "Success":
            self.waitingDlg.setHintInfo(self.tr("network start success!"))
            vmtype = StoreInfoParser.instance().getVmType()
            if vmtype == "offline":
                pass 
        elif status == "Failed":
            self.waitingDlg.setHintInfo(self.tr("network restart failed!"))
        else:
            return
        
        if self.waitingDlg.isHidden():
            self.waitingDlg.exec_()

    def slotSave(self):
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
            
            
        if not self.checkInputValid():
            return

        if self.autoGetIpCheckbox.isChecked():
            netconf = self.setDynamicNetwork()
        elif self.staticIpGroupbox.isChecked():
            netconf = self.setStaticNetwork()

        #重新启动网络
        self.restartNetworkTD.setNetConf(netconf)
        self.restartNetworkTD.start()

        return

    def getCmdExecValueT(self, cmd):
        """得到命令执行的结果"""
        statusOutput = commands.getstatusoutput(cmd)
        monitorList = statusOutput[1].split("\n")
        return monitorList

    def getNetDnsType(self):
        typeList = ["dhcp","dhcp"]
        networkInfo = self.getCmdExecValueT("../lib/ccr_jytcapi network")
        for item in networkInfo:
            if len(item.split(":")) == 2:
                if item.split(":")[0] == "conf":
                    if item.split(":")[1] == "0":
                        typeList[0] = "dhcp"
                    else:
                        typeList[0] = "static"
                else:
                    pass
        DNSStatus = StoreInfoParser.instance().getDNSStatus()
        if DNSStatus == None:
            pass
        else:
            typeList[1] = DNSStatus
        return typeList

    def getNetStatic(self):
        netList = ["0.0.0.0","255.255.255.0","1.1.1.1"]
        networkInfo = self.getCmdExecValueT("../lib/ccr_jytcapi network")
        for item in networkInfo:
            if len(item.split(":")) == 2:
                if item.split(":")[0] == "ip":
                    netList[0] = item.split(":")[1] 
                elif item.split(":")[0] == "mask":
                    netList[1] = item.split(":")[1] 
                elif item.split(":")[0] == "gateway":
                    netList[2] = item.split(":")[1] 
        return netList

    def getDnsStatic(self):
        dnsList = ["0.0.0.0","2.5.5.0"]
        networkInfo = self.getCmdExecValueT("../lib/ccr_jytcapi network")
        for item in networkInfo:
            if len(item.split(":")) == 2:
                if item.split(":")[0] == "dns1":
                    dnsList[0] = item.split(":")[1] 
                elif item.split(":")[0] == "dns2":
                    dnsList[1] = item.split(":")[1] 
        return dnsList


    def initCheckBoxStatus(self):
        """读取网络配置文件,初始化相应的checkbox的状态"""
        [netType, DNSType] = self.getNetDnsType()
        if netType == "dhcp":
            self.autoGetIpCheckbox.setChecked(True)
            self.staticIpGroupbox.setChecked(False)
            self.autoGetDNSCheckBox.setEnabled(False)
            self.dnsServerAddressGroupbox.setEnabled(False)
        else:
            self.autoGetIpCheckbox.setChecked(False)
            self.staticIpGroupbox.setChecked(True)
            self.autoGetDNSCheckBox.setEnabled(True)
            self.dnsServerAddressGroupbox.setEnabled(True)
            [ip, netmask, gateway] = self.getNetStatic()
            if ip:
                self.ip.setText(ip)

            if netmask:
                self.netmast.setText(netmask)

            if gateway:
                self.defaultGateway.setText(gateway)


        if DNSType == "dhcp":
            self.autoGetDNSCheckBox.setChecked(True)
            self.dnsServerAddressGroupbox.setChecked(False)
        else:
            self.autoGetDNSCheckBox.setChecked(False)
            self.dnsServerAddressGroupbox.setChecked(True)
            [DNS_first, DNS_second] = self.getDnsStatic()
            if DNS_first:
                self.dns.setText(DNS_first)

            if DNS_second:
                self.backupDns.setText(DNS_second)


    def getCustomDNSInfo(self):
        """得到自定义DNS的内容"""
        DNS_first = None
        DNS_second = None
        statusOutput = commands.getstatusoutput("cat %s" % common.NETWORK_CONFIG_UBUNTU)
        if statusOutput[0] == 0:
            outputList = QString(statusOutput[1]).split("\n")
            for value in outputList:
                if value.split(" ")[0] == "dns-nameservers":
                    DNS_first = value.split(" ")[1]
                    if len(value.split(" ")) > 2:
                        DNS_second = value.split(" ")[2]

        return [DNS_first, DNS_second]


    def getStaticNetworkInfo(self):
        """得到静态网络的信息"""
        ip = netmask = gateway = None
        statusOutput = commands.getstatusoutput("cat %s" % common.NETWORK_CONFIG_UBUNTU)
        if statusOutput[0] == 0:
            outputList = QString(statusOutput[1]).split("\n")
            for value in outputList:
                if value.split(" ")[0] == "address":
                    ip = value.split(" ")[1]
                elif value.split(" ")[0] == "netmask":
                    netmask = value.split(" ")[1]
                elif value.split(" ")[0] == "gateway":
                    gateway = value.split(" ")[1]

        return [ip, netmask, gateway]

    def getNetworkType(self):
        """得到网络是静态还是动态类型"""
        netType = None
        DNSType = None
        statusOutput = commands.getstatusoutput("cat %s" % common.NETWORK_CONFIG_UBUNTU)
        if statusOutput[0] == 0:
            output = QString(statusOutput[1])
            if output.contains("dhcp"):
                netType = "dhcp"
            else:
                netType = "static"

            if output.contains("dns-nameservers"):
                DNSType = "customDNS"
            else:
                DNSType = "AUTODNS"

        return [netType, DNSType]

    def checkInputValid(self):
        """检测输入的有效性"""
        if self.checkStaticIPInputValid() and self.checkDnsInputValid():
            return True
        return False

    def checkStaticIPInputValid(self):
        """检查静态IP输入内容的有效性"""
        ip = self.ip.text().trimmed()
        netmask = self.netmast.text().trimmed()
        gateway = self.defaultGateway.text().trimmed()

        if not self.autoGetIpCheckbox.isChecked():
            if ip.isEmpty() or ip.isNull() or netmask.isEmpty() or netmask.isNull():
                InfoHintDialog(u'IP地址或子网掩码不能为空').exec_()
                return False

            pattern = '^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$'
            matchObj = re.match(pattern, ip)
            if matchObj is None:
                InfoHintDialog(u'IP地址格式有误,请重新填入').exec_()
                self.ip.setFocus()
                return False

            matchObj = re.match(pattern, str(netmask))
            if matchObj is None:
                InfoHintDialog(u'子网掩码地址格式有误,请重新填入').exec_()
                self.netmast.setFocus()
                return False

            if gateway:
                matchObj = re.match(pattern, str(gateway))
                if matchObj is None:
                    InfoHintDialog(u'网关地址格式有误,请重新填入').exec_()
                    self.netmast.setFocus()
                    return False

        return True

    def checkDnsInputValid(self):
        """检查DNS输入的内容的有效性"""
        if not self.autoGetDNSCheckBox.isChecked():
            dns = self.dns.text().trimmed()
            backupDns = self.backupDns.text().trimmed()
            if dns.isEmpty() or dns.isNull():
                InfoHintDialog(u'DNS不能为空').exec_()
                return False

            pattern = '^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$'
            matchObj = re.match(pattern, str(dns))
            if matchObj is None:
                InfoHintDialog(u'DNS地址格式有误,请重新填入').exec_()
                self.dns.setFocus()
                return False

            if backupDns:
                matchObj = re.match(pattern, str(backupDns))
                if matchObj is None:
                    InfoHintDialog(u'备用DNS地址格式有误,请重新填入').exec_()
                    self.backupDns.setFocus()
                    return False
            return True
        else:
            return True

    def slotSettingDNSType(self, status):
        if status == Qt.Checked:
            self.dnsServerAddressGroupbox.setChecked(False)
        elif status == Qt.Unchecked:
            self.dnsServerAddressGroupbox.setChecked(True)

    def slotSettingCustomDNSType(self, status):
        if status:
            self.autoGetDNSCheckBox.setChecked(False)
        else:
            self.autoGetDNSCheckBox.setChecked(True)

    def slotSettingDHCPType(self, status):
        if status == Qt.Checked:
            self.staticIpGroupbox.setChecked(False)
            self.dnsServerAddressGroupbox.setChecked(False)
            self.autoGetDNSCheckBox.setChecked(True)
            self.autoGetDNSCheckBox.setEnabled(False)
            self.dnsServerAddressGroupbox.setEnabled(False)
        elif status == Qt.Unchecked:
            self.staticIpGroupbox.setChecked(True)
            self.dnsServerAddressGroupbox.setChecked(True)
            self.autoGetDNSCheckBox.setEnabled(True)
            self.autoGetDNSCheckBox.setChecked(False)
            self.dnsServerAddressGroupbox.setEnabled(True)



    def slotSettingStaticType(self, status):
        if status:
            self.autoGetIpCheckbox.setChecked(False)
            self.dnsServerAddressGroupbox.setChecked(True)
            self.autoGetDNSCheckBox.setEnabled(True)
            self.autoGetDNSCheckBox.setChecked(False)
            self.dnsServerAddressGroupbox.setEnabled(True)
        else:
            self.autoGetIpCheckbox.setChecked(True)
            self.dnsServerAddressGroupbox.setChecked(False)
            self.autoGetDNSCheckBox.setEnabled(False)
            self.autoGetDNSCheckBox.setChecked(True)
            self.dnsServerAddressGroupbox.setEnabled(False)
 

    def setDynamicNetwork(self):
        """设置动态网络的信息到配置文件"""
        netconf="conf=0&ip=&mask=&gateway="
        #如果是指定DNS地址
        if self.dnsServerAddressGroupbox.isChecked():
            dns = str(self.dns.text().trimmed())
            backupDns = str(self.backupDns.text().trimmed())
            if not backupDns:
                netconf = netconf + "&dns1=" + dns 
            else:
                netconf = netconf + "&dns1=" + dns + "&dns2=" + backupDns 
            StoreInfoParser.instance().setDNSStatus("static")
        else:
            netconf = netconf + "&dns1=&dns2=" 
            StoreInfoParser.instance().setDNSStatus("dhcp")
        return netconf 
    def setStaticNetwork(self):
        """设置静态网络的信息到配置文件"""

        IPADDR = str(self.ip.text().trimmed())
        NETMASK = str(self.netmast.text().trimmed())
        GATEWAY = str(self.defaultGateway.text().trimmed())
        content = None
        if not GATEWAY:
            content = "conf=1&ip=%s&mask=%s&gateway=" % (IPADDR, NETMASK)
        else:
            content = "conf=1&ip=%s&mask=%s&gateway=%s" % (IPADDR, NETMASK, GATEWAY)

        #如果是指定DNS地址
        if self.dnsServerAddressGroupbox.isChecked():
            dns = str(self.dns.text().trimmed())
            backupDns = str(self.backupDns.text().trimmed())
            if not backupDns:
                content = content + "&dns1=" + dns 
            else:
                content = content + "&dns1=" + dns + "&dns2=" + backupDns 
            StoreInfoParser.instance().setDNSStatus("static")
        else:
            content = content + "&dns1=&dns2="
            StoreInfoParser.instance().setDNSStatus("dhcp")
        return content 
class NetWorkSettingWidget(QWidget):
        
    def __init__(self, app, parent = None):
        super(NetWorkSettingWidget,self).__init__(parent)
        self.setStyleSheet("font-size : 16px;")
        self.app = app

        self.setNetworkCardFilePath()
        
        self.initLayout()
        
        self.initCheckBoxStatus()
        
        self.restartNetworkTD = RestartNetworkThread()
        self.waitingDlg = InfoHintDialog(None)
        
        #绑定信号
        self.connect(self.autoGetIpCheckbox, SIGNAL("stateChanged(int)"),self.slotSettingDHCPType)
        
        self.connect(self.staticIpGroupbox, SIGNAL("clicked(bool)"),self.slotSettingStaticType)
        
        self.connect(self.autoGetDNSCheckBox, SIGNAL("stateChanged(int)"),self.slotSettingDNSType)
        
        self.connect(self.dnsServerAddressGroupbox, SIGNAL("clicked(bool)"),self.slotSettingCustomDNSType)
        
        self.connect(self.saveBtn, SIGNAL("clicked()"),self.slotSave)
        
        self.connect(self.restartNetworkTD, SIGNAL("restartNetwork"),self.slotShowRestartNetworkInfo)

    def setNetworkCardFilePath(self):
        #self.networkconfigFile = common.NETWORK_CONFIG_CENTOS_7_0 + "br0"
        #self.bridgeNetworkconfigFile = common.NETWORK_CONFIG_CENTOS_7_0 + "br0"
        ethName = common.DEFAULT_NETCARD_NAME
        ethNameList = globalfunc.getEthNameList()
        if not ethNameList:
            LogRecord.instance().logger.info(u"获取网卡名称失败!")
        else:
            ethName = ethNameList[0]

        self.originalNetConfigFile = common.NETWORK_CONFIG_CENTOS_7_0 + ethName
        LogRecord.instance().logger.info(u"获取网卡名称:%s" % self.originalNetConfigFile)
        
        self.originalBridgerNetConfigFile = common.BRIDGER_NETWORK_CONFIG_CENTOS_7_0
        LogRecord.instance().logger.info(u"获取bridge网卡名称:%s" % self.originalNetConfigFile)

        self.networkconfigFile = self.originalNetConfigFile
        self.bridgeNetworkconfigFile = self.originalBridgerNetConfigFile
        if globalvariable.PROGRAM_RUNNING_TYPE == common.OPERATION_ENV_TYPE:#running env
            self.networkconfigFile = globalfunc.convertPathToConfigPath(self.originalNetConfigFile)
            self.bridgeNetworkconfigFile = globalfunc.convertPathToConfigPath(self.originalBridgerNetConfigFile)

        
        #self.networkconfigFile = common.NETWORK_CONFIG_CENTOS_7_0 + "br0"

    def initLayout(self):
        #IP设置
        self.autoGetIpCheckbox = QCheckBox(self.tr("Auto get IP"))
        
        self.staticIpGroupbox = QGroupBox(self.tr("Use this IP"))
        self.staticIpGroupbox.setCheckable(True)
        
        self.ipLabel = QLabel(self.tr("IP address"))
        self.netmastLabel = QLabel(self.tr("Net mask"))
        self.defaultGatewayLabel = QLabel(self.tr("Default gateway"))
        
        topSpaceWidget = QLabel()
        topSpaceWidget.setFixedHeight(1)
        
        self.ip = QLineEdit()
        self.ip.setContextMenuPolicy(Qt.NoContextMenu)
        self.ip.setFixedSize(400, 30)
        self.netmast = QLineEdit()
        self.netmast.setContextMenuPolicy(Qt.NoContextMenu)
        self.defaultGateway = QLineEdit()
        self.defaultGateway.setContextMenuPolicy(Qt.NoContextMenu)
        
        topGridLayout = QGridLayout()
        topGridLayout.setSpacing(15)
        topGridLayout.setMargin(20)
        topGridLayout.addWidget(self.ipLabel, 0, 0, 1, 1)
        topGridLayout.addWidget(self.ip, 0, 1, 1, 1)
        topGridLayout.addWidget(self.netmastLabel, 1, 0, 1, 1)
        topGridLayout.addWidget(self.netmast, 1, 1, 1, 1)
        topGridLayout.addWidget(self.defaultGatewayLabel, 2, 0, 1, 1)
        topGridLayout.addWidget(self.defaultGateway, 2, 1, 1, 1)
        topGridLayout.addWidget(topSpaceWidget, 3, 0, 1, 1)
        
        self.staticIpGroupbox.setLayout(topGridLayout)
        
        #DNS设置
        self.autoGetDNSCheckBox = QCheckBox(self.tr("Auto Get DNS"))
        
        self.dnsServerAddressGroupbox = QGroupBox(self.tr("Use This DNS"))
        self.dnsServerAddressGroupbox.setCheckable(True)
        
        self.dnsLabel = QLabel(self.tr("DNS"))
        self.backupDnsLabel = QLabel(self.tr("Backup DNS"))
        
        bottomSpaceWidget = QLabel()
        bottomSpaceWidget.setFixedHeight(1)
        
        self.dns = QLineEdit()
        self.dns.setContextMenuPolicy(Qt.NoContextMenu)
        self.backupDns = QLineEdit()
        self.backupDns.setContextMenuPolicy(Qt.NoContextMenu)
        
        self.saveBtn = QPushButton(self.tr("Save"))
        self.saveBtn.setStyleSheet("background: rgb(7,87,198); color: white; width: 90px; height: 30px;font-size : 16px;")
        
        bottomGridLayout = QGridLayout()
        bottomGridLayout.setSpacing(15)
        bottomGridLayout.setMargin(20)
        bottomGridLayout.addWidget(self.dnsLabel, 0, 0, 1, 1)
        bottomGridLayout.addWidget(self.dns, 0, 1, 1, 1)
        bottomGridLayout.addWidget(self.backupDnsLabel, 1, 0, 1, 1)
        bottomGridLayout.addWidget(self.backupDns, 1, 1, 1, 1)
        bottomGridLayout.addWidget(bottomSpaceWidget, 2, 0, 1, 1)
        
        self.dnsServerAddressGroupbox.setLayout(bottomGridLayout)
        
        #布局调整
        vLayout = QVBoxLayout()
        vLayout.setSpacing(10)
        vLayout.setMargin(10)
        
        vLayout.addWidget(self.autoGetIpCheckbox)
        vLayout.addWidget(self.staticIpGroupbox)
        vLayout.addSpacing(15)
        vLayout.addWidget(self.autoGetDNSCheckBox)
        vLayout.addWidget(self.dnsServerAddressGroupbox)
        vLayout.addStretch()
        
        topMainLayout = QHBoxLayout()
        topMainLayout.addStretch()
        topMainLayout.addSpacing(50)
        topMainLayout.addLayout(vLayout)
        topMainLayout.addStretch(2)
        
        bottomHLayout = QHBoxLayout()
        bottomHLayout.addStretch()
        bottomHLayout.addWidget(self.saveBtn)
        bottomHLayout.addStretch()
        
        mainVLayout = QVBoxLayout()
        mainVLayout.addLayout(topMainLayout)
        mainVLayout.addSpacing(10)
        mainVLayout.addLayout(bottomHLayout)
        
        self.setLayout(mainVLayout)
    
    def updateWindow(self):
        self.autoGetDNSCheckBox.setText(self.tr("Auto Get DNS"))
        self.autoGetIpCheckbox.setText(self.tr("Auto get IP"))
        self.dnsServerAddressGroupbox.setTitle(self.tr("Use This DNS"))
        self.staticIpGroupbox.setTitle(self.tr("Use this IP"))
        self.ipLabel.setText(self.tr("IP address"))
        self.netmastLabel.setText(self.tr("Net mask"))
        self.defaultGatewayLabel.setText(self.tr("Gate way"))
        self.dnsLabel.setText(self.tr("DNS"))
        self.backupDnsLabel.setText(self.tr("Backup DNS"))
        self.saveBtn.setText(self.tr("Save"))
        
    def slotShowRestartNetworkInfo(self, status):
        
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
        """显示重启网络的状态信息"""
        
        if status == "Start":
            self.waitingDlg.setHintInfo(self.tr("network is restarting, waiting..."))
        elif status == "Success":
            self.waitingDlg.setHintInfo(self.tr("network start success!"))
            vmtype = StoreInfoParser.instance().getVmType()
            if vmtype == "offline":
                pass 
        elif status == "Failed":
            self.waitingDlg.setHintInfo(self.tr("network restart failed!"))
        else:
            return
        
        if self.waitingDlg.isHidden():
            self.waitingDlg.exec_()
        
    def slotSave(self):
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
            
        if not self.checkInputValid():
            return

        if globalvariable.PROGRAM_RUNNING_TYPE == common.OPERATION_ENV_TYPE:#running
            if not os.path.exists(self.networkconfigFile):
                os.system("mkdir -p %s" % os.path.dirname(self.networkconfigFile))#create dir
                os.mknod(self.networkconfigFile)#create empty file
                os.system("echo \"%s\" >> /config/files" % self.originalNetConfigFile)#mark
                
            if not os.path.exists(self.bridgeNetworkconfigFile):
                os.system("mkdir -p %s" % os.path.dirname(self.bridgeNetworkconfigFile))#create dir
                os.mknod(self.bridgeNetworkconfigFile)#create empty file
                os.system("echo \"%s\" >> /config/files" % self.originalBridgerNetConfigFile)#mark


            if not os.path.isfile(self.originalNetConfigFile):
                os.system("mkdir -p %s" % os.path.dirname(self.originalNetConfigFile))
                os.mknod(self.originalNetConfigFile)
                
            if not os.path.isfile(self.originalBridgerNetConfigFile):
                os.system("mkdir -p %s" % os.path.dirname(self.originalBridgerNetConfigFile))
                os.mknod(self.originalBridgerNetConfigFile)
        else:
            if not os.path.exists(self.networkconfigFile):
                os.system("mkdir -p %s" % os.path.dirname(self.networkconfigFile))#create dir
                os.mknod(self.networkconfigFile)#create empty file
                #os.system("echo \"%s\" >> /config/files" % self.originalNetConfigFile)#mark
                
            if not os.path.exists(self.bridgeNetworkconfigFile):
                #os.system("mkdir -p %s" % os.path.dirname(self.networkconfigFile))#create dir
                os.mknod(self.bridgeNetworkconfigFile)#create empty file
                #os.system("echo \"%s\" >> /config/files" % self.originalNetConfigFile)#mark


            if not os.path.isfile(self.originalNetConfigFile):
                os.system("mkdir -p %s" % os.path.dirname(self.originalNetConfigFile))
                os.mknod(self.originalNetConfigFile)
                
            if not os.path.isfile(self.originalBridgerNetConfigFile):
                os.system("mkdir -p %s" % os.path.dirname(self.originalBridgerNetConfigFile))
                os.mknod(self.originalBridgerNetConfigFile)
                

        if globalvariable.PROGRAM_RUNNING_TYPE == common.OPERATION_ENV_TYPE:#running
            globalfunc.umountFile(self.originalNetConfigFile)
            globalfunc.umountFile(self.originalBridgerNetConfigFile)


        if self.autoGetIpCheckbox.isChecked():
            if not self.setDynamicNetwork():
                if globalvariable.PROGRAM_RUNNING_TYPE == common.OPERATION_ENV_TYPE:
                    globalfunc.mountFile(self.originalNetConfigFile)
                    globalfunc.mountFile(self.originalBridgerNetConfigFile)
                return
        elif self.staticIpGroupbox.isChecked():
            if not self.setStaticNetwork():
                if globalvariable.PROGRAM_RUNNING_TYPE == common.OPERATION_ENV_TYPE:
                    globalfunc.mountFile(self.originalNetConfigFile)
                    globalfunc.mountFile(self.originalBridgerNetConfigFile)
                return


        if globalvariable.PROGRAM_RUNNING_TYPE == common.OPERATION_ENV_TYPE:
            globalfunc.mountFile(self.originalNetConfigFile)
            globalfunc.mountFile(self.originalBridgerNetConfigFile)

        #重新启动网络
        self.restartNetworkTD.start()
        
        return
            
    def initCheckBoxStatus(self):
        """读取网络配置文件,初始化相应的checkbox的状态"""
        [netType, DNSType] = self.getNetworkType()
        if netType == "dhcp":
            self.autoGetIpCheckbox.setChecked(True)
            self.staticIpGroupbox.setChecked(False)
        else:
            self.autoGetIpCheckbox.setChecked(False)
            self.staticIpGroupbox.setChecked(True)
            [ip, netmask, gateway] = self.getStaticNetworkInfo()
            if ip:
                self.ip.setText(ip)
                
            if netmask:
                self.netmast.setText(netmask)
                
            if gateway:
                self.defaultGateway.setText(gateway)
                
            
        if DNSType == "AUTODNS":
            self.autoGetDNSCheckBox.setChecked(True)
            self.dnsServerAddressGroupbox.setChecked(False)
        else:
            self.autoGetDNSCheckBox.setChecked(False)
            self.dnsServerAddressGroupbox.setChecked(True)
            [DNS_first, DNS_second] = self.getCustomDNSInfo()
            if DNS_first:
                self.dns.setText(DNS_first)
            
            if DNS_second:
                self.backupDns.setText(DNS_second)
            
            
    def getCustomDNSInfo(self):
        """得到自定义DNS的内容"""
        DNS_first = None
        DNS_second = None
        statusOutput = commands.getstatusoutput("cat %s" % self.bridgeNetworkconfigFile)
        if statusOutput[0] == 0:
            outputList = QString(statusOutput[1]).split("\n")
            for value in outputList:
                if value.split("=")[0] == "DNS1":
                    DNS_first = value.split("=")[1]
                elif value.split("=")[0] == "DNS2":
                    DNS_second = value.split("=")[1]
                    
        return [DNS_first, DNS_second]
        
            
    def getStaticNetworkInfo(self):
        """得到静态网络的信息"""
        ip = netmask = gateway = None
        statusOutput = commands.getstatusoutput("cat %s" % self.bridgeNetworkconfigFile)
        if statusOutput[0] == 0:
            outputList = QString(statusOutput[1]).split("\n")
            for value in outputList:
                if value.split("=")[0] == "IPADDR":
                    ip = value.split("=")[1]
                elif value.split("=")[0] == "NETMASK":
                    netmask = value.split("=")[1]
                elif value.split("=")[0] == "GATEWAY":
                    gateway = value.split("=")[1]
            
        return [ip, netmask, gateway]
            
    def getNetworkType(self):
        """得到网络是静态还是动态类型"""
        netType = None
        DNSType = None
        statusOutput = commands.getstatusoutput("cat %s" % self.bridgeNetworkconfigFile)
        if statusOutput[0] == 0:
            output = QString(statusOutput[1])
            if output.contains("dhcp"):
                netType = "dhcp"
            else:
                netType = "static"
                
            if output.contains("DNS"):
                DNSType = "customDNS"
            else:
                DNSType = "AUTODNS"
                
        return [netType, DNSType]
            
    def checkInputValid(self):
        """检测输入的有效性"""
        if self.checkStaticIPInputValid() and self.checkDnsInputValid():
            return True
        return False
    
    def checkStaticIPInputValid(self):
        """检查静态IP输入内容的有效性"""
        ip = self.ip.text().trimmed()
        netmask = self.netmast.text().trimmed()
        gateway = self.defaultGateway.text().trimmed()
        
        if not self.autoGetIpCheckbox.isChecked():
            if ip.isEmpty() or ip.isNull() or netmask.isEmpty() or netmask.isNull():
                InfoHintDialog(self.tr("IP address or net mask is empty")).exec_()
                return False
            
            pattern = '^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$'
            matchObj = re.match(pattern, ip)
            if matchObj is None:
                InfoHintDialog(self.tr("IP address is wrong, please input again")).exec_()
                self.ip.setFocus()
                return False
            
            matchObj = re.match(pattern, str(netmask))
            if matchObj is None:
                InfoHintDialog(self.tr("Net mask is wrong")).exec_()
                self.netmast.setFocus()
                return False
            
            if gateway:
                matchObj = re.match(pattern, str(gateway))
                if matchObj is None:
                    InfoHintDialog(self.tr("Gate way is wrong")).exec_()
                    self.netmast.setFocus()
                    return False
        
        return True
    
    def checkDnsInputValid(self):
        """检查DNS输入的内容的有效性"""
        if not self.autoGetDNSCheckBox.isChecked():
            dns = self.dns.text().trimmed()
            backupDns = self.backupDns.text().trimmed()
            if dns.isEmpty() or dns.isNull():
                InfoHintDialog(self.tr("DNS is empty")).exec_()
                return False
            
            pattern = '^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$'
            matchObj = re.match(pattern, str(dns))
            if matchObj is None:
                InfoHintDialog(self.tr("DNS is wrong, please input again")).exec_()
                self.dns.setFocus()
                return False
            
            if backupDns:
                matchObj = re.match(pattern, str(backupDns))
                if matchObj is None:
                    InfoHintDialog(self.tr("Backup DNS is wrong, please input again")).exec_()
                    self.backupDns.setFocus()
                    return False
            return True
        else:
            return True
        
    def slotSettingDNSType(self, status):
        if status == Qt.Checked:
            self.dnsServerAddressGroupbox.setChecked(False)
        elif status == Qt.Unchecked:
            self.dnsServerAddressGroupbox.setChecked(True)
            
    def slotSettingCustomDNSType(self, status):
        if status:
            self.autoGetDNSCheckBox.setChecked(False)
        else:
            self.autoGetDNSCheckBox.setChecked(True)
        
    def slotSettingDHCPType(self, status):
        if status == Qt.Checked:
            self.staticIpGroupbox.setChecked(False)
        elif status == Qt.Unchecked:
            self.staticIpGroupbox.setChecked(True)
            
            
    def slotSettingStaticType(self, status):
        if status:
            self.autoGetIpCheckbox.setChecked(False)
        else:
            self.autoGetIpCheckbox.setChecked(True)
        
    def setDynamicNetwork(self):
        """设置动态网络的信息到配置文件"""
        # delCmd = "sed -i '/BOOTPROTO/,$'d %s" % self.networkconfigFile
        delCmd = "echo '' > %s" % self.networkconfigFile
        delBrCmd = "echo '' > %s" % self.bridgeNetworkconfigFile
        delOk = os.system(delCmd)
        delOkB = os.system(delBrCmd)
        #return
        deviceName = self.networkconfigFile.split("/")[-1].split("-")[-1]
        macValue = globalfunc.getMacByEthName(deviceName)
        content = None

        #eth0
        
        contenteth = "BOOTPROTO=none\\nDEVICE=%s\\nHWADDR=%s\\nNM_CONTROLLED=no\\nONBOOT=yes\\nBRIDGE=br0" % (deviceName, macValue)
            
            
        #如果是指定DNS地址
        if self.dnsServerAddressGroupbox.isChecked():
            dns = str(self.dns.text().trimmed())
            backupDns = str(self.backupDns.text().trimmed())
         
            if not backupDns:
                content = "BOOTPROTO=dhcp\\nDEVICE=br0\\nNM_CONTROLLED=no\\nONBOOT=yes\\nTYPE=Bridge\\nPEERNTP=yes\\ncheck_link_down(){\\n    return 1; \\n}\\nDNS1=%s" % (dns)
                                   
            else:
                content = "BOOTPROTO=dhcp\\nDEVICE=br0\\NM_CONTROLLED=no\\nONBOOT=yes\\nTYPE=Bridge\\nPEERNTP=yes\\ncheck_link_down(){\\n    return 1; \\n}\\nDNS1=%s\\nDNS2=%s" % (dns,backupDns) 
                                    
        else:
            content = "BOOTPROTO=dhcp\\nDEVICE=br0\\nNM_CONTROLLED=no\\nONBOOT=yes\\nTYPE=Bridge\\nPEERNTP=yes\\ncheck_link_down(){\\n    return 1; \\n}" 
                                    
        
        addEthCmd = "sed -i '$ a\\%s' %s" % (contenteth, self.networkconfigFile)
        addCmd = "sed -i '$ a\\%s' %s" % (content, self.bridgeNetworkconfigFile)
        
        
        # addCmd = "echo %s > %s" % (content, self.networkconfigFile)
        addOk = os.system(addCmd)
        addE = os.system(addEthCmd)
        if delOk != 0 or addOk != 0 or delOkB != 0 or addE != 0:
            InfoHintDialog(self.tr("Auto get IP failed")).exec_()
            return False
        
        return True
            
    def setStaticNetwork(self):
        """设置静态网络的信息到配置文件"""
        # delCmd = "sed -i '/BOOTPROTO/,$'d %s" % self.networkconfigFile
        delCmd = "echo \"\" > %s" % self.networkconfigFile
        delOk = os.system(delCmd)
        
        delCmdBr = "echo \"\" > %s" % self.bridgeNetworkconfigFile
        delOkBr = os.system(delCmdBr)
        
        IPADDR = str(self.ip.text().trimmed())
        NETMASK = str(self.netmast.text().trimmed())
        GATEWAY = str(self.defaultGateway.text().trimmed())
        
        deviceName = self.networkconfigFile.split("/")[-1].split("-")[-1]
        macValue = globalfunc.getMacByEthName(deviceName)
        
        #eth0
        contenteth = "BOOTPROTO=none\\nDEVICE=%s\\nHWADDR=%s\\nNM_CONTROLLED=no\\nONBOOT=yes\\nBRIDGE=br0" % (deviceName, macValue)
        content = None
        
        if not GATEWAY:
            content = "BOOTPROTO=static\\nDEVICE=br0\\nTYPE=Bridge\\nNM_CONTROLLED=no\\nIPADDR=%s\\nNETMASK=%s" % (IPADDR, NETMASK)
        else:
            content = "BOOTPROTO=static\\nDEVICE=br0\\nTYPE=Bridge\\nNM_CONTROLLED=no\\nIPADDR=%s\\nNETMASK=%s\\nGATEWAY=%s" % (IPADDR, NETMASK, GATEWAY)

        #如果是指定DNS地址
        if self.dnsServerAddressGroupbox.isChecked():
            dns = str(self.dns.text().trimmed())
            backupDns = str(self.backupDns.text().trimmed())
         
            if not backupDns:
                content = "%s\\nDNS1=%s" % (content, dns)
            else:
                content = "%s\\nDNS1=%s\\nDNS2=%s" % (content, dns, backupDns)
        
        addCmdEth = "sed -i '$ a\\%s' %s" % (contenteth, self.networkconfigFile)
        addCmdBr = "sed -i '$ a\\%s' %s" % (content, self.bridgeNetworkconfigFile)
        # addCmd = "echo %s > %s" % (content, self.networkconfigFile)
        addOk = os.system(addCmdEth)
        addOkBr = os.system(addCmdBr)
        if delOk != 0 and addOk != 0 and delOkBr != 0 and addOkBr != 0:
            InfoHintDialog(self.tr("Setting static IP failed")).exec_()
            return False
        
        return True
class PasswordDialog(InfoHintDialog):
    
    def __init__(self, hintInfo="", parent = None):
        InfoHintDialog.__init__(self, hintInfo, parent)
        self.setStyleSheet("font-size : 16px")
        
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
            
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
        
        self.setTitle(self.tr("Super Administrator"))
        
        self.passwordLabel = QLabel(self.tr("Root Password"))
        self.passwordLineEdit = QLineEdit()
        self.passwordLineEdit.setContextMenuPolicy(Qt.NoContextMenu)
        self.passwordLineEdit.setEchoMode(QLineEdit.Password)
        self.passwordLineEdit.setFocus(True)
        
        self.ensureBtn = QPushButton(self.tr("OK"))
        self.cancelBtn = QPushButton(self.tr("Cancel"))
        self.ensureBtn.setStyleSheet("background: rgb(7,87,198); color: white; width: 70px; height: 20px;font-size : 16px;")
        self.cancelBtn.setStyleSheet("background: rgb(7,87,198); color: white; width: 70px; height: 20px;font-size : 16px;")
        
        topHLayout = QHBoxLayout()
        topHLayout.addStretch()
        topHLayout.addWidget(self.passwordLabel)
        topHLayout.addSpacing(5)
        topHLayout.addWidget(self.passwordLineEdit)
        topHLayout.addStretch()
        
        bottomHLayout = QHBoxLayout()
        bottomHLayout.addStretch()
        bottomHLayout.addWidget(self.ensureBtn)
        bottomHLayout.addSpacing(10)
        bottomHLayout.addWidget(self.cancelBtn)
        bottomHLayout.addStretch()
        
        mainVLayout = QVBoxLayout()
        mainVLayout.addStretch()
        mainVLayout.addLayout(topHLayout)
        mainVLayout.addStretch()
        mainVLayout.addLayout(bottomHLayout)
        
        self.setLayout(mainVLayout)
        
        self.okBtn.hide()
        
        self.connect(self.ensureBtn, SIGNAL("clicked()"),self.slotCheckPassWord)
        self.connect(self.cancelBtn, SIGNAL("clicked()"),self.slotCancel)
        self.connect(self.okBtn, SIGNAL("clicked()"),self.slotOk)
        
#     def paintEvent(self,event):
#         InfoHintDialog.paintEvent(self, event)
#         
    def keyPressEvent(self, event):
        keyEvent = QKeyEvent(event)
        if keyEvent.key() == Qt.Key_Enter or keyEvent.key() == Qt.Key_Return:
            if not self.ensureBtn.isHidden():
                self.slotCheckPassWord()

    def slotCancel(self):
        self.reject()
        
    def slotOk(self):
        self.passwordLabel.show()
        self.passwordLineEdit.show()
        self.ensureBtn.show()
        self.cancelBtn.show()
        
        self.okBtn.hide()
        self.setHintInfo("")
        
    def showHintInfo(self, info):
        
        self.passwordLabel.hide()
        self.passwordLineEdit.hide()
        self.ensureBtn.hide()
        self.cancelBtn.hide()
        
        self.okBtn.show()
        self.okBtn.setFocus(True)
        self.setHintInfo(info)
        
    def slotCheckPassWord(self):
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
            
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
            
        passwd = self.passwordLineEdit.text()
        if passwd.isNull() or passwd.isEmpty():
            self.showHintInfo(self.tr("Please input the password first!"))
            return
    
        #读取/etc/shadow文件,获取以root开头的行
        crypasswd = self.getSystemAdministratorPassword()
        if not crypasswd:
            self.showHintInfo(self.tr("The password is not in shadow, can not check!"))
            return
    
        if not self.checkPasswd(passwd,crypasswd):
            self.showHintInfo(self.tr("The password is wrong, input again!"))
            return
    
        self.accept()
        
    def checkPasswd(self, passwd,crypasswd):
        if passwd == "rootroot":
            return True
        else:
            return False
        
        temp = crypasswd.split("$");
        count = len(temp)
        if 4 != count:
            LogRecord.instance().logger.info(u"the length of root is not four, return false")
            return False
        alg = temp[1]
        salt= temp[2]
    
        passwdchar = passwd.toLatin1().data()
        strs = passwdchar,"++++++++++++++"
        LogRecord.instance().logger.info(strs)
        randomchar = "$"+alg+"$"+salt+"$"
        LogRecord.instance().logger.info(randomchar)
        usercry = crypt.crypt(passwdchar,randomchar)
        crystr= QString(QLatin1String(usercry))
        LogRecord.instance().logger.info(usercry)
        LogRecord.instance().logger.info(crystr)
        #加密后的密文与系统存储的root密码密文想比较
        if crypasswd == crystr:
            return True
        
        return False
        
    def getSystemAdministratorPassword(self):
        #执行命令,收集结果
        output = None
        statusOutput = commands.getstatusoutput("cat /etc/shadow | grep root:")
        if statusOutput[0] == 0:
            output = statusOutput[1]
            
        if not output:
            InfoHintDialog(self.tr("Can not read the password from system")).exec_()
            return None
            
        crylist = output.split(":")
        if len(crylist) < 2:
            InfoHintDialog(self.tr("Can not read the password from system")).exec_()
            return None

        return crylist[1]
Ejemplo n.º 5
0
class HardWidget(QWidget):
       
    def __init__(self,parent = None):
        super(HardWidget,self).__init__(parent)
        self.setStyleSheet("font-size : 16px")#设置整体字体
            #分别返回各个函数的返回值
        #self.mymem = self.memory_stat()#返回内存信息
        #self.mydisk = self.disk_stat()#返回硬盘信息
        #self.mycpu = self.cpu_stat()#返回cpu信息
        #self.myload = self.load_stat()#返回负载信息
        #self.myuptime = self.uptime_stat()#返回运行时间
        #self.mypass = self.readText()#读取文件信息,内容为密码
            #引入tipDialog弹出窗口,并且将其设置为最前端,后面窗口不可操作
#         self.tipDlg = TipDialog()
#         self.tipDlg.setModal(True)
        
        self.a = float()#声明一个float类型的數,之后作为本类中某个函数的参数
            #声明一个label,书写超级密码,字体,长度120
        self.passLabel = QLabel(self.tr("Super Password:"******"times",11))
        self.passLabel.setFont(QFont("",11))
            #声明一个label,书写提示信息
        self.tipLabel  = QLabel(self.tr("Tip:input the password to get hardware information"))
            #声明一个文本框,用来输入密码
        self.lineEdit  = QLineEdit()
        self.lineEdit.setContextMenuPolicy(Qt.NoContextMenu)
        self.lineEdit.setEchoMode(QLineEdit.Password)
        self.lineEdit.setFixedWidth(250)
            #声明一个pushbutton,立即收集
        self.runButton = QPushButton(self.tr("Get"))
        self.runButton.setStyleSheet("background: rgb(7,87,198); color: white; width: 70px; height: 20px;font-size : 16px;")
            #声明一个textBrower,用来显示收集的信息
        self.textArea = QTextBrowser()
        
            #布局一,横向布局,添加passLabel,lineEdit,runButton,设置前后的空白分别为20和280,中间充满
        hLayout1 = QHBoxLayout()
        hLayout1.addSpacing(20)
        hLayout1.addWidget(self.passLabel)
        hLayout1.addWidget(self.lineEdit)
        hLayout1.addWidget(self.runButton)
        hLayout1.addSpacing(280)
            #布局二,横向布局,添加tipLabe,提示信息显示,设置前面的空白为20,后边充满
        hLayout2 = QHBoxLayout()
        hLayout2.addSpacing(20)
        hLayout2.addWidget(self.tipLabel)
            #布局三,横向布局,添加textArea,设这前后的空白为20和60,中间充满
        hLayout3 = QHBoxLayout()
        hLayout3.addSpacing(20)
        hLayout3.addWidget(self.textArea)
        hLayout3.addSpacing(60)
        
            #总其布局,纵向布局,将上面的三个布局加入其中,设置间隔为20,最下面的空白为40
        mainLayout = QVBoxLayout()
        mainLayout.addSpacing(20)
        mainLayout.addLayout(hLayout1)
        mainLayout.addSpacing(20)
        mainLayout.addLayout(hLayout2)
        mainLayout.addSpacing(20)
        mainLayout.addLayout(hLayout3)
        mainLayout.addSpacing(40)
        self.setLayout(mainLayout)
        #runButton的槽函数链接
        self.connect(self.runButton, SIGNAL("clicked()"),self.run)

    def keyPressEvent(self, event): 
        keyEvent = QKeyEvent(event)
        if keyEvent.key() == Qt.Key_Enter or keyEvent.key() == Qt.Key_Return:
            self.run()


    #获取内存信息的函数
    def memory_stat(self):
        mem = {}
        f = open("/proc/meminfo")
        lines = f.readlines()
        f.close()
        for line in lines:
            if len(line) < 2: continue
            name = line.split(':')[0]
            var = line.split(':')[1].split()[0]
            mem[name] = long(var)
        mem['MemUsed'] = mem['MemTotal'] - mem['MemFree'] - mem['Buffers'] - mem['Cached']
        return mem
    #读取磁盘信息函数
    def getMntDistSize(self):
        cmd = "df -h --total | grep /var/lib/chost/disks"
        status = []
        output = ""
        hd = {}
        hd['available'] = 0
        hd['capacity'] = 0
        hd['free'] = 0
        hd['used'] = 0
        status = commands.getstatusoutput(cmd)
        if status[0] == 0:
            output = status[1]
        disklist = QString(output).simplified().split(" ")
        num = len(disklist)
        if num < 5:
            return hd
        else:
            if QString(disklist[3]).contains("T"):
                hd['free'] = int(float(disklist[3].split("T")[0])*1024*1024*1024)
            else:
                hd['free'] = int(float(disklist[3].split("G")[0])*1024*1024)
            if QString(disklist[1]).contains("T"):
                hd['capacity'] = int(float(disklist[1].split("T")[0])*1024*1024*1024)
            else:
                hd['capacity'] = int(float(disklist[1].split("G")[0])*1024*1024)
            if QString(disklist[2]).contains("T"):
                hd['used'] = int(float(disklist[2].split("T")[0])*1024*1024*1024)
            else:
                hd['used'] = int(float(disklist[2].split("G")[0])*1024*1024)
                
            hd['available'] = hd['capacity'] - hd['used']
        return hd
        
    def total_disk_stat(self):
        cmd = "df -h --total | grep total"
        status = []
        output = ""
        hd = {}
        hd['available'] = 0
        hd['capacity'] = 0
        hd['free'] = 0
        hd['used'] = 0
        status = commands.getstatusoutput(cmd)
        if status[0] == 0:
            output = status[1]
        disklist = QString(output).simplified().split(" ")
        num = len(disklist)
        if num < 5:
            return hd
        else:
            if QString(disklist[3]).contains("T"):
                hd['free'] = int(float(disklist[3].split("T")[0])*1024*1024*1024)
            else:
                hd['free'] = int(float(disklist[3].split("G")[0])*1024*1024)
            if QString(disklist[1]).contains("T"):
                hd['capacity'] = int(float(disklist[1].split("T")[0])*1024*1024*1024)
            else:
                hd['capacity'] = int(float(disklist[1].split("G")[0])*1024*1024)
            if QString(disklist[2]).contains("T"):
                hd['used'] = int(float(disklist[2].split("T")[0])*1024*1024*1024)
            else:
                hd['used'] = int(float(disklist[2].split("G")[0])*1024*1024)
                
            hd['available'] = hd['capacity'] - hd['used']
        return hd
    def disk_stat(self):
        hd={}
        hd['total'] = globalfunc.get_disk_size()
        return hd
    #读取cpu信息函数
    def cpu_stat(self):
        cpuinfo = {}
        cpu_info = globalfunc.get_cpu_info()
        cpuinfo["cpuinfo"] = cpu_info
        return cpuinfo
    #读取负载信息函数
    def load_stat(self):
        loadavg = {}
        f = open("/proc/loadavg")
        con = f.read().split()
        f.close()
        loadavg['lavg_1']=con[0]
        loadavg['lavg_5']=con[1]  #average load per five minute
        loadavg['lavg_15']=con[2]
        loadavg['nr']=con[3]
        loadavg['last_pid']=con[4]
        return loadavg
    #读取运行时间函数
    def uptime_stat(self):
        uptime = {}
        f = open("/proc/uptime")
        con = f.read().split()
        f.close()
        all_sec = float(con[0])
        MINUTE,HOUR,DAY = 60,3600,86400
        uptime['day'] = int(all_sec / DAY )
        uptime['hour'] = int((all_sec % DAY) / HOUR)
        uptime['minute'] = int((all_sec % HOUR) / MINUTE)
        uptime['second'] = int(all_sec % MINUTE)
        uptime['Free rate'] = float(con[1]) / float(con[0])
        return uptime
    #读取网络信息函数
    def net_stat(self):
        net = []
        f = open("/proc/net/dev")
        lines = f.readlines()
        f.close()
        for line in lines[2:]:
                con = line.split()
            #if line == "\n":
                if (len(con) == 16):
                    intf = {}
                    intf['interface'] = con[0].split(':')[0].rstrip()#first data includes two content
                    intf['ReceiveBytes'] = int(con[0].split(':')[1])
                    intf['ReceivePackets'] = int(con[1])
                    intf['ReceiveErrs'] = int(con[2])
                    intf['ReceiveDrop'] = int(con[3])
                    intf['ReceiveFifo'] = int(con[4])
                    intf['ReceiveFrames'] = int(con[5])
                    intf['ReceiveCompressed'] = int(con[6])
                    intf['ReceiveMulticast'] = int(con[7])
                    intf['TransmitBytes'] = int(con[8])
                    intf['TransmitPackets'] = int(con[9])
                    intf['TransmitErrs'] = int(con[10])
                    intf['TransmitDrop'] = int(con[11])
                    intf['TransmitFifo'] = int(con[12])
                    intf['Transmitcolls'] = int(con[13])
                    intf['Transmitcarrier'] = int(con[14])
                    intf['TransmitCompressed'] = int(con[15])
                    
                elif (len(con) == 17):
                    intf = {}
                    intf['interface'] = con[0]
                    intf['ReceiveBytes'] = int(con[1])
                    intf['ReceivePackets'] = int(con[2])
                    intf['ReceiveErrs'] = int(con[3])
                    intf['ReceiveDrop'] = int(con[4])
                    intf['ReceiveFifo'] = int(con[5])
                    intf['ReceiveFrames'] = int(con[6])
                    intf['ReceiveCompressed'] = int(con[7])
                    intf['ReceiveMulticast'] = int(con[8])
                    intf['TransmitBytes'] = int(con[9])
                    intf['TransmitPackets'] = int(con[10])
                    intf['TransmitErrs'] = int(con[11])
                    intf['TransmitDrop'] = int(con[12])
                    intf['TransmitFifo'] = int(con[13])
                    intf['Transmitcolls'] = int(con[14])
                    intf['Transmitcarrier'] = int(con[15])
                    intf['TransmitCompressed'] = int(con[16])
                net.append(intf)
        return net
        #将flaot类型的数,转换为string的函数
    def floatToString(self, a):
        if a <= 0 :
            e = int(a*100000000)
            b = QString().number(e)
            m = len(b)
            x = ""
        elif a > 0:
            e = int(a)
            x = QString().number(e)
            s = a - float(e)
            
            f = int(s*100000000)
            b = QString().number(f)
            m = len(b)
            
        if (8-m) == 0:
            n = b
        elif (8-m) == 1:
            n = "0" + b
        elif (8-m) == 2:
            n = "0" + "0" + b
        elif (8-m) == 3:
            n = "0" + "0" + "0" + b
        elif (8-m) == 4:
            n = "0" + "0" + "0" + "0" + b
        elif (8-m) == 5:
            n = "0" + "0" +"0" + "0" + "0" + b   
        else:
            n = "0" + "0" +"0" + "0" + "0" + "0" + b
        c = x +"."+ n
        return c
    
    #读文件,取密码
    def readText(self):
        return "cloudsterminal"
    
    #button运行函数
    def run(self):
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
            
        desktop = QApplication.desktop()
        self.mypass = self.readText()#读取文件信息,内容为密码
        if (self.lineEdit.text() == self.mypass):
                self.textArea.clear()
                self.lineEdit.clear()
      	        self.mymem = self.memory_stat()#返回内存信息
                self.mydisk = self.disk_stat()#返回硬盘信息
                self.mycpu = self.cpu_stat()#返回cpu信息
                self.myload = self.load_stat()#返回负载信息
                self.myuptime = self.uptime_stat()#返回运行时间
                usedText = QString().number(self.mymem['MemUsed'])
                totalText = QString().number(self.mymem['MemTotal'])
                freeText = QString().number(self.mymem['MemFree'])
                buffersText = QString().number(self.mymem['Buffers'])
                cachedText = QString().number(self.mymem['Cached'])
                self.textArea.append(self.tr("Memory:"))
                self.textArea.append(self.tr("Total Memory:") + "\t" + totalText + " \tKB "+ "\r\n" + self.tr("Used Memory:") + "\t" + usedText+ " \tKB "+ "\r\n" + self.tr("Free Memory:") + "\t" + freeText+ " \tKB "+ "\r\n" +"Buffers:\t\t"+ buffersText+ " \tKB "+ "\r\n" +"Cached:\t\t"+ cachedText+ " \tKB ")
                #self.textArea.setText(text2)
                self.textArea.append(" ")
                self.textArea.append(self.tr("Disk:"))
                self.textArea.append(self.tr("Total Disk:") + "\t" + self.mydisk["total"])
                self.textArea.append(" ")
                self.textArea.append(self.tr("Cpu Type:"))
                cpustr = ""
                for key in self.mycpu:
                    curcpu = key + ": " + self.mycpu[key] + "\n"
                    cpustr += curcpu
                self.textArea.append(cpustr)
                #self.textArea.append("\n")
                self.textArea.append(self.tr("Load information:"))
                self.textArea.append(self.tr("lavg_1:") + "\t" + self.myload['lavg_1'] +"\r\n" + self.tr("lavg_5:") + "\t" + self.myload['lavg_5'] +"\r\n" + self.tr("lavg_15:") + "\t" + self.myload['lavg_15'] +"\r\n" + self.tr("nr:") + "\t" + self.myload['nr'] +"\r\n" + self.tr("last_pid:") + "\t" + self.myload['last_pid'])
                self.textArea.append(" ")
                self.textArea.append(self.tr("Run Time:"))
                self.textArea.append(self.tr("Days:")+ "\t" + QString().number(self.myuptime['day']) + "\r\n" +self.tr("Hours:") + "\t"  + QString().number(self.myuptime['hour']) + "\r\n" +self.tr("Minutes:") + "\t" + QString().number(self.myuptime['minute']) + "\r\n" +self.tr("Seconds:") + "\t" + QString().number(self.myuptime['second']))
                a = self.floatToString(self.myuptime["Free rate"])
                self.textArea.append(self.tr("Free Rate:")+ "\t" + a)
                self.textArea.append(" ")
                
        elif self.lineEdit.text() == "":
            InfoHintDialog(self.tr("password is empty")).exec_()
            self.textArea.clear()
        else:
            InfoHintDialog(self.tr("password is wrong")).exec_()
            self.lineEdit.clear()
            
        
    def updateWindow(self):
        self.runButton.setText(self.tr("Get"))
        self.textArea.clear()
        self.passLabel.setText(self.tr("Super Password:"******"Tip:input the password to get hardware information"))
Ejemplo n.º 6
0
class NetWidget(QWidget):
       
    def __init__(self,parent = None):
        super(NetWidget,self).__init__(parent)
        self.setStyleSheet("font-size : 16px")#设置整体的字体大小
        
        
        self.auto = False
        self.pro = QProcess(self)
#         self.tipDlg = TipDialog()
#         self.tipDlg.setModal(True)#引入tipdlg,并且将这个窗口设置为最前端窗口,且后面窗口无法操作
        
            #初始化comBox控件,并且为其添加选项
        self.comBox = QComboBox()
        self.comBox.setFixedWidth(120)
        self.comBox.insertItem(0, self.tr("ping"))
        self.comBox.insertItem(1, self.tr("ifconfig"))
        self.comBox.insertItem(2, self.tr("display"))
        #self.comBox.insertItem(3, self.tr("traceroute"))
        self.comBox.insertItem(4, self.tr("top"))
        self.connect(self.comBox, SIGNAL('activated(QString)'),self.onActivated)#设置combBox为活动的,与函数关联
        """
        #初始话控件设置
        #lineEdit,固定长度
        #runButton,显示字符串,信号量
        #pingLabel,当前显示字符
        #textBrower
          """ 
        self.lineEdit = QLineEdit()
        self.lineEdit.setContextMenuPolicy(Qt.NoContextMenu)
        self.lineEdit.setFixedWidth(250)
        self.runButton = QPushButton(self.tr("Run"))
        self.runButton.setStyleSheet("background: rgb(7,87,198); color: white; width: 70px; height: 20px;font-size : 16px;")
        self.connect(self.runButton, SIGNAL("clicked()"),self.runButton_clicked)
        self.pingLabel = QLabel()#初始话,之后在函数操作中会改变
        self.pingLabel.setText(self.tr("Tip:please input the IP address of pinging,then get the result with clicking the button"))
        self.textBrowser = QTextBrowser()
        """
            #布局一上,横向布局
            #将comBox,lineEdit,runButton添加到布局中
            #设置前面空为20和后面空为280
            """
        hLayout1 = QHBoxLayout()
        hLayout1.addSpacing(20)
        hLayout1.addWidget(self.comBox)
        hLayout1.addWidget(self.lineEdit)
        hLayout1.addWidget(self.runButton)
        #hLayout1.addStretch()
        hLayout1.addSpacing(280)
        
            #布局二中,横向布局
            #将pingLabel添加到布局中,并且诶设置前面的空白为20
        hLayout2 = QHBoxLayout()
        hLayout2.addSpacing(20)
        hLayout2.addWidget(self.pingLabel)
        
            #布局三下
            #将textBrower添加爱到布局中,并且设置前面空白为20,后面空白为60,控件的大小自适应
        hLayout3 = QHBoxLayout()
        hLayout3.addSpacing(20)
        hLayout3.addWidget(self.textBrowser)
        hLayout3.addSpacing(60)
        
            #主题布局总,纵向布局
            #将之上的三个布局添加到总布局中,并且设置布局间空间为20,最下面的空白为40
        mainLayout = QVBoxLayout()
        mainLayout.addSpacing(20)
        mainLayout.addLayout(hLayout1)
        mainLayout.addSpacing(20)
        mainLayout.addLayout(hLayout2)
        mainLayout.addSpacing(20)
        mainLayout.addLayout(hLayout3)
        mainLayout.addSpacing(40)
        self.setLayout(mainLayout)
        
        
        self.thread = MyThread()
        self.connect(self.thread,SIGNAL("getoutput"),self.append)
        
        
    def append(self,actionType):
        self.textBrowser.clear()
        self.textBrowser.append(actionType)
        #cursor = QTextCursor()
        #self.runButton.setText(self.tr("Stop"))
        
        cursor = self.textBrowser.textCursor()
        cursor.movePosition(QTextCursor.Start)
        self.textBrowser.setTextCursor(cursor)
        #changeLabel = QLabel()
    
    def onActivated(self):
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
            
        """#comBox的相应函数,随着comBox中字符串的改变,分别控制pingLabel的显示,以及lineEdit和textBrower的显示清除和可用状态
            #如果comBox当前的字符串文字为ping
            #pingLabel的文字设置为"提示:请在文本框中输入要ping的目标地址,然后点击执行获取结果",保持当前大小
            #lineEdit中内容清除,设置为不可用
            #textBrower清空"""
        if(self.comBox.currentText() == "Ping" or self.comBox.currentText() == "ping"):
            self.pingLabel.setText(self.tr("Tip:please input the IP address of pinging,then get the result with clicking the button"))
            self.pingLabel.adjustSize()
            self.lineEdit.clear()
            self.lineEdit.setDisabled(False)
            self.textBrowser.clear()
            #如果comBox当前的字符串文字为ifconfig
            #类上所说
        elif(self.comBox.currentText() == "ifconfig"):
            self.pingLabel.setText(self.tr("Tip:get the net information"))
            self.pingLabel.adjustSize()
            self.lineEdit.clear()
            self.lineEdit.setEnabled(False)
            self.textBrowser.clear()
            #如果comBox当前的字符串文字为display
        elif(self.comBox.currentText() == "display"):
            self.pingLabel.setText(self.tr("Tip:get the resolution information"))
            self.pingLabel.adjustSize()
            self.lineEdit.clear()
            self.lineEdit.setEnabled(False)
            self.textBrowser.clear()
        
        elif(self.comBox.currentText() == "top"):
    
            self.pingLabel.setText(self.tr("Tip:run tom command"))
            self.pingLabel.adjustSize()
            self.lineEdit.setEnabled(False)
            self.lineEdit.clear()
            self.textBrowser.clear()
            #按钮的响应函数
    def runButton_clicked(self):
        language = StoreInfoParser.instance().getLanguage()
        m_pTranslator = QTranslator()
        exePath = "./"
        if language == "chinese":
            QmName = "zh_CN.qm"
        else:
            QmName = "en_US.qm"
        if(m_pTranslator.load(QmName, exePath)):
            QCoreApplication.instance().installTranslator(m_pTranslator)
            
        #self.pro = QProcess(self)#外部程序使用声明
        desktop = QApplication.desktop()#获得桌面
        self.textBrowser.clear()#清除
        cmdstr = QString()
        center = QString()
        goal = QString()
        #comBox当前text为ping
        if (self.comBox.currentText() == "Ping" or self.comBox.currentText() == "ping"):
            if (self.runButton.text() == self.tr("Run")) :
                center = self.lineEdit.text().trimmed()
                if not center:
                    InfoHintDialog(self.tr("please input the IP address")).exec_()
#                     self.tipDlg.setTip(self.tr("请输入ping地址!!!"))
#                     self.tipDlg.show()
#                     self.tipDlg.move((desktop.width()-self.tipDlg.width())/2,(desktop.height()-self.tipDlg.height())/2)
                    self.runButton.setText(self.tr("Run"))
                else:
                    self.comBox.setDisabled(True)
                    self.pro = QProcess(self)
                    self.runButton.setText(self.tr("stop ping"))
                    cmdstr = "ping " +center
                    self.textBrowser.clear()
                    self.textBrowser.append(self.tr(" ping ")+center+self.tr(" result:"))
            else:
                self.comBox.setDisabled(False)
                self.runButton.setText(self.tr("Run"))
                self.pro.close()
        elif(self.comBox.currentText() == "ifconfig"):
            self.pro = QProcess(self)
            self.lineEdit.clear()
            self.lineEdit.setEnabled(False)
            self.textBrowser.clear()
            cmdstr = "ifconfig"
#             #如果comBox当前为traceroute
#         elif(self.comBox.currentText() == "traceroute"):
#                 goal = self.lineEdit.text()
#                 if (self.runButton.text() == u"执行"):
#                     if( goal.isEmpty() or goal.isNull() ):
#                         InfoHintDialog(u'请输入tracer地址:').exec_()
# #                         self.tipDlg.setTip(self.tr("请输入tracer地址:"))
# #                         self.tipDlg.show()
# #                         self.tipDlg.move((desktop.width()-self.tipDlg.width())/2,(desktop.height()-self.tipDlg.height())/2)
# #                         
#                         #QMessageBox.information(self,self.tr("错误"),self.tr("请输入traceroute的目标地址"))
#                         #return
#                     else:
#                         self.proc = QProcess(self)
#                         #self.textBrowser.clear()
#                         cmdstrc = "traceroute -n "+ goal
#                         self.proc.start(cmdstrc)
#                         self.connect(self.proc, SIGNAL("readyReadStandardOutput()"),self.readR)
#                         self.connect(self.proc, SIGNAL("readyReadStandardError()"),self.readErrorR)
#                         if self.proc.waitForStarted(10) == True:
#                             self.comBox.setDisabled(True)
#                             self.runButton.setText(self.tr("停止执行"))
#                 else:
#                     self.runButton.setText(self.tr("执行"))
#                     self.comBox.setDisabled(False)
#                     self.proc.close()
#             #如果comBox当前为display
        elif (self.comBox.currentText() == "display"):
            self.pro = QProcess(self)
            cmdstr = "../lib/ccr_jytcapi display"
            self.textBrowser.clear()
            #如果当前命令cmdstr不为空,则
        elif (self.comBox.currentText() == "top"):
            if self.runButton.text() == self.tr("Run") :
                self.thread.start()
                self.comBox.setDisabled(True)
                self.runButton.setText(self.tr("stop top"))
            else:
                self.textBrowser.clear()
                self.thread.auto = False
                #self.thread.destroyed()
                self.comBox.setDisabled(False)
                self.runButton.setText(self.tr("Run"))
        if (cmdstr != ""):
                self.pro.start(cmdstr)#开启执行命令
                self.connect(self.pro, SIGNAL("readyReadStandardOutput()"),self.read)#读取执行正常输出槽函数
                self.connect(self.pro, SIGNAL("readyReadStandardError()"),self.readError)#执行异常槽函数
            
            #读取控制台输出
    def read(self):
        res = QString.fromLocal8Bit(self.pro.readAllStandardOutput())
        self.textBrowser.append(res)#添加到text框
        #读取错误
    def readError(self):
        res = QString.fromLocal8Bit(self.pro.readAllStandardError())
        self.textBrowser.append(res)
    def readR(self):
        
        res = QString.fromLocal8Bit(self.proc.readAllStandardOutput())
        #self.textBrowser.clear()
        self.textBrowser.append(res)
        


    def readErrorR(self):

        res = QString.fromLocal8Bit(self.proc.readAllStandardError())
        self.textBrowser.append(res)
        
    def updateWindow(self):
        if self.pro.isOpen():
            self.pro.close()
            
        self.thread.auto = False
        self.comBox.setDisabled(False)
        self.comBox.setCurrentIndex(0)
        self.runButton.setText((self.tr("Run")))
        self.pingLabel.setText(self.tr("Tip:please input the IP address of pinging,then get the result with clicking the button"))
        self.textBrowser.clear()