User logged into remote machine - c#

Is there a way to determine what all users are logged into remote machine, using WMI and C#

After little research I was able to figure it out, although not sure if this is the best way
public void GetCompDet(string ComputerName)
{
CurrentSystem = ComputerName;
ConnectionOptions options = new ConnectionOptions();
ManagementScope moScope = new ManagementScope(#"\\" + ComputerName + #"\root\cimv2");
try
{
moScope.Connect();
}
catch
{
return;
}
ObjectQuery query = new ObjectQuery("select * from Win32_Process where name='explorer.exe'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(moScope, query);
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject m in queryCollection)
{
ManagementOperationObserver mo = new ManagementOperationObserver();
mo.ObjectReady += new ObjectReadyEventHandler(mo_ObjectReady);
m.InvokeMethod(mo, "GetOwner", null);
}
}
void mo_ObjectReady(object sender, ObjectReadyEventArgs e)
{
ManagementObject m = sender as ManagementObject;
LoggedinUser.Enqueue(CurrentSystem + " - >" + e.NewObject.Properties["user"].Value.ToString());
Console.WriteLine(CurrentSystem + " - >" + e.NewObject.Properties["user"].Value.ToString());
}

Related

Updating DNS server Resource Records with MicrosoftDNS classes (ASP.net)

I am writing an app for doing changes to DNS resource records on local server.
I wrote a function to do it:
public void UpdateDomainRecord(string domainName, string recordname, IEnumerable<JProperty> content)
{
ResourceRecord Rezults = new ResourceRecord();
string wql = "";
wql += " SELECT * ";
wql += " FROM MicrosoftDNS_ResourceRecord";
wql += " WHERE OwnerName = '" + recordname + '.' + domainName + "'";
ObjectQuery q = new ObjectQuery(wql);
ManagementObjectSearcher s = new ManagementObjectSearcher(this.Session, q);
ManagementObjectCollection col = s.Get();
int total = col.Count;
foreach (ManagementObject o in col)
{
foreach (JProperty prop in content)
{
o.SetPropertyValue(prop.Name.ToString(),prop.Value.ToString());
}
o.Put();
}
}
It seems o.Put() method does not work: the loop changed the property of ManagementObject object but changes is not saved on server.
The app has all access it needs to connect to server.
I'm not trying to change properties that can not be changed.
Do you have any ideas on why it is not working?

DateTime from Remote PC on LAN

For my application needs, I would like to get current DateTime from server PC connected with LAN. After googled, I found an MSDN Article. But it is written in vb. How can i do it in c#? Any clue?
Thanks.
I have got a solution from another answer. It's perfectly working for me.
try
{
string pc = "pcname";
//string domain = "yourdomain";
//ConnectionOptions connection = new ConnectionOptions();
//connection.Username = some username;
//connection.Password = somepassword;
//connection.Authority = "ntlmdomain:" + domain;
string wmipath = string.Format("\\\\{0}\\root\\CIMV2", pc);
//ManagementScope scope = new ManagementScope(
// string.Format("\\\\{0}\\root\\CIMV2", pc), connection);
ManagementScope scope = new ManagementScope(wmipath);
scope.Connect();
ObjectQuery query = new ObjectQuery(
"SELECT * FROM Win32_LocalTime");
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(scope, query);
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("Win32_LocalTime instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("Date: {0}-{1}-{2}", queryObj["Year"], queryObj["Month"], queryObj["Day"]);
Console.WriteLine("Time: {0}:{1}:{2}", queryObj["Hour"], queryObj["Minute"], queryObj["Second"]);
}
}
catch (ManagementException err)
{
Console.WriteLine("An error occurred while querying for WMI data: " + err.Message);
}
catch (System.UnauthorizedAccessException unauthorizedErr)
{
Console.WriteLine("Connection error (user name or password might be incorrect): " + unauthorizedErr.Message);
}

I can't get all ARecords of the Dns Zone

I programmed a project to manage Dns. I could code for create and delete Zone, NsRecord and ARecord, but I can't get ARecords of the Zone.
Can anyone guide me?
This is sample of my code:
private void CreateZone(string domainName)
{
wmiScope = new ManagementScope("\\\\" + System.Environment.MachineName + "\\ROOT\\MicrosoftDNs");
wmiScope.Connect();
var zonePath = new ManagementPath("MicrosoftDNs_Zone");
var zone = new ManagementClass(wmiScope, zonePath, null);
var inParams = zone.GetMethodParameters("CreateZone");
inParams.Properties["ZoneName"].Value = domainName;
inParams.Properties["ZoneType"].Value = 0;
zone.InvokeMethod("CreateZone", inParams, null);
var query = new ObjectQuery("SELECT * FROM MicrosoftDNs_SOAType WHERE OwnerName = '" + domainName + "'");
var searcher = new ManagementObjectSearcher(wmiScope, query);
var zoneRecordes = searcher.Get();
foreach (ManagementObject zoneRecorde in zoneRecordes)
{
var soaParams = zoneRecorde.GetMethodParameters("Modify");
soaParams.Properties["PrimaryServer"].Value = "ns1.domain.com";
soaParams.Properties["ResponsibleParty"].Value = "contact#domain.com";
zoneRecorde.InvokeMethod("Modify", soaParams, null);
}
}
To be complete I'll add the answer that got us to the solution.
According to the following site (discuss.fogcreek.com/dotnetquestions/…) you should be able to get the ARecords like this:
ManagementScope oMs = new ManagementScope("\\\\" + dnsServer + "\\root\\microsoftdns");
string strQuery = "select * from microsoftdns_" + recType + "type where containername = '" + domain + "'";
ManagementObjectSearcher oS = new ManagementObjectSearcher(strQuery); oS.Scope = oMs;
ManagementObjectCollection oRc = oS.Get();

query on Win32_NTLogEvent WHERE Logfile = 'Security' works only on remote machine

I've have a problem using the code below to retrieve data from the security log event of my local machine. I tested on various computers: the local machine is a windows xp sp3. The query has no error but it returns 0 record. For remote machines it works perfectly
Anyone can give me a solution?
This is the code:
using System;
using System.Management;
using System.Windows.Forms;
namespace WMISample
{
public class MyWMIQuery
{
public static void Main()
{
try
{
string[] arrComputers = {".","clientN"};
foreach (string strComputer in arrComputers)
{
Console.WriteLine("==========================================");
Console.WriteLine("Computer: " + strComputer);
Console.WriteLine("==========================================");
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(
"\\\\" + strComputer + "\\root\\CIMV2",
"SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'Security'");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("Win32_NTLogEvent instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("RecordNumber: {0}", queryObj["RecordNumber"]);
Console.WriteLine("SourceName: {0}", queryObj["SourceName"]);
Console.WriteLine("TimeGenerated: {0}", queryObj["TimeGenerated"]);
}
}
}
catch(ManagementException err)
{
MessageBox.Show("An error occurred while querying for WMI data: " + err.Message);
}
}
}
}
I understood that using the impersonation level for the wmi query in vbs it works.
Set objWMI = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate,(Security)}!\\" _
& strComputer & "\root\cimv2")
Set colLoggedEvents = objWMI.ExecQuery _
("Select * from Win32_NTLogEvent Where Logfile = 'Security'" )
So I have to translate in c#.
Ok so I close this Question using my code.
the code is:
using System;
using System.Management;
namespace WMISample
{
public class MyWMIQuery
{
public static void Main()
{
try
{
ConnectionOptions oConn = new ConnectionOptions();
oConn.Impersonation = ImpersonationLevel.Impersonate;
oConn.EnablePrivileges = true;
string[] arrComputers = {".","clientN"};
foreach (string strComputer in arrComputers)
{
Console.WriteLine("==========================================");
Console.WriteLine("Computer: " + strComputer);
Console.WriteLine("==========================================");
ManagementObjectSearcher searcher = new ManagementObjectSearcher
(
new ManagementScope("\\\\" + strComputer + "\\root\\CIMV2", oConn),
new ObjectQuery( #"SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'Security'")
);
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("Win32_NTLogEvent instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("RecordNumber: {0}", queryObj["RecordNumber"]);
Console.WriteLine("SourceName: {0}", queryObj["SourceName"]);
Console.WriteLine("TimeGenerated: {0}", queryObj["TimeGenerated"]);
}
}
}
catch(ManagementException err)
{
MessageBox.Show("An error occurred while querying for WMI data: " + err.Message);
}
}
}
}
try using the local computername instead of ".". so, instead of
string[] arrComputers = {".","clientN"};
you would have
string[] arrComputers = { Environment.GetEnvironmentVariable("computername"), "clientN" };

How to get username of process running in task manager?

I want to know the user that created each process.
How do I get the usernames of all the processes running in task manager using c#?
Look into Win32_Process Class, and GetOwner Method
Sample Code
Sample code
public string GetProcessOwner(int processId)
{
string query = "Select * From Win32_Process Where ProcessID = " + processId;
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection processList = searcher.Get();
foreach (ManagementObject obj in processList)
{
string[] argList = new string[] { string.Empty, string.Empty };
int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
if (returnVal == 0)
{
// return DOMAIN\user
return argList[1] + "\\" + argList[0];
}
}
return "NO OWNER";
}

Categories

Resources