Query services remotely using WMI - c#

I want to get status of services on remote server (Windows 2008 R2). I am using domain account. My problem is that instead of 150+ services, I am getting only 34.
Here is my code:
var connection = new ConnectionOptions
{
Username = $"{domain}\\{userName}",
Password = password,
};
var scope = new ManagementScope(#"\\{ip}\root\cimv2", connection);
var query = new ObjectQuery(importConfig.Query);
var searcher = new ManagementObjectSearcher(scope, "SELECT * FROM Win32_Service");
var result = searcher.Get()
When I add my domain account do Administrators on this server, I am getting valid response - 150+ services.
I also tried to set (I tried AU, SID and many other combinations):
sc sdset SCMANAGER D:(A;;CCLCRPRC;;;AU)(A;;CCLCRPWPRC;;;SY)(A;;KA;;;BA)S:(AU;FA;KA;;;WD)(AU;OIIOFA;GA;;;WD)
but the result is the same - 34 services are returned when domain account is not in Admins. Any idea why I don't see other services?

Related

I cannot connect to a remote PC with WinXP OS with CimSession. I get Error "Microsoft.Management.Infrastructure.CimException:..."

In my application I have to connect to remote PC's mostly with WinXP OS (Older production machines) from my office server. I am starting a CIMSession in order to read the CPU Load of the remote PC. If I use following code I get Error:
"Microsoft.Management.Infrastructure.CimException: The client cannot connect to the destination specified in the request. Verify that the service on the destination is running and is accepting requests. Consult the logs and documentation for the WS-Management service running on the destination, most commonly IIS or WinRM. If the destination is the WinRM service, run the following command on the destination to analyze and configure the WinRM service: "winrm quickconfig" "
The remote IP is added into the TrustedHosts list on the server where my app is running
public void Read_CPU_Load()
{
string Namespace = #"root\cimv2";
string OSQuery = "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor where Name='_Total'";
string domain = "";
string username = "xxxxxx";
var s = new SecureString();
s.AppendChar('P');
s.AppendChar('a');
s.AppendChar('s');
s.AppendChar('s');
s.AppendChar('w');
s.AppendChar('o');
s.AppendChar('r');
s.AppendChar('d');
// create Credentials
CimCredential Credentials = new CimCredential(PasswordAuthenticationMechanism.Default,
domain,
username,
s);
// create SessionOptions using Credentials
WSManSessionOptions SessionOptions = new WSManSessionOptions();
SessionOptions.AddDestinationCredentials(Credentials);
// create Session using computer, SessionOptions
CimSession mySession = CimSession.Create(TagService.IP_to_Connect, SessionOptions);
IEnumerable<CimInstance> queryInstance = mySession.QueryInstances(Namespace, "WQL", OSQuery);
foreach (CimInstance process in queryInstance)
{
CPU_Load_WMI_int = Convert.ToInt16(process.CimInstanceProperties["PercentProcessorTime"]);
}
}

From where PrincipalContext gets the connected server name?

I have a web application with windows authentication. When I debug the line
var domainContext = new PrincipalContext(ContextType.Domain, "abc");
where "abc" is domain name.
I can see the connected server as domain controller name. I would like to know from where it is getting the DC name.
Actually, the issue is, even though a particular DC is demoted and new DC is added, our application always pointing to the same demoted DC and throws error when we try to get groups of the user using the below lines.
var user = UserPrincipal.FindByIdentity(domainContext, "username");
var groups = user.GetGroups();
[ActiveDirectoryServerDownException: The server is not operational.
Name: "DomainController.Domain.com"
]
System.DirectoryServices.ActiveDirectory.PropertyManager.GetPropertyValue(DirectoryContext
context, DirectoryEntry directoryEntry, String propertyName) +510
System.DirectoryServices.ActiveDirectory.DirectoryEntryManager.ExpandWellKnownDN(WellKnownDN
dn) +239
System.DirectoryServices.ActiveDirectory.DomainController.get_Domain()
+71
System.DirectoryServices.AccountManagement.ADStoreCtx.GetGroupsMemberOf(Principal
p) +839
System.DirectoryServices.AccountManagement.Principal.GetGroups() +32
Do I need to clear IIS cache or some other cache? I have restarted the IIS too.
You can retrieve the DC name programmatically if your server belongs to domain controller.
using (var context = new System.DirectoryServices.AccountManagement.PrincipalContext(ContextType.Domain))
{
server = context.ConnectedServer;
//Output : dc.example.com
var formatted = server.Split('.').Select(s => String.Format("DC={0}", s));
joined = String.Join(",", formatted);
// Output DC=dc,DC=example,DC=com
}
If the server isn't a part of the domain controller. You can retrieve it by using credentials like this;
System.DirectoryServices.ActiveDirectory.DirectoryContext domainContext = new DirectoryContext(DirectoryContextType.Domain, "domainName", "domainUser", "Password");
var domain = ActiveDirectory.Domain.GetDomain(domainContext);
var controller = domain.FindDomainController();

Connecting to oracle database with proxy address

So I'm trying to connect to an Oracle database using the Oracle.ManagedDataAccess-library, where I'm using the following datasource:
(DESCRIPTION =(SOURCE_ROUTE = YES)
(ADDRESS_LIST=
(ADDRESS = (PROTOCOL = TCP)(Host = PROXY-OracleConnectionManager)(Port = 1111))
(ADDRESS = (PROTOCOL = TCP) (Host = MAIN-DATABASE) (Port = 0000)))
(connect_data= (UR = A)(SERVICE_NAME = SERVICENAME)))
I'm also providing a user id and password.
We don't have any control over the database on our end, but as far as I know, they are using a connection manager as the first address, which should route us to the next address in the list if we are authenticated. This works when using this in Oracle SQL Developer but does not work programatically with Oracle.ManagedDataAccess.
This is how I build and use the connection string:
var connString = new OracleConnectionStringBuilder
{
{"User Id", settings.DbUserId},
{"Password", settings.DbUserPassword},
{"Data Source", settings.DbDataSource}
};
OracleConnection conn = new OracleConnection(connectionString.ToString())
conn.Open()
When I run this, I get the following error:
ORA-12537: Network Session: End of file
I suspect that the issue is the ADDRESS_LIST and that the routing doesn't work, but I can't say for sure. Anyone able to provide some insight?

Error when calling any method on Service Management API

I'm looking to start an Azure runbook from a c# application which will be hosted on an Azure web app.
I'm using certificate authentication (in an attempt just to test that I can connect and retrieve some data)
Here's my code so far:
var cert = ConfigurationManager.AppSettings["mgmtCertificate"];
var creds = new Microsoft.Azure.CertificateCloudCredentials("<my-sub-id>",
new X509Certificate2(Convert.FromBase64String(cert)));
var client = new Microsoft.Azure.Management.Automation.AutomationManagementClient(creds, new Uri("https://management.core.windows.net/"));
var content = client.Runbooks.List("<resource-group-id>", "<automation-account-name>");
Every time I run this, no matter what certificate I use I get the same error:
An unhandled exception of type 'Hyak.Common.CloudException' occurred in Microsoft.Threading.Tasks.dll
Additional information: ForbiddenError: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription.
I've tried downloading the settings file which contains the automatically generated management certificate you get when you spin up the Azure account... nothing I do will let me talk to any of the Azure subscription
Am I missing something fundamental here?
Edit: some additional info...
So I decided to create an application and use the JWT authentication method.
I've added an application, given the application permissions to the Azure Service Management API and ensured the user is a co-administrator and I still get the same error, even with the token...
const string tenantId = "xx";
const string clientId = "xx";
var context = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantId));
var user = "<user>";
var pwd = "<pass>";
var userCred = new UserCredential(user, pwd);
var result = context.AcquireToken("https://management.core.windows.net/", clientId, userCred);
var token = result.CreateAuthorizationHeader().Substring("Bearer ".Length); // Token comes back fine and I can inspect and see that it's valid for 1 hour - all looks ok...
var sub = "<subscription-id>";
var creds = new TokenCloudCredentials(sub, token);
var client = new AutomationManagementClient(creds, new Uri("https://management.core.windows.net/"));
var content = client.Runbooks.List("<resource-group>", "<automation-id>");
I've also tried using other Azure libs (like auth, datacentre etc) and I get the same error:
ForbiddenError: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription.
I'm sure it's just 1 tickbox I need to tick buried somewhere in that monolithic Management Portal but I've followed a few tutorials on how to do this and they all end up with this error...
public async Task StartAzureRunbook()
{
try
{
var subscriptionId = "azure subscription Id";
string base64cer = "****long string here****"; //taken from http://stackoverflow.com/questions/24999518/azure-api-the-server-failed-to-authenticate-the-request
var cert = new X509Certificate2(Convert.FromBase64String(base64cer));
var client = new Microsoft.Azure.Management.Automation.AutomationManagementClient(new CertificateCloudCredentials(subscriptionId, cert));
var ct = new CancellationToken();
var content = await client.Runbooks.ListByNameAsync("MyAutomationAccountName", "MyRunbookName", ct);
var firstOrDefault = content?.Runbooks.FirstOrDefault();
if (firstOrDefault != null)
{
var operation = client.Runbooks.Start("MyAutomationAccountName", new RunbookStartParameters(firstOrDefault.Id));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Also in portal:
1) Application is multitenant
2) Permissions to other applications section - Windows Azure Service Manager - Delegated permissions "Access Azure Service Management(preview)"
Ensure that your Management certificate has private key and was not made from the .CER file. The fact that you're not supplying a password when generating the X509Certificate object makes me think you're using public key only
Ensure that your Managemnet's certificate public key (.CER file) has been uploaded to the Azure management portal (legacy version, Management Certificate area)
Use CertificateCloudCredentials and not any other credential type of an object
Ok, stupid really but one of the tutorials I followed suggested installing the prerelease version of the libs.
Installing the preview (0.15.2-preview) has fixed the issue!

How to create a new server using OpenStack.NET

I am new to OpenStack, just a few hours experience. I want to create a new machine using OpenStack.NET and this is the code that I come up with.
var identityUrl = "http://server:5000/v2.0";
var imageUrl = "http://server:9292";
var username = "username";
var password = "password";
var cloudId = new CloudIdentity() { Username = username, Password = password };
var cloudIdProvider = new CloudIdentityProvider(new Uri(identityUrl));
cloudIdProvider.Authenticate(cloudId);
var cloudServersProvider = new CloudServersProvider(cloudId, cloudIdProvider);
var newServer = cloudServersProvider.CreateServer("cloudServerName", "Windows Server 2012", "m1.medium");
identityUrl is the url for identity service
imageUrl is the url for image service
I can authenticate on cloudIdProvider.Authenticate(cloudId); line so I think the identity service and username/password are correct.
When I debug on cloudServersProvider.CreateServer("cloudServerName", "Windows Server 2012", "m1.medium");, it throws No region was provided, the service does not provide a region-independent endpoint, and there is no default region set for the user's account. exception which I don't know how to fix it.
The Identity Service is likely failing to include information about the Compute Service endpoint, because you did not specify the tenantName and/or tenantId during authentication. The next release of the SDK will include support for specifying these as described in the preview build of the OpenStack Authentication documentation. However, since the described classes do not exist in the 1.3.1.0 release, you'll need to include a copy of them in your project until 1.3.2.0 is released.
CloudIdentityWithProject.cs
OpenStackIdentityProvider.cs
ProjectId.cs

Categories

Resources