Using C# how can I release and renew my DHCP-based IP Address?
At the moment I am using the process method to use these DOS commands:
ipconfig /release
and
ipconfig /renew
Is there a more managed approach in C# for this?
You could use WMI, but its much simpler to just do it using System.Diagnostics.Process
Here is a WMI solution anyway:
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
//Need to determine which adapter here with some kind of if() statement
objMO.InvokeMethod("ReleaseDHCPLease", null, null);
objMO.InvokeMethod("RenewDHCPLease", null, null);
}
You can try something like this:
SelectQuery query = new SelectQuery("Win32_NetworkAdapter", "AdapterTypeID=0");
ManagementObjectSearcher search = new ManagementObjectSearcher(query);
foreach (ManagementObject result in search.Get())
{
NetworkAdapter adapter = new NetworkAdapter(result);
adapter.Disable();
}
Not that your process must have elevated privileges.
Hope it helps.
Related
I am trying to connect (locally) to get a list of virtual machines and their properties. I have hacked some code I found, but my code is failing to connect so I can only assume that the connection string is wrong.
Using Server 2012, Hyper-V
private void listVirtualMachines() {
ManagementScope manScope = new ManagementScope(#"\\LOCALHOST\root\cimv2");
if (manScope.IsConnected) {
ObjectQuery queryObj = new ObjectQuery("SELECT * FROM Msvm_ComputerSystem");
// connect and set up our search
ManagementObjectSearcher vmSearcher = new ManagementObjectSearcher(manScope, queryObj);
ManagementObjectCollection vmCollection = vmSearcher.Get();
// loop through the machines
foreach (ManagementObject vm in vmCollection) {
// display VM details
LogString(vm["ElementName"].ToString());
LogString(vm["EnabledState"].ToString());
LogString(vm["Description"].ToString());
}
} else {
//WE END UP HERE EVERY TIME!
LogString("Cannot Connect to ManagementScope!");
}
} //funct
In Server 2012, Msvm_ComputerSystem is in the WMI namespace root\virtualization\v2 so the code should be:
ManagementScope manScope = new ManagementScope(#"\\.\root\virtualization\v2");
manScope.Connect();
How can I disable/enable an internet connection? Just want to disable internet connection only not LAN.
I tried this but it is not working
string[] connections = DisconnectWrapper.Connections();
for (int i = 0; i < connections.Length; i++)
{
try
{
DisconnectWrapper.CloseConnection(connections[i]);
}
catch (Exception ex)
{ }
}
You can use WMI.
Add System.Management to your referenced and try this code
SelectQuery wmiQuery = new SelectQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionId != NULL");
ManagementObjectSearcher searchProcedure = new ManagementObjectSearcher(wmiQuery);
foreach (ManagementObject item in searchProcedure.Get())
{
if (((string)item["NetConnectionId"]) == "Local Network Connection")
{
item.InvokeMethod("Disable", null);
}
}
There is another article:Disable/Enable Network Connections Programmatically.
with WMI you can disable and enable all network connections.
Edited:
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(#"select * from Win32_NetworkAdapter"))
{
ManagementObjectCollection results = searcher.Get();
foreach (ManagementObject obj in results)
{
System.Console.WriteLine("Found adapter {0} :", obj["Caption"]);
System.Console.WriteLine("Disabling adapter ...");
object[] param = new object[0];
obj.InvokeMethod("Disable",param);
System.Console.WriteLine("Done.");
}
Console.ReadLine();
}
Be aware Some of the adapter cannot be disabled.
You can do what you need by doing a shell call to netsh.
Example:
netsh interface set interface "Target Adapter Name" enabled
netsh interface set interface "Target Adapter Name" disabled
Netsh will block so if you wait for the process you spawn to exit, you'll know it's done. It requires administrator privileges, so your process will also require it. Netsh will set its exit code to 0 on success or 1 on failure, so you can check that for feedback if needed.
I am trying to shutdown and start the sql server on a remote computer (on the same network), i have used this code
ConnectionOptions options = new ConnectionOptions();
options.Username = userName;
options.Password = password;
ManagementScope scope =
new ManagementScope(
string.Format(#"\\{0}\root\cimv2", serverFullName),
options);
scope.Connect();
ObjectQuery query = new ObjectQuery(
string.Format(#"SELECT * FROM Win32_Process WHERE Name='{0}'",
processToTerminate));
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject m in queryCollection)
{
m.InvokeMethod("Terminate", null);
}
is there another way of doing that ?
how can i start the process (if Terminate close it)?
Thank you
What about using the ServiceController class? (see MSDN)
// just replace the params with your values
ServiceController sc = new ServiceController("SERVICENAME", "MACHINENAME");
if (sc.Status.Equals(ServiceControllerStatus.Running))
sc.Stop();
This should do the trick.
hth
It would seem a lot easier to just use the ServiceController class, that you can give a service name and computer name to, and then call methods such as Start and Stop.
Killing a process and stoping a service are two different things. A service could spawn other processes that will remain lingering. Also, you are effectively pulling the plug on the process. It isn't being given any time to stop gracefully, write everything to disk, etc.
Instead you should use the Win32_Service WMI object to find your service. This has a StartService and StopService method, which will allow you to stop and start it as you need.
Mind you, this WMI object is about services, not processes, so you will have to tweak your code to stop it by the service name, not the process name. Something like this:
ConnectionOptions options = new ConnectionOptions();
options.Username = userName;
options.Password = password;
ManagementScope scope = new ManagementScope(string.Format(#"\\{0}\root\cimv2", serverFullName), options);
scope.Connect();
ObjectQuery query = new ObjectQuery(string.Format(#"SELECT * FROM Win32_Service WHERE Name='{0}'",serviceToStop));
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject m in queryCollection)
{
m.InvokeMethod("StopService", null);
}
Then later on you can use InvokeMethod on StartService.
you can do some like this to start and stop your sql server
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "net start \"Sql Server (SQLEXPRESS)\"";
process.Start();
How am I able do find all local printers of the machine where the program is running with a user that doesn't have admin rights. I need to remap the printer IP and set the printer as default. My idea is to use impersonation to do this but I don't know where to find the printer and if it is a good solution to use impersonation.
Thanks for any help!
I don't think you will have any luck with this. Impersonation will not work here and just throw a exception. You can try this by making a impersonation and try to open Environment.Domain it should give you a exception.
You can try something like this without impersonation:
ManagementScope mscope = new ManagementScope(#"\root\CIMV2", options);
mscope.Connect();
System.Management.ObjectQuery oQuery = new ObjectQuery("Select * from Win32_TCPIPPrinterPort");
System.Management.ManagementObjectSearcher searcher = new ManagementObjectSearcher(mscope, oQuery);
ManagementObjectCollection moCollection = searcher.Get();
foreach (ManagementObject mo in moCollection)
{
string name = mo["Name"].ToString();
if (name.Equals(this.portName))
{
System.Threading.Thread.Sleep(10000);
mo["HostAddress"] = this.printerIP;
mo.Put();
Console.WriteLine("Adjusted Printer Port to new IP address " + this.printerIP);
return true;
}
}
I need to check a group of servers to see whether the anti virus is up-to-date and running. Tricky thing is that they are spread over Windows 2003 and 2008 servers and I need to be able to check them all.
Is there any way of doing this with C# or VB.NET?
I have briefly looked around using WMI, but it appears on 2008/win7 computers Microsoft has changed what information they give back to you.
In summary, I need the following:
AV name
AV version
AV Up-to-Date
AV Enabled/Running
Can anyone help?
Sample can be found here using WMI as you mentioned. The poster states this is being done on a Win 7 machine; so the code below should get you started...
ConnectionOptions _connectionOptions = new ConnectionOptions();
//Not required while checking it in local machine.
//For remote machines you need to provide the credentials
//options.Username = "";
//options.Password = "";
_connectionOptions.EnablePrivileges = true;
_connectionOptions.Impersonation = ImpersonationLevel.Impersonate;
//Connecting to SecurityCenter2 node for querying security details
ManagementScope _managementScope = new ManagementScope(string.Format("\\\\{0}\\root\\SecurityCenter2", ipAddress), _connectionOptions);
_managementScope.Connect();
//Querying
ObjectQuery _objectQuery = new ObjectQuery("SELECT * FROM AntivirusProduct");
ManagementObjectSearcher _managementObjectSearcher =
new ManagementObjectSearcher(_managementScope, _objectQuery);
ManagementObjectCollection _managementObjectCollection = _managementObjectSearcher.Get();
if (_managementObjectCollection.Count > 0)
{
foreach (ManagementObject item in _managementObjectCollection)
{
Console.WriteLine(item["displayName"]);
//For Kaspersky AntiVirus, I am getting a null reference here.
//Console.WriteLine(item["productUptoDate"]);
//If the value of ProductState is 266240 or 262144, its an updated one.
Console.WriteLine(item["productState"]);
}
}
Depending on how your environment is setup you may need to specify your security and permissions. You should also note that some antivirus products (like McAfee) do not make data available through WMI.
You can query the Antivirus information from WMI using this snippet:
string computer = Environment.MachineName;
string wmipath = #"\\" + computer + #"\root\SecurityCenter";
string query = #"SELECT * FROM AntivirusProduct";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmipath, query);
ManagementObjectCollection results = searcher.Get();
foreach (ManagementObject result in results)
{
// do something with `result[value]`);
}