How to change the registry value of remote system using C# - c#

Hai every one
I am developing an windows application in which i have to block the removable storage devices such as pendrives.I found that its possible by changing the registry value of HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\UsbStor,start value to 4.But the problem is I have to block it on remote systems too.Can any one suggest me how to change the value of registry of remote system using c# with a code or sites where i can i find the code for this.

The .net way is to use Microsoft.Win32.RegistryKey.OpenRemoteBaseKey.
An alternative would be to use WMI. There are lots of examples on Google for reading values; replacing GetStringValue with SetStringValue (or SetDWORDValue, etc.) should do what you want.

You probably want to take a look at the Remote Registry Service and make an RPC call.
MSDN description: http://msdn.microsoft.com/en-us/library/aa940121(WinEmbedded.5).aspx
MSDN example using RegistryKey.OpenRemoteBaseKey: http://msdn.microsoft.com/en-us/library/8zha3xws.aspx

You need to have Remote Registry service running on remote machine. Then you can use WMI to connect the registry. Here is a code sample script from this site:
Dim strComputer
Dim strUserName
Dim strPassword
Dim objLocator
Dim objService
Dim objRegistry
strComputer = "somesys"
strUserName = "somename"
strPassword = "somepw"
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
Set objService = objLocator.ConnectServer( strComputer, _
"Root\Default", strUserName, strPassword )
objService.Security_.impersonationlevel = 3
Set objRegistry = objService.Get( "StdRegProv" )
'Do something here like retrieving or setting values.
Set objRegistry = Nothing
Set objLocator = Nothing
Set objService = Nothing
you can get many valuable results by googling for "using WMI to modify remote registry"

Related

windows remote login api using c#/c++

I want to write a program to login into remote machine using domain admin user credential and do following tasks
Get some system information like OS, IIS version, .net version etc
Transfer some files from remote to local machine and vice versa.
Is there any windows API to do this?
Task I am trying to do can done manually using remote desktop application, but I don't want to use GUI as I would like to automate this, to get machine info periodically from our environment and display in a Dashboard.
you can use winrm
and automate it using powershell
https://msdn.microsoft.com/en-us/library/aa384426%28v=vs.85%29.aspx
here is a vb example (you can use the same COM objects in c#)
Const RemoteComputer = "ComputerName.domain.com"
Set objWsman = CreateObject("Wsman.Automation")
Set objConnectionOptions = objWsman.CreateConnectionOptions
objConnectionOptions.UserName = "Username"
objConnectionOptions.Password = "Password"
iFlags = objWsman.SessionFlagUseKerberos Or _
objWsman.SessionFlagCredUserNamePassword
Set objSession = objWsman.CreateSession("https://" & RemoteComputer, _
iFlags, objConnectionOptions)
strResource = "http://schemas.microsoft.com/wbem/wsman/1/" & _
"wmi/root/cimv2/Win32_OperatingSystem"
Set objResponse = objSession.Enumerate(strResource)
While Not objResponse.AtEndOfStream
DisplayOutput(objResponse.ReadItem)
Wend
'****************************************************
' Displays WinRM XML message using built-in XSL
'****************************************************
Sub DisplayOutput(strWinRMXml)
Dim xmlFile, xslFile
Set xmlFile = CreateObject("MSXml2.DOMDocument.3.0")
Set xslFile = CreateObject("MSXml2.DOMDocument.3.0")
xmlFile.LoadXml(strWinRMXml)
xslFile.Load("WsmTxt.xsl")
Wscript.Echo xmlFile.TransformNode(xslFile)
End Sub

Mobile Broadband - how to obtain service provider name

I am unable to find out how to obtain the service providers name from the windows 7 mobile broadband API.
The provider.providerName always returns a null string but the providerID is correct (23430) for EE here in the UK.
Below is show a snippet of the used to obtain this information. All the other aspects of the Mbn interface are working
including the profiles etc, but I cant find out how to get the Name!
Am I missing something? , Could any one help me out on my final issue please?
Note: Windows VAN does show the service provider.
My Many Thanks
Sarah
///
/// Check the reported state of this interface
switch (readyState)
{
case MBN_READY_STATE.MBN_READY_STATE_INITIALIZED:
/// interface is initialised and has active SIM
/// so lets get service providor information
///
MBN_PROVIDER provider = mobileInterface.GetHomeProvider();
mi.Provider = provider.providerName; // Always ""
mi.ProviderID = provider.providerID; // but this is correct
mi.ProviderState = provider.providerState; // as is all this
mi.Signaldbm = mbnGetSignal(mi.InterfaceID);
mi.Signalbar = mbnConvertSignal(mi.Signaldbm);
mi.Message = "Ready";
break;
System Setup
Windows 7 Lenovo Laptop, F3507g internal modem
The answer provided here for Configuring a Connection Programatically was my solution:
C# Read Windows Mobile Broadband connection properties
This helped me to find the ProfileName (netsh mbn show profiles) by iterating across interfaces and then calling GetConnectionProfiles() passing the interface as a parameter and then loading an XMLDocument with the IMbnConnectionProfile GetProfileXMLData
The ProfileName is in the XMLDocument["MbnProfile"]["Name"].InnerText
It seems like a lot of work but if you only have to worry about one interface and one profile you can use the first element of each array. I'll paste my code in but it's VB
Dim mcpm As MbnConnectionProfileManager = New MbnConnectionProfileManager()
Dim imcpm As IMbnConnectionProfileManager = DirectCast(mcpm, IMbnConnectionProfileManager)
Dim connectionProfiles() As IMbnConnectionProfile
Dim mim As MbnInterfaceManager = New MbnInterfaceManager()
Dim imim As IMbnInterfaceManager = DirectCast(mim, IMbnInterfaceManager)
Dim interfaceArray() As IMbnInterface = imim.GetInterfaces()
For Each i As IMbnInterface In interfaceArray
connectionProfiles = imcpm.GetConnectionProfiles(i)
For Each c As IMbnConnectionProfile In connectionProfiles
Dim doc As System.Xml.XmlDocument = New System.Xml.XmlDocument()
doc.LoadXml(c.GetProfileXmlData())
cmbMBNProfileName.Items.Add(doc("MBNProfile")("Name").InnerText)
Next
Next

Getting strange error code when programmatically adding a machine to a domain using C#

I am trying to add a Windows machine (server 2008 R2) to a domain programmatically using C#. I know I have the correct permissions to add the machine to the domain because I am able to add it manually through the windows UI. I also know that my ManagementScope is correct because when I create it I am able to query any WMI object that I want. I am trying to connect as follows:
ManagementClass computerSystem = new ManagementClass(scope, new ManagementPath("Win32_ComputerSystem"), new ObjectGetOptions());
ManagementObjectCollection computerSystemInstances = computerSystem.GetInstances();
ManagementObject baseObject = computerSystemInstances.ToList<ManagementObject>().First();
ManagementBaseObject inParams = baseObject.GetMethodParameters("JoinDomainOrWorkgroup");
inParams["Name"] = "my.domain.com";
inParams["Password"] = domainCredentials.FullUserName;
inParams["UserName"] = domainCredentials.Password;
inParams["FJoinOptions"] = 1;
var joinParams = baseObject.InvokeMethod("JoinDomainOrWorkgroup", inParams, null);
The method invoke does not throw any exceptions, but the error code value found at joinParams.Properties["ReturnValue"].Value is 1312. I can't find any documentation anywhere (even on Microsoft's MSDN page for the method) stating what this error code means. Does anyone know where to find what this error code is for?
In your code, you've transposed your username and password to the wrong variables. This may be the cause?
This might be a system error code, found http://msdn.microsoft.com/en-us/library/ms681385%28v=vs.85%29
ERROR_NO_SUCH_LOGON_SESSION
1312 (0x520)
A specified logon session does not exist. It may already have been terminated.

Granting remote user (non admin) the ability to enumerate services in Win32_Service in namespace cimv2 using WMI & C#

I'm creating a watch dog service that will be monitoring other services on various remote servers (all in the same domain). The user that I'm using to connect to the remote servers is not an admin. When I try to enumerate the services in the Win32_Service class, I get an access denied error.
I've given the user 'Remote Enable' & 'Enable Account' persmissions to the Root\CIMV2 namespace in the WMI Control.
I am able to connect to the server with the following code. The object ServiceListItem is just a simple class that contains the server name and the service name:
SecureString secureString = new SecureString();
foreach ( char c in "password" )
{
secureString.AppendChar( c );
}
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.Username = "domain\\user";
connectionOptions.SecurePassword = secureString;
foreach ( ServiceListItem service in _serviceList )
{
ManagementScope managementScope = new ManagementScope();
managementScope = new ManagementScope( String.Format( #"\\{0}\root\cimv2", service.ServerName ), connectionOptions );
managementScope.Connect();
//RelatedObjectQuery relatedObjectQuery = new RelatedObjectQuery( String.Format( "Win32_Service.Name='{0}'", service.ServiceName ) );
//ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher( managementScope, relatedObjectQuery );
ObjectQuery objectQuery = new ObjectQuery( "SELECT * FROM Win32_Service WHERE Name = '" + service.ServiceName + "'" );
ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher( managementScope, objectQuery );
ManagementObjectCollection objectCollection = objectSearcher.Get();
foreach ( ManagementObject managementObject in objectCollection )
{
serviceStatus = managementObject.Properties["State"].Value.ToString();
Debug.Print(service.ServiceName + " - " + serviceStatus);
//break;
}
}
The managementScope.Connect() runs fine, which means the wmi security on cimv2 is set up correctly. However, when I try to enumerate the objectCollection, I get the 'Access Denied' exception. This tells me (I think) that the user doesn't have permissions to enumerate the Win32_Service class (SC_MANAGER_ENUMERATE_SERVICE).
I just haven't been able to find any good examples on how to enable that permission for a remote user. I'm not very experienced when it comes to coding with Windows api's, so please be as detailed as possible in your answers :)
Trying to find the same answer myself today, I've been doing a lot of googling. After a good half hour of incantations, I found this MSDN article (907460) which uses sc sdet. It seems to work so far, even though the security descriptor is for Windows Server 2003. I've found you can do sc sdshow SCMANAGER to get the current value so when back in the office tomorrow I'll be comparing an contrasting to make sure I've not locked something out I shouldn't have :-)
For completeness, the notes in KB907460 (in case it moves/goes away):
Symptoms: After you install Microsoft Windows Server 2003 Service Pack 1 (SP1), non-administrators cannot remotely access the Service Control Manager.
Cause: Windows Server 2003 SP1 changes the Service Control Manager default security settings.
Resolution:
To resolve this issue, use version 5.2.3790.1830 of the Sc.exe tool.
This tool is located in the %windir%\System32 folder. To do this,
follow these steps:
Click Start, click Run, type cmd, and then click OK.
Type the following command at the command prompt, and then press ENTER:
sc sdset SCMANAGER D:(A;;CCLCRPRC;;;AU)(A;;CCLCRPWPRC;;;SY)(A;;KA;;;BA)S:(AU;FA;KA;;;WD)(AU;OIIOFA;GA;;;WD)
I found myself stuck into a similar problem. In my case it had nothing to do with permissions, which I did set by following this link: http://www.poweradmin.com/help/enableWMI.aspx
So, After hours of wondering lost I found this article that tells how UAC interfere with your set of permissions and how can you fix that:
http://www.solarwinds.com/documentation/apm/docs/APMWMITroubleshooting.pdf
In my case, the registry key didn't existed, so I created it.
Hope this helps also, cheers!

Setting Server Bindings of IIS 6.0 Programmatically

I'm trying to set up an installer to register a web site. Currently, I've got it creating an Application Pool and Web Site under Windows Server 2003. Unfortunately, whenever I try to modify the ServerBindings property to set the IP Address, it throws an exception at me. I first tried this because the documentation here told me to http://msdn.microsoft.com/en-us/library/ms525712%28VS.90%29.aspx. I'm currently using VB.NET, but C# answers are okay too as I need to switch it over to using C# anyway.
siteRootDE.Properties.Item("ServerBindings").Item(0) = "<address>"
This throws an ArgumentOutOfRangeException. I checked it, and server bindings is of size 0. When I tried to create a new entry in the list like this:
siteRootDE.Properties.Item("ServerBindings").Add("<address>")
I get a COMException when I try that.
I looked at the registered property keys, and ServerBindings is nowhere to be found. However, when I create the Web Site through IIS, it generates ServerBindings correctly and I can see it.
What do I need to do to get ServerBindings to appear?
EDIT: I moved the code over to C# and tried it. It seems for some reason, VB.NET crashes when given either the above, but C# doesn't. But that code still doesn't seem to do anything. It just silently fails. I'm trying it like this:
// WebPage is the folder where I created the website
DirectoryEntry siteRootDE = new DirectoryRoot("IIS://LocalHost/W3SVC/WebPage");
// www.mydomain.com is one of the IP addresses that shows up
// when I used the IIS administrative program
siteRootDE.Properties["ServerBindings"].Value = ":80:www.mydomain.com";
siteRootDE.CommitChanges();
In C# you should be able to do this:
webSite.Invoke("Put", "ServerBindings", ":80:www.mydomain.com");
or
webSite.Properties["ServerBindings"].Value = ":80:www.mydomain.com";
EDIT:
Here is the sample code I used.
public static void CreateNewWebSite(string siteID, string hostname)
{
DirectoryEntry webService = new DirectoryEntry("IIS://LOCALHOST/W3SVC");
DirectoryEntry website = new DirectoryEntry();
website = webService.Children.Add(siteID, "IIsWebServer");
website.CommitChanges();
website.Invoke("Put", "ServerBindings", ":80:" + hostname);
// Or website.Properties["ServerBindings"].Value = ":80:" + hostname;
website.Properties["ServerState"].Value = 2;
website.Properties["ServerComment"].Value = hostname;
website.CommitChanges();
DirectoryEntry rootDir = website.Children.Add("ROOT", "IIsWebVirtualDir");
rootDir.CommitChanges();
rootDir.Properties["AppIsolated"].Value = 2;
rootDir.Properties["Path"].Value = #"C:\Inetpub\wwwroot\MyRootDir";
rootDir.Properties["AuthFlags"].Value = 5;
rootDir.Properties["AccessFlags"].Value = 513;
rootDir.CommitChanges();
website.CommitChanges();
webService.CommitChanges();
}
Also, here is a good article for reference.

Categories