Cannot create Application/ApplicationPool for IIS7 through WMI - python

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?

Related

Error While Checking Windows Updates using Python

I am using Python 3.9.5,
Using the module
from windows_tools.updates import get_windows_updates
After importing, when I try to execute the command get_windows_updates()
Following is the error it's showing,
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
get_windows_updates()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\windows_tools\updates\__init__.py", line 69, in get_windows_updates
'operation': OPERATION_CODES[int(entry.Operation)],
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\win32com\client\dynamic.py", line 628, in __getattr__
ret = self._oleobj_.Invoke(retEntry.dispid, 0, invoke_type, 1)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2145120257), None)
Can anyone help me out to resolve this please?

Issues trying to Dispatch a SASEGObjectModel COM Object with Python using win32com

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 to Get pywin32 Methods to Accept Variable Parameters

I'm using pywin32 to write a program that sends email notifications. Based on error exceptions
def main(recipient):
try:
mailer = Dispatch("Outlook.Application")
msg = mailer.CreateItem(0)
msg.To = recipient
msg.CC = ""
msg.Subject = "EmailTest"
msg.Body = "This is most certainly a test"
msg.Send()
success(msg.Subject, recipient)
except Exception:
failure(msg.Subject, recipient)
When the parameters to the success and fail methods are variables (with string values) it returns the error:
Traceback (most recent call last):
File "C:\pathtoprogram\thisprogram.py", line 48, in main
success(msg.Subject, recipient)
File "C:\Users\myuser\AppData\Local\Programs\Python\Python36-32\lib\site-packages\win32com\client\dynamic.py", line 516, in __getattr__
ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'The item has been moved or deleted.', None, 0, -2147221238), None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "C:\pathtoprogram\thisprogram.py", line 50, in main
failure(msg.Subject, recipient)
File "C:\Users\myuser\AppData\Local\Programs\Python\Python36-32\lib\site-packages\win32com\client\dynamic.py", line 516, in __getattr__
ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'The item has been moved or deleted.', None, 0, -2147221238), None)
I don't know what's creating the exception, but the code works fine when I enter the parameters directly as strings.
success("mySubject", "anEmail")
except Exception:
failure("mySubject", "anEmail")
That code works will run fine, but I need the parameters to be variables because they need to be able to be passed in from the main method.
I've been looking up answers to similar problems but I haven't found one that pertains to this issue. It seems like msg.Subject and msg.To don't actually store string values even though they're in what looks like any other assignment statement. Maybe it's an obvious thing I'm missing?
Any help would be greatly appreciated.
I'm using python 3.6 and the corresponding version of pywin32.
The problem is not with the way you are using the variables. You can test this by checking the values of msg.Subject before you call msg.Send()
Refer to the CDO (collaboration data objects) documentation from Microsoft, specifically for the Send method:
https://msdn.microsoft.com/en-us/library/ms527190(v=exchg.10).aspx
Send moves the message to the current users Outbox folder. Messaging systems retrieve messages from the Outbox and transport them to the recipients. After it is transported, a message is removed from the Outbox and deleted unless saveCopy is True.*
Refer to the error message you were getting:
4096, 'Microsoft Outlook', 'The item has been moved or deleted.'
So the system is doing what it was designed to do - delete the message after you send it.

Remove AD user from Security group using Python

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")

Unable to create file system object in wmi using python

I connected to remote windows server using wmi. I want to create filesystem object to extract file version of file on remote server.
My code goes like this:
# mc_name-machine name, login_machine() to login
c = login_machine(mc_name)
print "logged-in"
# erroneous line.
fo = c.win32com.client.Dispatch('Scripting.filesystemobject')
# path=path of file on remote machine
print fo.GetFileVersion(path)
Help will be greatly appreciated.
For the erroneous line in above code error thrown:
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\wmi.py", line 1145, in __getattr__
return self._cached_classes (attribute)
File "C:\Python34\lib\site-packages\wmi.py", line 1156, in _cached_classes
self._classes_map[class_name] = _wmi_class (self, self._namespace.Get (class_name))
File "<COMObject <unknown>>", line 3, in Get
File "C:\Python34\lib\site-packages\win32com\client\dynamic.py", line 282, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'SWbemServicesEx', 'Not found ', None, 0, -2147217406), None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#54>", line 1, in <module>
fo=c.win32com.client.Dispatch('Scripting.filesystemobject')
File "C:\Python34\lib\site-packages\wmi.py", line 1147, in __getattr__
return getattr (self._namespace, attribute)
File "C:\Python34\lib\site-packages\win32com\client\dynamic.py", line 522, in __getattr__
raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: <unknown>.win32com
I was trying to solve this by using ProvideConstants. Code for same
fo = win32com.client.Dispatch('Scripting.filesystemobject')
foo=ProvideConstants(fo)
I'm not sure how to use this wmi.ProvideConstants object to get file version.
I was able to query the version of a remote file with this code:
c = wmi.WMI('computer', user='domain\\user', password='pass')
result = c.query('SELECT * FROM CIM_DataFile WHERE Name = "C:\\path\to\file"')
for file in result:
print file.Version
Update: To get the LastModifed time as a python datetime object, and print it out in dd/mm/yyyy format:
from datetime import datetime
last_modified = datetime(*wmi.to_time(file.LastModified)[:7])
print last_modified.strftime("%d/%m/%Y")

Categories