I am trying to remove a user from a security group using Python and pywin32, but so far have not been successful. However I am able to add a user to a security group.
from win32com.client import GetObject
grp = GetObject("LDAP://CN=groupname,OU=groups,DC=blah,DC=local")
grp.Add("LDAP://CN=username,OU=users,DC=blah,DC=local") # successfully adds a user to the group
grp.Remove("LDAP://CN=username,OU=users,DC=blah,DC=local") # returns an error
The error is below:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<COMObject LDAP://CN=groupname,OU=groups,DC=blah,DC=local>", line 2, in Remove
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None,
0, -2147024891), None)
I have also tried adding using GetObject to get the user and remove it that way, however I get the same error.
usr = GetObject("LDAP://CN=user,OU=users,DC=blah,DC=local")
grp.Remove(usr)
Any help would be much appreciated as I've hit a dead-end here.
EDIT
I have also now tried using Tim Golden's active_directory module to try and remove the group member.
import active_directory as ad
grp = ad.find_group("groupname")
usr = ad.find_user("username")
grp.remove(usr.path())
However this also doesn't work, and I encounter the below error.
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\active_directory.py", line 799, in __getat
tr__
attr = getattr(self.com_object, name)
AttributeError: 'PyIADs' object has no attribute 'group'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\active_directory.py", line 802, in __getat
tr__
attr = self.com_object.Get(name)
pywintypes.com_error: (-2147463155, 'OLE error 0x8000500d', (0, 'Active Director
y', 'The directory property cannot be found in the cache.\r\n', None, 0, -214746
3155), None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python33\lib\site-packages\active_directory.py", line 1081, in remove
self.group.Remove(dn)
File "C:\Python33\lib\site-packages\active_directory.py", line 804, in __getat
tr__
raise AttributeError
AttributeError
EDIT
Wherby suggested that I change to Python 2.7 and give that a go. I have just tried this:
import active_directory as ad
user = ad.find_user("username")
group = ad.find_group("groupname")
group.remove(user.path())
... but I'm still getting an error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<COMObject LDAP://CN=groupname,OU=groups,DC=blah,DC=local>", line 2, in remove
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None,
0, -2147024891), None)
The user and group are definitely found correctly, as I can print their LDAP paths using print user.path() and print group.path()
Are there any other active directory libraries for Python 3.3 that anyone can recommend?
From
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\active_directory.py", line 799, in __getat
tr__
attr = getattr(self.com_object, name)
AttributeError: 'PyIADs' object has no attribute 'group'
The error indicate you are using not existed "group name", the function find_group required anexisted group name, but you give not existed name.
You should double check "Tim Golden's active_directory module" 's manual.
For
usr = GetObject("LDAP://CN=user,OU=users,DC=blah,DC=local")
grp.Remove(usr)
I suggest you add "print user" to see if the user really get.
Well, I've gone and figured out I was being a bit of a muppet. The account I was logged in to didn't have the permissions to delete from AD groups. When I logged in as the network admin account it worked like a charm.
The final code:
from win32com.client import GetObject
group = GetObject("LDAP://CN=groupname,OU=Groups,DC=blah,DC=local")
group.Remove("LDAP://CN=username,OU=Users,DC=blah,DC=local")
Related
I'm trying to use pywin32 to manipulate SAS Enterprise Guide using Python. But I'm running into some errors. I've tried both Dispatch and EnsureDispatch, but both return the same error:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\win32com\client\dynamic.py", line 89, in _GetGoodDispatch
IDispatch = pythoncom.connect(IDispatch)
pywintypes.com_error: (-2147221021, 'Operation unavailable', None, None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\xxxxxxx\Desktop\test.py", line 4, in <module>
sas = EnsureDispatch('SASEGObjectModel.Application.7.1')
File "C:\ProgramData\Anaconda3\lib\site-packages\win32com\client\gencache.py", line 527, in EnsureDispatch
disp = win32com.client.Dispatch(prog_id)
File "C:\ProgramData\Anaconda3\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch
dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
File "C:\ProgramData\Anaconda3\lib\site-packages\win32com\client\dynamic.py", line 114, in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
File "C:\ProgramData\Anaconda3\lib\site-packages\win32com\client\dynamic.py", line 91, in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
pywintypes.com_error: (-2147024809, 'The parameter is incorrect.', None, None)
(This is using EnsureDispatch, the error using Dispatch is almost the same, only without the 2nd and 3rd lines after the second traceback).
Also, I've tried running makepy (from the same lib) to see what it would return, and I get the following message:
Could not locate a type library matching 'SASEGObjectModel.Application.7.1'
If I try doing it using vbs, using the following code:
Set app = CreateObject("SASEGObjectModel.Application.7.1")
WScript.echo app.Name
It shows a message box with 'Enterprise Guide' written, showing that the object is available to the system.
I've tried asking for help over SAS Support Community, and after many interesting suggestions, I still couldn't solve the issue. But one thing that I hadn't tried, and ended up working, was install a fresh python installation (Not Anaconda), installing PyWIN and it simply worked.
How can I implement a context manager with the following API:
s = "this is my message"
with PushStackFrame(s):
raise RuntimeError("something")
such that when RuntimeError is raised, I get the following message:
Traceback (most recent call last):
File "foo.py", line 4, in <module>
## PushStackFrame: this is my message ## KEY LINE
File "foo.py", line 5, in <module>
raise RuntimeError("something")
RuntimeError: something
Most importantly, I want the string passed to PushStackFrame to be inserted verbatim into the stack trace, I don't want to see just the code.
One way to do this is to catch the exception on the way out of the context manager, figure out where in the traceback the context manager was called, and insert a new traceback frame, before rethrowing the exception with traceback. I'd prefer not to do this.
I have the following function:
def findHardDriveLetter(drivename):
drives = win32api.GetLogicalDriveStrings()
drives = drives.split('\000')[:-1]
for drive in drives:
try:
volname = win32api.GetVolumeInformation(drive)[0].upper()
except:
pass
if volname == drivename.upper():
return drive
Depending on drive state, this error can occur, and I would like my except to catch the specific error:
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "<editor selection>", line 5, in findHardDriveLetter
error: (21, 'GetVolumeInformation', 'The device is not ready.')
Using type(exception).__name__, the error is reposted to be of type error. This seems to be different from the typical format of Python error types, and if I use
except error:
to catch it, I get this exception:
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "<editor selection>", line 20, in findHardDriveLetter
NameError: global name 'error' is not defined
So why is this not working as I expect, and how do I catch this exception without a generic except?
You can except win32api.error since this is the exception type you been getting, but it's generally used as the base class of all win32api exceptions...weird
try:
# ....
except win32api.error:
pass
The InstanceEditor demo example at Enthought GitHub Repository raises the following exception:
Traceback (most recent call last):
File "C:\Users\jgv\AppData\Local\Programs\Python\Python36\lib\site-packages\traitsui\ui.py", line 232, in dispose
self.result = result
File "C:\Users\jgv\AppData\Local\Programs\Python\Python36\lib\site-packages\traits\trait_handlers.py", line 172, in error
value )
traits.trait_errors.TraitError: The 'result' trait of an UI instance must be a boolean, but a value of <PyQt4.QtCore.QObject object at 0x000001EA249AEB88> <class 'PyQt4.QtCore.QObject'> was specified.
Traceback (most recent call last):
File "C:\Users\jgv\AppData\Local\Programs\Python\Python36\lib\site-packages\traitsui\ui.py", line 232, in dispose
self.result = result
File "C:\Users\jgv\AppData\Local\Programs\Python\Python36\lib\site-packages\traits\trait_handlers.py", line 172, in error
value )
traits.trait_errors.TraitError: The 'result' trait of an UI instance must be a boolean, but a value of <PyQt4.QtCore.QObject object at 0x000001EA249AEB88> <class 'PyQt4.QtCore.QObject'> was specified.
when the user interface is used to specify a trait setting.
My system is: Python 3.6.0, traits 4.6.0, PyQt4-4.11.4, and Microsoft Windows 10.
I would appreciate suggestions on how to fix this.
Thanks.
For the record: issue filed and being discussed at https://github.com/enthought/traitsui/issues/331
Environment: Windows 2008 R2 x64, IIS 7
I'm trying to add "Application" and "Application Pool" to IIS. IIS is configured and is running just fine. I've manually added sites/applications - and they work fine as well.
import wmi
oWebAdmin = wmi.GetObject(r"winmgmts:root\WebAdministration")
strApplicationPath = "/my_site"
strSiteName = "Default Web Site"
strPhysicalPath = r"C:\Windows\SysNative\certsrv\mscep"
#fails here:
oWebAdmin.Get('Application').Create(strApplicationPath, strSiteName, strPhysicalPath)
oWebAdmin.Get("ApplicationPool").Create("NewAppPool")
I get the error:
Traceback (most recent call last):
File "C:\work\selenium-project\mdm-setup-assistant\ndes\install_dnes_service.py", line 23, in <module>
oWebAdmin.Get('Application').Create(strApplicationPath, strSiteName, strPhysicalPath)
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 505, in __getattr__
ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'SWbemObjectEx', u'Invalid parameter ', None, 0, -2147217400), None)
The interesting part is that .Create() from msdn says all the parameters I put are valid.
What have I tried:
1) to create Application Pool first (however the order should not matter, since I need to bind them when they are both created)
oWebAdmin.Get("ApplicationPool").Create("NewAppPool")
and, of course, I get the very similar error:
Traceback (most recent call last):
File "C:\work\selenium-project\mdm-setup-assistant\ndes\install_dnes_service.py", line 17, in <module>
oWebAdmin.Get("ApplicationPool").Create("NewAppPool")
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 505, in __getattr__
ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'SWbemObjectEx', u'Invalid parameter ', None, 0, -2147217400), None)
2) I've tried to list the applications. And that works:
oApps = oWebAdmin.InstancesOf("Application")
for app in oApps:
print app.SiteName
print app.Path
print app.ApplicationPool
print app.EnabledProtocols
Output:
Default Web Site
/
DefaultAppPool
http
Default Web Site
/CertSrv/mscep_admin
SCEP
http
Default Web Site
/CertSrv/mscep
SCEP
http
MyApp
/
MyApp AppPool
http
What could be wrong with my .Create() call?
NOTE: I'm running with elevated privileges (if that matters)
UPDATE: Could .Get be failing?: No, it's definetely .Create():
app = oWebAdmin.Get('Application')
#fails here:
app.Create(strApplicationPath, strSiteName, strPhysicalPath)
error:
Traceback (most recent call last):
File "C:\work\selenium-project\mdm-setup-assistant\ndes\install_dnes_service.py", line 18, in <module>
app.Create(strApplicationPath, strSiteName, strPhysicalPath)
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 505, in __getattr__
ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'SWbemObjectEx', u'Invalid parameter ', None, 0, -2147217400), None)
Are you sure it's not the GET that's failing?