Ejemplo n.º 1
0
    def get_alldevices(self):
        dv = QNetworkInterface.allInterfaces()
        # nan = [interface.addressEntries() for interface
        #        in dv]
        availabledevices = {
            interface.humanReadableName():
            interface.addressEntries()[i].ip().toString()
            for interface in dv for i in range(len(interface.addressEntries()))
            if (len(interface.addressEntries())
                and not interface.addressEntries()[i].ip().isLinkLocal() and
                interface.addressEntries()[i].ip().toString() != "127.0.0.1"
                and ":" not in interface.addressEntries()[i].ip().toString()
                and "." in interface.addressEntries()[i].ip().toString())
        }

        self.devicedict = {
            k: v
            for k, v in sorted(availabledevices.items(),
                               key=lambda item: item[1],
                               reverse=True)
        }
        # if len(self.devicedict)==0:
        #     self.showm_signal.emit("未接入网络!")
        print(self.devicedict)
        return self.devicedict
Ejemplo n.º 2
0
    def run(self):
        localHostName = QHostInfo.localHostName()
        hostinfo = QHostInfo.fromName(localHostName)
        listaddress = hostinfo.addresses()

        for address in listaddress:
            if QHostAddress(
                    address).protocol() == QAbstractSocket.IPv4Protocol:
                address = QHostAddress(address).toString()
        print(address)

        host_info = ""
        confList = QNetworkConfigurationManager().allConfigurations()
        print("confList = ", confList.__len__())
        for conf in confList:
            if str(conf.bearerTypeName()) == "Ethernet":
                host_info += "\n"
                host_info += "name : " + QNetworkConfiguration(
                    conf).name() + "\n"
                host_info += str(QNetworkConfiguration(conf).isValid()) + "\n"
                host_info += "bearerType: " + QNetworkConfiguration(
                    conf).bearerTypeName() + "\n"

        list = QNetworkInterface.allInterfaces()
        for interface in list:
            host_info += "\n"
            host_info += "=============================\n"
            host_info += "name: " + interface.name() + "\n"
            host_info += QNetworkInterface(interface).hardwareAddress() + "\n"
            host_info += str(QNetworkInterface(interface).isValid()) + "\n"
            host_info += "---------\n"
            if QNetworkInterface(interface).flags() & QNetworkInterface.IsUp:
                host_info += "Interface: is up\n"
            if QNetworkInterface(
                    interface).flags() & QNetworkInterface.IsLoopBack:
                host_info += "Interface: is loop back\n"  # 迴環地址
            if QNetworkInterface(
                    interface).flags() & QNetworkInterface.IsRunning:
                host_info += "Interface: is running \n"  # 網絡已經啓動運行
            if interface.flags() & QNetworkInterface.CanMulticast:
                host_info += "Interface: CanMulticast\n"  # 多播
            if interface.flags() & QNetworkInterface.CanBroadcast:
                host_info += "Interface: CanBroadcast\n"
            host_info += "---------\n"

            entryList = QNetworkInterface(interface).addressEntries()
            for entry in entryList:
                address = entry.ip()
                if QHostAddress(address).protocol(
                ) == QAbstractSocket.IPv4Protocol:  # and  \
                    # str(address.toString()) != "127.0.0.1":
                    host_info += "IP Address: " + QNetworkAddressEntry(
                        entry).ip().toString() + "\n"
                    host_info += "Netmask: " + QNetworkAddressEntry(
                        entry).netmask().toString() + "\n"
                    host_info += "Broadcast: " + QNetworkAddressEntry(
                        entry).broadcast().toString() + "\n"
            host_info += "=============================\n"
        self.sig.emit(host_info)
Ejemplo n.º 3
0
 def load_all(self):
     for i in QNetworkInterface.allInterfaces():
         for e in i.addressEntries():
             if e.ip().isLoopback() == False and i.isValid() and e.ip(
             ).isMulticast() == False and e.ip().isNull() == False and e.ip(
             ).protocol() == QAbstractSocket.IPv4Protocol and e.ip(
             ).isLinkLocal() == False:
                 self.append(Interface(self.mem).init__create(i, e))
Ejemplo n.º 4
0
    def fillActivateIps(self):
        print("start fill")
        for interface in QNetworkInterface.allInterfaces():
            iflags = interface.flags()
            if (iflags & QNetworkInterface.IsRunning) and  not (iflags  & QNetworkInterface.IsLoopBack) :
                for addrentry in interface.addressEntries():
#                    print("append ",addrentry.ip().toString(),addrentry.ip().protocol())
                    if addrentry.ip().protocol() == QAbstractSocket.IPv4Protocol:
                        self.plainTextEdit_iplist.appendPlainText("{}:{}".format(addrentry.ip().toString(), self.port))
Ejemplo n.º 5
0
def isConnectedToNetwork(reference=None):
    ifaces = QNetworkInterface.allInterfaces()
    result = False
    for iface in ifaces:
        if (iface.flags() & QNetworkInterface.IsUp) and not (iface.flags() & QNetworkInterface.IsLoopBack):
            for entry in iface.addressEntries():
                result = True
                break
    return result
Ejemplo n.º 6
0
def get_local_ip4():
    """
    Creates a dictionary of local IPv4 interfaces on local machine.
    If no active interfaces available, returns a dict of localhost IPv4 information

    :returns: Dict of interfaces
    """
    # Get the local IPv4 active address(es) that are NOT localhost (lo or '127.0.0.1')
    log.debug('Getting local IPv4 interface(es) information')
    my_ip4 = {}
    for iface in QNetworkInterface.allInterfaces():
        log.debug('Checking for isValid and flags == IsUP | IsRunning')
        if not iface.isValid() or not (
                iface.flags() &
            (QNetworkInterface.IsUp | QNetworkInterface.IsRunning)):
            continue
        log.debug('Checking address(es) protocol')
        for address in iface.addressEntries():
            ip = address.ip()
            # NOTE: Next line will skip if interface is localhost - keep for now until we decide about it later
            # if (ip.protocol() == QAbstractSocket.IPv4Protocol) and (ip != QHostAddress.LocalHost):
            log.debug('Checking for protocol == IPv4Protocol')
            if ip.protocol() == QAbstractSocket.IPv4Protocol:
                log.debug('Getting interface information')
                my_ip4[iface.name()] = {
                    'ip':
                    ip.toString(),
                    'broadcast':
                    address.broadcast().toString(),
                    'netmask':
                    address.netmask().toString(),
                    'prefix':
                    address.prefixLength(),
                    'localnet':
                    QHostAddress(address.netmask().toIPv4Address()
                                 & ip.toIPv4Address()).toString()
                }
                log.debug(
                    'Adding {iface} to active list'.format(iface=iface.name()))
    if 'localhost' in my_ip4:
        log.debug('Renaming windows localhost to lo')
        my_ip4['lo'] = my_ip4['localhost']
        my_ip4.pop('localhost')
    if len(my_ip4) == 0:
        log.warning('No active IPv4 network interfaces detected')
    if len(my_ip4) == 1:
        if 'lo' in my_ip4:
            # No active interfaces - so leave localhost in there
            log.warning('No active IPv4 interfaces found except localhost')
    else:
        # Since we have a valid IP4 interface, remove localhost
        if 'lo' in my_ip4:
            log.debug('Found at least one IPv4 interface, removing localhost')
            my_ip4.pop('lo')

    return my_ip4
Ejemplo n.º 7
0
def isConnectedToNetwork(reference=None):
    ifaces = QNetworkInterface.allInterfaces()
    result = False
    for iface in ifaces:
        if (iface.flags() & QNetworkInterface.IsUp
            ) and not (iface.flags() & QNetworkInterface.IsLoopBack):
            for entry in iface.addressEntries():
                result = True
                break
    return result
Ejemplo n.º 8
0
 def _available_server_ipv4_addresses(self):
     from PyQt5.QtNetwork import QNetworkInterface, QAbstractSocket
     a = []
     for ni in QNetworkInterface.allInterfaces():
         flags = ni.flags()
         if (flags & QNetworkInterface.IsUp
             ) and not (flags & QNetworkInterface.IsLoopBack):
             for ae in ni.addressEntries():
                 ha = ae.ip()
                 if (ha.protocol() == QAbstractSocket.IPv4Protocol
                         and not ha.isLoopback() and not ha.isNull()
                         and not ha.toString().startswith('169.254')
                     ):  # Exclude link-local addresses
                     a.append(ha)
     return a
Ejemplo n.º 9
0
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent object (QObject)
        """
        super(CooperationClient, self).__init__(parent)

        self.__chatWidget = parent

        self.__servers = []
        for networkInterface in QNetworkInterface.allInterfaces():
            for addressEntry in networkInterface.addressEntries():
                address = addressEntry.ip()
                # fix scope of link local addresses
                if address.toString().lower().startswith("fe80"):
                    address.setScopeId(networkInterface.humanReadableName())
                server = CooperationServer(address, self)
                server.newConnection.connect(self.__newConnection)
                self.__servers.append(server)

        self.__peers = collections.defaultdict(list)

        self.__initialConnection = None

        envVariables = [
            "USERNAME.*", "USER.*", "USERDOMAIN.*", "HOSTNAME.*",
            "DOMAINNAME.*"
        ]
        environment = QProcess.systemEnvironment()
        found = False
        for envVariable in envVariables:
            for env in environment:
                if QRegExp(envVariable).exactMatch(env):
                    envList = env.split("=")
                    if len(envList) == 2:
                        self.__username = envList[1].strip()
                        found = True
                        break

            if found:
                break

        if self.__username == "":
            self.__username = self.tr("unknown")

        self.__listening = False
        self.__serversErrorString = ""
Ejemplo n.º 10
0
 def __init__(self, parent=None):
     """
     Constructor
     
     @param parent reference to the parent object (QObject)
     """
     super(CooperationClient, self).__init__(parent)
     
     self.__chatWidget = parent
     
     self.__servers = []
     for networkInterface in QNetworkInterface.allInterfaces():
         for addressEntry in networkInterface.addressEntries():
             address = addressEntry.ip()
             # fix scope of link local addresses
             if address.toString().lower().startswith("fe80"):
                 address.setScopeId(networkInterface.humanReadableName())
             server = CooperationServer(address, self)
             server.newConnection.connect(self.__newConnection)
             self.__servers.append(server)
     
     self.__peers = collections.defaultdict(list)
     
     self.__initialConnection = None
     
     envVariables = ["USERNAME.*", "USER.*", "USERDOMAIN.*",
                     "HOSTNAME.*", "DOMAINNAME.*"]
     environment = QProcess.systemEnvironment()
     found = False
     for envVariable in envVariables:
         for env in environment:
             if QRegExp(envVariable).exactMatch(env):
                 envList = env.split("=")
                 if len(envList) == 2:
                     self.__username = envList[1].strip()
                     found = True
                     break
         
         if found:
             break
     
     if self.__username == "":
         self.__username = self.tr("unknown")
     
     self.__listening = False
     self.__serversErrorString = ""
Ejemplo n.º 11
0
def get_network_interfaces():
    """
    Creates a dictionary of local IPv4 interfaces on local machine.
    If no active interfaces available, returns a dict of localhost IPv4 information

    :returns: Dict of interfaces
    """
    log.debug('Getting local IPv4 interface(es) information')
    interfaces = {}
    for interface in QNetworkInterface.allInterfaces():
        interface_name = interface.name()
        if INTERFACE_FILTER.search(interface_name):
            log.debug(
                'Filtering out interfaces we don\'t care about: {name}'.format(
                    name=interface_name))
            continue
        log.debug('Checking for isValid and flags == IsUP | IsRunning')
        if not interface.isValid() or not (
                interface.flags() &
            (QNetworkInterface.IsUp | QNetworkInterface.IsRunning)):
            continue
        log.debug('Checking address(es) protocol')
        for address in interface.addressEntries():
            ip = address.ip()
            log.debug('Checking for protocol == IPv4Protocol')
            if ip.protocol() == QAbstractSocket.IPv4Protocol:
                log.debug('Getting interface information')
                interfaces[interface_name] = {
                    'ip':
                    ip.toString(),
                    'broadcast':
                    address.broadcast().toString(),
                    'netmask':
                    address.netmask().toString(),
                    'prefix':
                    address.prefixLength(),
                    'localnet':
                    QHostAddress(address.netmask().toIPv4Address()
                                 & ip.toIPv4Address()).toString()
                }
                log.debug('Adding {interface} to active list'.format(
                    interface=interface.name()))
    if len(interfaces) == 0:
        log.warning('No active IPv4 network interfaces detected')
    return interfaces
Ejemplo n.º 12
0
    def __init__(self):
        """
        Constructor
        """
        super(DebuggerGeneralPage, self).__init__()
        self.setupUi(self)
        self.setObjectName("DebuggerGeneralPage")

        t = self.execLineEdit.whatsThis()
        if t:
            t += Utilities.getPercentReplacementHelp()
            self.execLineEdit.setWhatsThis(t)

        try:
            backends = e5App().getObject("DebugServer").getSupportedLanguages()
            for backend in sorted(backends):
                self.passiveDbgBackendCombo.addItem(backend)
        except KeyError:
            self.passiveDbgGroup.setEnabled(False)

        t = self.consoleDbgEdit.whatsThis()
        if t:
            t += Utilities.getPercentReplacementHelp()
            self.consoleDbgEdit.setWhatsThis(t)

        self.consoleDbgCompleter = E5FileCompleter(self.consoleDbgEdit)
        self.dbgTranslationLocalCompleter = E5DirCompleter(
            self.dbgTranslationLocalEdit)

        # set initial values
        interfaces = []
        networkInterfaces = QNetworkInterface.allInterfaces()
        for networkInterface in networkInterfaces:
            addressEntries = networkInterface.addressEntries()
            if len(addressEntries) > 0:
                for addressEntry in addressEntries:
                    if ":" in addressEntry.ip().toString() and \
                            not socket.has_ipv6:
                        continue  # IPv6 not supported by Python
                    interfaces.append("{0} ({1})".format(
                        networkInterface.humanReadableName(),
                        addressEntry.ip().toString()))
        self.interfacesCombo.addItems(interfaces)
        interface = Preferences.getDebugger("NetworkInterface")
        if not socket.has_ipv6:
            # IPv6 not supported by Python
            self.all6InterfacesButton.setEnabled(False)
            if interface == "allv6":
                interface = "all"
        if interface == "all":
            self.allInterfacesButton.setChecked(True)
        elif interface == "allv6":
            self.all6InterfacesButton.setChecked(True)
        else:
            self.selectedInterfaceButton.setChecked(True)
            index = -1
            for i in range(len(interfaces)):
                if QRegExp(".*{0}.*".format(interface))\
                        .exactMatch(interfaces[i]):
                    index = i
                    break
            self.interfacesCombo.setCurrentIndex(index)

        self.allowedHostsList.addItems(Preferences.getDebugger("AllowedHosts"))

        self.remoteCheckBox.setChecked(
            Preferences.getDebugger("RemoteDbgEnabled"))
        self.hostLineEdit.setText(Preferences.getDebugger("RemoteHost"))
        self.execLineEdit.setText(Preferences.getDebugger("RemoteExecution"))

        if self.passiveDbgGroup.isEnabled():
            self.passiveDbgCheckBox.setChecked(
                Preferences.getDebugger("PassiveDbgEnabled"))
            self.passiveDbgPortSpinBox.setValue(
                Preferences.getDebugger("PassiveDbgPort"))
            index = self.passiveDbgBackendCombo.findText(
                Preferences.getDebugger("PassiveDbgType"))
            if index == -1:
                index = 0
            self.passiveDbgBackendCombo.setCurrentIndex(index)

        self.debugEnvironReplaceCheckBox.setChecked(
            Preferences.getDebugger("DebugEnvironmentReplace"))
        self.debugEnvironEdit.setText(
            Preferences.getDebugger("DebugEnvironment"))
        self.automaticResetCheckBox.setChecked(
            Preferences.getDebugger("AutomaticReset"))
        self.debugAutoSaveScriptsCheckBox.setChecked(
            Preferences.getDebugger("Autosave"))
        self.consoleDbgCheckBox.setChecked(
            Preferences.getDebugger("ConsoleDbgEnabled"))
        self.consoleDbgEdit.setText(
            Preferences.getDebugger("ConsoleDbgCommand"))
        self.dbgPathTranslationCheckBox.setChecked(
            Preferences.getDebugger("PathTranslation"))
        self.dbgTranslationRemoteEdit.setText(
            Preferences.getDebugger("PathTranslationRemote"))
        self.dbgTranslationLocalEdit.setText(
            Preferences.getDebugger("PathTranslationLocal"))
        self.debugThreeStateBreakPoint.setChecked(
            Preferences.getDebugger("ThreeStateBreakPoints"))
        self.dontShowClientExitCheckBox.setChecked(
            Preferences.getDebugger("SuppressClientExit"))
        self.exceptionBreakCheckBox.setChecked(
            Preferences.getDebugger("BreakAlways"))
        self.exceptionShellCheckBox.setChecked(
            Preferences.getDebugger("ShowExceptionInShell"))
        self.autoViewSourcecodeCheckBox.setChecked(
            Preferences.getDebugger("AutoViewSourceCode"))
Ejemplo n.º 13
0
 def __init__(self):
     """
     Constructor
     """
     super(DebuggerGeneralPage, self).__init__()
     self.setupUi(self)
     self.setObjectName("DebuggerGeneralPage")
     
     t = self.execLineEdit.whatsThis()
     if t:
         t += Utilities.getPercentReplacementHelp()
         self.execLineEdit.setWhatsThis(t)
     
     try:
         backends = e5App().getObject("DebugServer").getSupportedLanguages()
         for backend in sorted(backends):
             self.passiveDbgBackendCombo.addItem(backend)
     except KeyError:
         self.passiveDbgGroup.setEnabled(False)
     
     t = self.consoleDbgEdit.whatsThis()
     if t:
         t += Utilities.getPercentReplacementHelp()
         self.consoleDbgEdit.setWhatsThis(t)
     
     self.consoleDbgCompleter = E5FileCompleter(self.consoleDbgEdit)
     self.dbgTranslationLocalCompleter = E5DirCompleter(
         self.dbgTranslationLocalEdit)
     
     # set initial values
     interfaces = []
     networkInterfaces = QNetworkInterface.allInterfaces()
     for networkInterface in networkInterfaces:
         addressEntries = networkInterface.addressEntries()
         if len(addressEntries) > 0:
             for addressEntry in addressEntries:
                 if ":" in addressEntry.ip().toString() and \
                         not socket.has_ipv6:
                     continue    # IPv6 not supported by Python
                 interfaces.append(
                     "{0} ({1})".format(
                         networkInterface.humanReadableName(),
                         addressEntry.ip().toString()))
     self.interfacesCombo.addItems(interfaces)
     interface = Preferences.getDebugger("NetworkInterface")
     if not socket.has_ipv6:
         # IPv6 not supported by Python
         self.all6InterfacesButton.setEnabled(False)
         if interface == "allv6":
             interface = "all"
     if interface == "all":
         self.allInterfacesButton.setChecked(True)
     elif interface == "allv6":
         self.all6InterfacesButton.setChecked(True)
     else:
         self.selectedInterfaceButton.setChecked(True)
         index = -1
         for i in range(len(interfaces)):
             if QRegExp(".*{0}.*".format(interface))\
                     .exactMatch(interfaces[i]):
                 index = i
                 break
         self.interfacesCombo.setCurrentIndex(index)
     
     self.allowedHostsList.addItems(
         Preferences.getDebugger("AllowedHosts"))
     
     self.remoteCheckBox.setChecked(
         Preferences.getDebugger("RemoteDbgEnabled"))
     self.hostLineEdit.setText(
         Preferences.getDebugger("RemoteHost"))
     self.execLineEdit.setText(
         Preferences.getDebugger("RemoteExecution"))
     
     if self.passiveDbgGroup.isEnabled():
         self.passiveDbgCheckBox.setChecked(
             Preferences.getDebugger("PassiveDbgEnabled"))
         self.passiveDbgPortSpinBox.setValue(
             Preferences.getDebugger("PassiveDbgPort"))
         index = self.passiveDbgBackendCombo.findText(
             Preferences.getDebugger("PassiveDbgType"))
         if index == -1:
             index = 0
         self.passiveDbgBackendCombo.setCurrentIndex(index)
     
     self.debugEnvironReplaceCheckBox.setChecked(
         Preferences.getDebugger("DebugEnvironmentReplace"))
     self.debugEnvironEdit.setText(
         Preferences.getDebugger("DebugEnvironment"))
     self.automaticResetCheckBox.setChecked(
         Preferences.getDebugger("AutomaticReset"))
     self.debugAutoSaveScriptsCheckBox.setChecked(
         Preferences.getDebugger("Autosave"))
     self.consoleDbgCheckBox.setChecked(
         Preferences.getDebugger("ConsoleDbgEnabled"))
     self.consoleDbgEdit.setText(
         Preferences.getDebugger("ConsoleDbgCommand"))
     self.dbgPathTranslationCheckBox.setChecked(
         Preferences.getDebugger("PathTranslation"))
     self.dbgTranslationRemoteEdit.setText(
         Preferences.getDebugger("PathTranslationRemote"))
     self.dbgTranslationLocalEdit.setText(
         Preferences.getDebugger("PathTranslationLocal"))
     self.debugThreeStateBreakPoint.setChecked(
         Preferences.getDebugger("ThreeStateBreakPoints"))
     self.dontShowClientExitCheckBox.setChecked(
         Preferences.getDebugger("SuppressClientExit"))
     self.exceptionBreakCheckBox.setChecked(
         Preferences.getDebugger("BreakAlways"))
     self.exceptionShellCheckBox.setChecked(
         Preferences.getDebugger("ShowExceptionInShell"))
     self.autoViewSourcecodeCheckBox.setChecked(
         Preferences.getDebugger("AutoViewSourceCode"))