Detect Antivirus on Windows using C#
This link tells whether antivirus is installed in the system or not ? Can we code in such a way that we fetch the name of the antivirus installed too?
You need to access wmi displayName property for each antivirus instance. Use ManagementBaseObject.Properties
string wmipathstr = #"\\" + Environment.MachineName + #"\root\SecurityCenter2";
var searcher = new ManagementObjectSearcher(wmipathstr, "SELECT * FROM AntivirusProduct");
var instances = searcher.Get();
foreach (var instance in instances)
{
Console.WriteLine(instance.GetPropertyValue("displayName"));
}
Related
I want to open process pon remote machine, this remote machine is inside local network.
I try this command and in the remote machine nothing happen, this user that i connect with have administrators rights.
Both machines running Windows 7
static void Main(string[] args)
{
try
{
//Assign the name of the process you want to kill on the remote machine
string processName = "notepad.exe";
//Assign the user name and password of the account to ConnectionOptions object
//which have administrative privilege on the remote machine.
ConnectionOptions connectoptions = new ConnectionOptions();
connectoptions.Username = #"MyDomain\MyUser";
connectoptions.Password = "12345678";
//IP Address of the remote machine
string ipAddress = "192.168.0.100";
ManagementScope scope = new ManagementScope(#"\\" + ipAddress + #"\root\cimv2", connectoptions);
//Define the WMI query to be executed on the remote machine
SelectQuery query = new SelectQuery("select * from Win32_process where name = '" + processName + "'");
object[] methodArgs = { "notepad.exe", null, null, 0 };
using (ManagementObjectSearcher searcher = new
ManagementObjectSearcher(scope, query))
{
foreach (ManagementObject process in searcher.Get())
{
//process.InvokeMethod("Terminate", null);
process.InvokeMethod("Create", methodArgs);
}
}
Console.ReadLine();
}
catch (Exception ex)
{
//Log exception in exception log.
//Logger.WriteEntry(ex.StackTrace);
Console.WriteLine(ex.StackTrace);
}
}
you are not opening a process with that code but you are enumerating all the running process named "iexplore.exe" and close them.
I think an easier, better way is to use SysInternals PsExec or the Task Scheduler API
If you want to use WMI your code should look like this:
object theProcessToRun = { "YourFileHere" };
ManagementClass theClass = new ManagementClass(#"\\server\root\cimv2:Win32_Process");
theClass.InvokeMethod("Create", theProcessToRun);
----------In reply to your comment------------------
First of all you need to change your attitude and approach to coding and read the code that your are copy/pasting.
Then you should study a little more about programming languages.
No I will not write the code for you. I gave you an hint to point to the right direction. now it is your turn to develop it. Have fun!!
This is script that i did for my company before this using vbs script. can search the net to convert it to C# or etc. Fundamental of the steps and how to start a service using WMI. Have a nice coding and have fun.
sUser = "TESTDomain\T-CL-S"
sPass = "Temp1234"
Set ServiceSet = GetObject("winmgmts:").ExecQuery("Select * from Win32_Service where Name = 'netlogon'")
For Each Service In ServiceSet
Service.StopService
Service.Change "netlogon",Service.PathName, , ,"Automatic",false,sUser,sPass
Service.StartService
Next
Set Service = Nothing
Set ServiceSet = Nothing
We have 6 Citrix Servers. I'm trying to find out if Remote Logons are enabled/disabled.
I plan to put this onto of a webpage to display and green icon if they are or red if they aren't.
I've managed to connect to the machines and pull operating system information etc.. However when i try and connect to view the TerminalServiceSetting information.. i get an Invalid Class error.
Here is my code.
ManagementScope scope = new ManagementScope("\\\\MACHINENAME\\ROOT\\cimv2");
scope.Connect();
//create object query
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_TerminalServiceSetting");
//create object searcher
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(scope, query);
//get collection of WMI objects
ManagementObjectCollection queryCollection = searcher.Get();
//enumerate the collection.
foreach (ManagementObject m in queryCollection)
{
// access properties of the WMI object
Label1.Text = m["AllowTSConnections"].ToString();
}
If anyone can shed some light on it that would be great.
Thanks
Update:
I have now found the code (i think) that checks to see if remote connections are enabled or disabled.
ManagementScope scope =
new ManagementScope("\\\\MACHINENAME\\root\\CIMV2\\TerminalServices",con);
scope.Options.EnablePrivileges = true;
scope.Options.Authentication = AuthenticationLevel.PacketPrivacy;
scope.Options.Impersonation = ImpersonationLevel.Impersonate;
scope.Connect();
//create object query
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_TerminalServiceSetting");
//create object searcher
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(scope, query);
//get collection of WMI objects
ManagementObjectCollection queryCollection = searcher.Get();
//enumerate the collection.
foreach (ManagementObject m in queryCollection)
{
if (m["AllowTSConnections"].ToString() == "1")
{
Redicon.Visible = false;
}
else
{
Greenicon.Visible = false;
}
}
However when i run the code i get returned "1".. which is fine. However if i deny remote logins on the server and re run the code it stays at 1..
Any ideas?
You need to be sure that the server provide the TerminalServiceSetting information. WMI uses unmanaged code because not all servers and their configurations provide all information.
You can use Mgmtclassgen to generate managed code and at the same time make sure that the server provides the information.
Sorted!!!
I was looking up the wrong field.
the correct one is :
Label1.Text = "Remote Connections: " + m["Logons"].ToString();
I want to get id processor in .NET with WMI but when I'm using the get() method from the ManagementObjectSearcher, I'm getting an out of memory exception ...
If you want to take a look from the code see below :
ManagementObjectSearcher searcher = new ManagementObjectSearcher(
"select * from Win32_Processor");
foreach (ManagementObject share in searcher.Get())
foreach (PropertyData PC in share.Properties)
if (PC.Name.Equals("ProcessorId"))
return (string)PC.Value;
return null;
This code works on others computers but not on mine ...
I'm using windows 7.
What is the problem ?
I tried to restart WMI service and that not resolve my problem :(
There are several reasons which could cause out of memory exception.
possible memory leak in WMI, source:
http://brooke.blogs.sqlsentry.net/2010/02/win32service-memory-leak.html
check whether you have permission(s), that would explain why does your code work on some computers and why doesn't on yours.
run your code as Administrator (for debugging start VS as Administrator)
Here is an other code snippet, try this one as well... who knows
Sample:
public static String GetCPUId()
{
String processorID = "";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(
"Select * FROM WIN32_Processor");
ManagementObjectCollection mObject = searcher.Get();
foreach (ManagementObject obj in mObject)
{
processorID = obj["ProcessorId"].ToString();
}
return processorID;
}
Source: WIN32_Processor::Is ProcessorId Unique for all computers
I use mgmtclassgen.exe and get wrapper(DataFile.cs) class for CIM_DataFile wmi class. Code below works perfect on localhost (without filling credentionals), but when I connect to remote machine variable returnResult=9 (Invalid object). But size of variable dataFileCollection=1
var _connectionOptions = new ConnectionOptions();
_connectionOptions.Username = "username";
_connectionOptions.Password = "password";
_connectionOptions.Authority = String.Format("ntlmdomain:{0}", "DOMAIN");
var _managementScope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2",
"RemotePCName"), _connectionOptions);
var dataFileCollection = DataFile.GetInstances(_managementScope,
#"Name = 'C:\\Windows\\System32\\mapisvc.inf'";
var tempFilePath = "c:\\temp.txt");
if (dataFileCollection.Count > 0)
{
foreach (var dataFile in dataFileCollection.Cast<DataFile>())
{
var returnResult = dataFile.Copy(tempFilePath);
if (File.Exists(tempFilePath))
{
List<string> lines = File.ReadAllLines(tempFilePath).ToList();
File.Delete(tempFilePath);
}
}
}
try adjusting your management scope differently
Maybe you could try it like:
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(
"\\\\" + strComputer + "\\root\\CIMV2",
"SELECT * FROM Win32_PerfFormattedData_MSSQLSERVER_SQLServerDatabases");
where strComputer is the name of the remote pc and Win32_Perf... the class you're trying to query. This works for me, as it is in a local network, though I am not certain where your remote machine is located.
You could as well to go http://www.microsoft.com/en-us/download/details.aspx?id=8572 which is a WMI-query generator by Microsoft. This allows you to generate query's in either C#, VB, and VB scripts. While setting the connection properties.
Might be worth a shot.
I can create a new zone, add and delete records for that zone, all relatively easily using WMI and System.Management, but for the life of me can't figure out how to delete a zone. It doesn't appear to be a method in the WMI Documentation:
http://msdn.microsoft.com/en-us/library/ms682123(VS.85).aspx
Any thoughts on how to do this? Trying to keep the DNS server clean when we remove old website customers, but I can only get as good as deleting all the records in a zone.
EDIT: This is on a windows server 2008 R2 machine. And I would be ok with an answer of "don't use WMI" if there is an alternate solution I can execute from a remote machine and code in c#
You can delete zones in the same manner you would a record.
internal static bool DeleteZoneFromDns(string ZoneName)
{
try
{
string Query = "SELECT * FROM MicrosoftDNS_Zone WHERE ContainerName = '" + ZoneName + "'";
ObjectQuery qry = new ObjectQuery(Query);
DnsProvider dns = new DnsProvider();
ManagementObjectSearcher s = new ManagementObjectSearcher(dns.Session, qry);
ManagementObjectCollection col = s.Get();
dns.Dispose();
foreach (ManagementObject obj in col)
{
obj.Delete();
}
return true;
}
catch (Exception)
{
return false;
}
}