I'm trying to get status of a remote windows service. I use code like this, but nothing happens. Labels have not get any value. Help my please!
ConnectionOptions options = new ConnectionOptions();
options.Password = "password";
options.Username = "username";
options.Impersonation = System.Management.ImpersonationLevel.Impersonate;
ManagementScope scope = new ManagementScope("\\\\computer_name\\root\\cimv2", options);
scope.Connect();
ServiceController sc = new ServiceController("service_name", "computer_name");
label1.Text = sc.ServiceName;
label2.Text = sc.Status.ToString();
Related
When I try to execute the below code, I get the error - RPC server is unavailable.
string username = "****";
string password = "****";
server = comboBox1.SelectedItem.ToString();
service = "****";
ServiceController windowsservice = new ServiceController(service, server);
try
{
ConnectionOptions connectopt = new ConnectionOptions();
connectopt.Username = username;
connectopt.Password = password;
connectopt.EnablePrivileges = true;
connectopt.Impersonation = ImpersonationLevel.Impersonate;
ManagementScope scope = new ManagementScope(#"\\'"+server+"'\\root\\cimv2", connectopt);
scope.Connect();
}
But when I hardcode the value of server name in the line
ManagementScope scope = new ManagementScope(#"\\'"+server+"'\\root\\cimv2", connectopt);
it works fine with no errors
Any help would be much appreciated
This code works fine when opening two other VMs but gives me an RPC error on
opening a computer on a different domain. At the moment I am using the ConnectionOptions class to connect to the remote computer
`options.Username = dif_users[i]; // Assume correct user name
options.Password = dif_passwords[i]; // Assume correct password
if (i == 2) // To execute for the third VM. (i = 0 in the beginning)
{
//
options.Authentication = AuthenticationLevel.Packet;
options.Impersonation = ImpersonationLevel.Impersonate;
options.EnablePrivileges = true;
options.Authority = "ntlmdomain:DIFFERENT_DOMAIN";
}
ManagementScope scope = new ManagementScope("\\\\" + comps + "\\root\\cimv2", options);
scope.Connect(); // RPC server is unavaialaible
`
I can start or stop service remotely from .net project.
ConnectionOptions options = new ConnectionOptions();
options.Username = #"192.168.36.22\test";
options.Password = "test";
ManagementScope scope = new ManagementScope(#"\\192.168.36.22\root\cimv2", options);
scope.Connect();
ManagementOperationObserver Stop = new ManagementOperationObserver();
Stop.Completed += new CompletedEventHandler(Stop_CallBack);
try
{
string NameServices = "ArcGIS Server";
WqlObjectQuery query = new WqlObjectQuery("SELECT * FROM Win32_Service WHERE Name=\"" + NameServices + "\"");
ManagementObjectSearcher find = new ManagementObjectSearcher(scope, query);
foreach (ManagementObject spooler in find.Get())
{
spooler.InvokeMethod("StopService", new object[] { });
spooler.InvokeMethod(Start, "StopService", new object[] { });
}
}
....
How can I restart this service?
You could use the ServiceController class like so:
ServiceController sc = new ServiceController("ArcGIS Server", "192.168.36.22");
sc.Start();
sc.Stop();
This saves you having to write all that code to interact with WMI. Note to use the ServiceController class, you'll have to add a reference to the System.ServiceProcess assembly.
Service controller didn't work for me, so I used Cmd to do it.
Process.Start("CMD.exe", "/C sc \\\\remoteMachine stop \"serviceName\"&sc \\\\remoteMachine start \"serviceName\"");
To overcome credentials issue, I used class from this https://stackoverflow.com/a/5433640/2179222 answer.
So in the end It looked like this:
private static void RestartService(string remoteMachine, string serviceName, string userName, string password)
{
using (new NetworkConnection($"\\\\{remoteMachine}", new NetworkCredential(userName, password)))
{
Process.Start("CMD.exe", $"/C sc \\\\{remoteMachine} stop \"{serviceName}\"&sc \\\\{remoteMachine} start \"{serviceName}\"");
}
}
I have come across a similar problem when I tried to connect, just add your machine name as admin in the 'users' group of the target machine and you will be able to fetch the data.
ConnectionOptions connOptions = new ConnectionOptions();
connOptions.Username = _username;
connOptions.Password = _password;
connOptions.Impersonation = ImpersonationLevel.Impersonate;
connOptions.Authentication = AuthenticationLevel.PacketPrivacy;
connOptions.EnablePrivileges = true;
ManagementScope manScope = new ManagementScope(_server, connOptions);
manScope.Connect();
ObjectGetOptions objectGetOptions = new ObjectGetOptions();
ManagementPath managementPath = new ManagementPath("Win32_ScheduledJob");
ManagementClass processClass = new ManagementClass(manScope, managementPath, objectGetOptions);
ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
inParams["Name"] = "TESTER";
inParams["Owner"] = "Tester";
inParams["Command"] = command;
inParams["StartTime"] = "********171000.000000-300";
I'm tyring to connect to a remote system to create a scheduled task. I can create the scheduled tasks, but its being created with user - SYSTEM. I want it to be created under my user. I tried using the properties like 'Owner' and 'Name' eg:
inParams["Owner"] = ;
inParams["Name"] = ;
But they throw a ManagementException, "Not Found". Does anyone know how I can do this, or what might be wrong that I'm doing here...
Thanks
Creating a scheduled job with the Win32_ScheduledJob WMI class is equivalent to create job using the AT command. The AT service normally run under the Local\System account or the NetworkService Account. so when you uses this class your jobs are created using one of these accounts for more info about this topic you can check the remarks part of the MSDN documentation.
I have searched through numerous questions about how to convert VBS to C# and all that good stuff.
The issue that I'm having is that with the VBS code (see below) when the process is executed on the remote machine it's run with the SYSTEM account.
When I execute with C# it's run with my credentials (or whomever runs the C# program).
The VBS seems to be more reliable in getting remote installs to go through which is what i need it for.
I wanted to switch to C# so I could make a more user friendly GUI for the program.
Anyone know how to get C# to run WMI with the SYSTEM account?
VBS Code:
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set objScheduledJob = objWMIService.Get("Win32_ScheduledJob")
Set objSWbemDateTime = CreateObject("WbemScripting.SWbemDateTime")
'add the scheduled job to be run
objSWbemDateTime.SetVarDate(DateAdd(INTERVAL, MINUTES, Now()))
errReturn = objScheduledJob.Create(strCommand, objSWbemDateTime.Value, False, 0, 0, True, intJobID)
C# code:
static public int RemoteAdmin(string remoteMachine, string runFile)
{
try
{
ManagementPath run = new ManagementPath(#"\\" + remoteMachine + #"\root\cimv2:Win32_process");
ManagementClass man = new ManagementClass(run);
man.InvokeMethod("Create", new Object[] { runFile });
return 0;
}
catch
{
MessageBox.Show("Error in remote execution");
return 1;
}
}
You need to setup the ConnectionOptions
ConnectionOptions wmiConnOpts = new ConnectionOptions();
wmiConnOpts.Impersonation = ImpersonationLevel.Impersonate;
wmiConnOpts.Authentication = System.Management.AuthenticationLevel.Default;
wmiConnOpts.EnablePrivileges = true;
ManagementScope wmiLoc =
new ManagementScope(String.Format(#"\\{0}\root\cimv2", remoteMachine ),
wmiConnOpts);
ManagementPath wmiProcPath = new ManagementPath("Win32_ScheduledJob");
ManagementClass wmiProc = new ManagementClass(wmiLoc, wmiProcPath, null);
wmiProc.InvokeMethod("Create", new Object[] { runFile });
This is probably idiot error on my part but the error I was getting was because I didn't specify a time (UTC format) for it to start the scheduled job
ConnectionOptions connOptions = new ConnectionOptions();
connOptions.Impersonation = ImpersonationLevel.Impersonate;
connOptions.Authentication = AuthenticationLevel.PacketPrivacy;
connOptions.EnablePrivileges = true;
ManagementScope manScope = new ManagementScope(String.Format(#"\\" + remoteMachine + #"\ROOT\CIMV2"), connOptions);
manScope.Connect();
ObjectGetOptions objectGetOptions = new ObjectGetOptions();
ManagementPath managementPath = new ManagementPath("Win32_ScheduledJob");
ManagementClass processClass = new ManagementClass(manScope, managementPath, objectGetOptions);
ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
inParams["Command"] = runFile;
string StartTime = DateTimetoUTC(DateTime.Now.AddMinutes(1));
inParams["StartTime"] = StartTime;
ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);