Query SCCM from Task Sequence - is it possible? - wmi

I have a VBscript which works abolultuly fine on my workstation. It queries SCCM to find out what domain a computer is in. When I run it as part of the task sequence, it fails. Note that this is almost the last step in the task sequence, under Windows 7, not Windows PE.
Option Explicit
Const wbemFlagReturnImmediately = &H10
Const wbemFlagForwardOnly = &H20
Dim computerName, userName, userPassword, server
Dim swbemLocator, swbemServices, providerLoc
Dim location, connection
Dim query, found, resource, resources
'--- Settings ---
userName = "domain\username"
userPassword = "password"
server = "domain.com"
'--- Get computer name ---
computerName = CreateObject("WScript.Network").ComputerName
WScript.Echo"Computer name: " & computerName
'--- Connect ----
Set swbemLocator = CreateObject("WbemScripting.SWbemLocator")
swbemLocator.Security_.AuthenticationLevel = 6
Set swbemServices = swbemLocator.ConnectServer(server, "root\sms",userName,userPassword)
Set providerLoc = swbemServices.InstancesOf("SMS_ProviderLocation")
For Each location In providerLoc
If location.ProviderForLocalSite = True Then
WScript.Echo "SiteCode: " & location.SiteCode
Set connection = swbemLocator.ConnectServer(server, "root\sms\site_" + location.SiteCode)
Else
WScript.Echo "Not provider for local site."
End If
Next
'--- Query & output ---
query = "SELECT * FROM SMS_FullCollectionMembership WHERE name = '" & computerName & "'"
Set resources = connection.ExecQuery(query, , wbemFlagForwardOnly Or wbemFlagReturnImmediately)
found = False
For Each resource In resources
WScript.Echo "Domain: " & resource.Domain & " (" & resource.CollectionID & ")"
found = True
Exit For
Next
If Not found Then WScript.Echo "Computer not found!"
If I open a command prompt ruing the task sequence (using F8 under Windows 7, not Windows PE) and run the script, I get:
SWbemLocator: Access is denied
on the line:
Set connection = swbemLocator.ConnectServer(server, "root\sms\site_" + location.SiteCode)
Any thoughts? Alternatively, any other suggestions on how to find out what domain a computer was in last time it was built?

Your Task Sequence runs in context of the the local system account, and per default this account has no rights in SCCM.
If you define "yourdomain\domain computers" in the SCCM admin console, Security Rights, Users, and give them read and read resource rights on Collection, you should be able to connect to your SCCM server.
Please notice, you have to do this on all site servers you want to connect to, these definitons are not replicated between sites.

I realise this is a very old post but I just had this problem myself.
You already have the username and password in the script and it is used here
Set swbemServices = swbemLocator.ConnectServer(server, "root\sms",userName,userPassword)
However just a bit further down you are making a connection to the site without the username and password.
Set connection = swbemLocator.ConnectServer(server, "root\sms\site_" + location.SiteCode)
Try this:
Set connection = swbemLocator.ConnectServer(server, "root\sms\site_" + location.SiteCode, userName, userPassword)
Hope this helps someone!

Related

Connecting DC Remote HyperV server in c#

I am trying to connect a hyperV server remotely which is the part of same Domain Controller as the local system is. It works if I give username without AD, but fails every time(with error "invalid parameter") when username is with AD.e.g. AD\administrator.
// This works
Impersonation = ImpersonationLevel.Impersonate;
Authority = "ntlmdomain:" + _domain;
options.Username = "administrator";
options.Password = _authPas;
//But this doesn't work
Impersonation = ImpersonationLevel.Impersonate;
Authority = "ntlmdomain:" + _domain;
options.Username = "testAD\\administrator";
options.Password = _authPas;
Any help will be highly appreciated.
Why you are giving the Domain name in username after you provided the domain name in "Authority"
Already the Domain is mentioned in Authority so the the username should be only Username without domainname
Giving multiple times will not work

My webservice using apache shiro always return unauthorized

I have this shiro.ini:
[main]
ds = org.apache.shiro.jndi.JndiObjectFactory
ds.requiredType = javax.sql.DataSource
ds.resourceName = java:/comp/env/jdbc/myDS
# JDBC realm config
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.authenticationQuery = "SELECT password FROM user WHERE username = ?"
jdbcRealm.dataSource = $ds
credentialsMatcher = org.apache.shiro.authc.credential.Sha256CredentialsMatcher
# base64 encoding, not hex in this example:
credentialsMatcher.storedCredentialsHexEncoded = false
credentialsMatcher.hashIterations = 1024
jdbcRealm.credentialsMatcher = $credentialsMatcher
[urls]
/logout = logout
/** = authcBasic
Im debbuging JndiRealm in doGetAuthenticationInfo. I get an exception when shiro try to execute my authenticationQuery in getPasswordForUser method. Those are the lines that execute the select:
ps = conn.prepareStatement(authenticationQuery);
ps.setString(1, username);
My atuthenticationQuery is "SELECT password FROM user WHERE username = ?" so trying to access position 1 is invalid since it starts from position 0. Is that a bug on JndiRealm from apache shiro or i wrote my sql wrong?
Looks like you have a simple mock implementation of a realm.
For logging in to work, you needs 2 steps:
authentication (is the username/password correct)
authorization (what is the user allowed to do)
Looks like you have only created the first step, but you are just giving back the password in the return statement.
Shiro will hash the password that was entered by the user. You should have the same hash stored somewhere in your database. In the doGetAuthenticationInfo you should do a lookup based on the username that was entered and retrieve the hash (either from the db, or disk or whatever you prefer), that is what you should put in the SimpleAuthenticationInfo object and return, shiro will do the user password hashing and comparison for you.
For the second step, override the method doGetAuthorizationInfo. You could let it return an instance of SimpleAuthorixationInfo containg a set of permissions, the simplest being "*", when it has access to everything.
Creating such a method can be as simple as:
#Override
public AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//here you can create custom permissions based on the principal
//that has been authenticated using your own logic
info.addStringPermission("*");
return info;
}

Entity Framework receives Access Denied, while plain SQL commands not

I am trying to force Entity Framework to create database at my desired location, but it always complains on "Access denied":
Error was: Unhandled exception: (System.Data.SqlClient.SqlException)
Unable to open the physical file "D:\te_mp\zeliboba_odin.mdf".
Operating system error 5: "5(Access denied.)".
But if I use plain SQL Commands with the same connection string - then DB is created successfully.
var createDbSql = String.Format(
"CREATE DATABASE {0} ON PRIMARY (NAME = {0}_Data, FILENAME = '{1}.mdf', SIZE = 10MB, " +
" FILEGROWTH = 10%) LOG ON (NAME = {0}_Log, FILENAME = '{1}.ldf', SIZE = 1MB, FILEGROWTH = 10%) ",
dbName, filename);
What's the difference between these two cases? Why EF fails?
Update 1:
First connection string is:
var sqlConnection = new SqlConnection(#"Server=.\SQLEXPRESS;Integrated Security=SSPI;");
This will work got plain SQL commands sent to server - I am creating databases right now.
Next I create DB, and I have its name. So I do like this:
var connectionString = String.Format(#"Data Source=.\SQLEXPRESS;Integrated Security=SSPI;database={0}", dbName);
sqlConnection = new SqlConnection(connectionString);
using (var db = new MyDbContext(sqlConnection, true)) {
// EF creates database without any troubles.
}
What I tried with EF - set AttachDatabaseFile (cant remember exact name of parameter). EF really tries to create a database at provided location, but it fails with Access denied error. I tried to play with args in connection string, but I failed, and I do not know how can I point EF to create database at particular folder with particular filenames (making sure SQL Server can create database there itself).
SQL Server database engine service account must have permissions to read/write in the new folder.
Attaching Database – Unable to Open Physical File (Access is Denied)

WMI: "The RPC Server is unavailable" error only for domain user

I'm trying to execute a program that is on machine B (Part of a domain) from machine A (Not part of domain). I've the following code and throws "The RPC Server is unavailable" when I tried to use a domain user that is part of machine B's Administrators group. When I use the local user "administrator" which is also part of Machine B's Administrators group, the code works fine.
Firewall is disabled on both the machines. I could logon to machine B from machine A using both the users.
Could you help me with it?
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.Authority = "kerberos:" + domain + #"\" + machine;
connectionOptions.Impersonation = ImpersonationLevel.Impersonate;
connectionOptions.Authentication = AuthenticationLevel.PacketPrivacy;
connectionOptions.Username = username;
connectionOptions.Password = password;
ManagementScope scope = new ManagementScope(#"\\" + machine + "." + domain + #"\root\CIMV2", connectionOptions);
ManagementPath p = new ManagementPath("Win32_Process");
ManagementClass classInstance = new ManagementClass(scope, p, null);
ManagementClass startupSettings = new ManagementClass("Win32_ProcessStartup");
startupSettings.Scope = scope;
startupSettings["CreateFlags"] = 16777216;
I could sort the problem out. The domain controller was not accessible. Also, both public and private IPs were configured to my machine. The private IP was the primary and public was secondary. I needed to use them accordingly when needed.

How to invoke a web service call using vbscript

i am beginner in coding.
I have to call a web service below:
http://www.w3schools.com/webservices/tempconvert.asmx?op=CelsiusToFahrenheit
enter a value like 25 and click Invoke returns you the temperature in Fahrenheit.
For that i used below code:
url = "http://www.w3schools.com/webservices/tempconvert.asmx?op=CelsiusToFahrenheit&Celsius=25"
'Set oHttpReq = CreateObject("Microsoft.XMLHTTP") 'when i use XMLHTTP i am getting error saying "The download of the specified resource has failed."
Set oHttpReq = CreateObject("MSXML2.ServerXMLHTTP") 'If i use it, the response contains Root Element missing
oHttpReq.open "POST", url, False
oHttpReq.send
'Response
responseText = oHttpReq.responseText
WScript.echo responseText
Can anyone help me?
Create at file.vbs (visual basic script)
Compile with external tool to exe
In server task set this.
Const HOST = Sample service in IIS
Const URL = "wsPage.asmx"
Set xmlhttp = CreateObject("Microsoft.XMLHTTP")
xmlhttp.open "POST", HOST & URL & "/wsServiceTest", false
'Set the Content-Type header to the specified value
xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
' Send the request synchronously
xmlhttp.send ""
WScript.Echo "Load ok..."