Solved

Stopping and Starting a Service using VB.Net

Posted on 2006-11-25
10
4,459 Views
Last Modified: 2007-12-19
Hi,

I have written the following piece of code to stop and start a particular service on a remote machine.

Public Sub call_bat()

        Dim proc As New System.Diagnostics.Process
        Dim startinfo As New System.Diagnostics.ProcessStartInfo
        Dim myController As ServiceController
        myController = New ServiceController
        myController.MachineName = "10.144.1.196"
        'myController.MachineName = "10.144.2.44"
        myController.ServiceName = "TSM server1"

        If myController.CanStop Then
            myController.Stop()
        Else
            MsgBox("TSM server1 service cannot be stopped or the service is already stopped")

        End If

        startinfo.FileName = "E:\Program Files\Tivoli\tsm\server1\rest1.bat"
        startinfo.UseShellExecute = True
        startinfo.WorkingDirectory = "E:\Program Files\Tivoli\tsm\server1\"
        startinfo.WindowStyle = ProcessWindowStyle.Normal
        proc.StartInfo = startinfo

        Try
            proc.Start()
        Catch ex As Exception
            MsgBox(ex.Message)
            Exit Sub
        End Try
        proc.WaitForExit()

        Try
            myController.Start()
            MsgBox("TSM server1 service started")
        Catch ex As Exception
            MsgBox(ex.Message)
            Exit Sub
        End Try

    End Sub

The machine is : Windows 2000 Advanced Server. The code used to work perferctly. But recently it shows the following error.

" An unhandled exception of type 'System.InvalidOperationException' occurred in system.serviceprocess.dll

Additional information: Cannot open Service Control Manager on computer '10.144.1.196'. This operation might require other privileges. "

Kinldy help on how this can be resolved. Is there any option in Service controller where in we can specify user id / password ?

Regards,

Sreejith
0
Comment
Question by:sreejithm
10 Comments
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
Comment Utility
>Kinldy help on how this can be resolved. Is there any option in Service controller where in we can specify user id / password ?
you will need to grant the user that runs your application the permissions to start/stop the services on the remote machine.
the code is indeed fine, you cannot do anything there.
0
 
LVL 8

Expert Comment

by:YoungBonzi
Comment Utility
It looks like I can be done with Impersonation.

This person was able to do it in his program: http://www.codeproject.com/csharp/svcmgr.asp
0
 
LVL 3

Expert Comment

by:joachim.claeys@teleatlas.com
Comment Utility
Hi,

Try using the following (wmi) function  to start/stop services on the remote computer:

Parameters:
sComputer: remote host
sName: Service Name
bStart: True = start, False = stop

Hope this helps.

'''''''''''''''''''''''''''''''''''''''''''''''''''''''
Sub alterServiceState(ByVal sComputer As String, ByVal sName As String, ByVal bStart As Boolean)
        Dim co As ConnectionOptions = New ConnectionOptions()
        'co.Username = "myuser"
        'co.Password = "mypassword"
        Dim scope As New System.Management.ManagementScope
        Try
            scope = New System.Management.ManagementScope("\\" & sComputer & "\root\cimv2")
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

        scope.Connect()
        Dim query As ObjectQuery = New ObjectQuery("Select * from Win32_Service Where Name = " & Chr(34) & sName & Chr(34) & " ")
        Dim searcher As ManagementObjectSearcher = New ManagementObjectSearcher(scope, query)
        Dim observer As ManagementOperationObserver = New ManagementOperationObserver()
        Dim queryCollection As ManagementObjectCollection = searcher.Get()
        Dim m As ManagementObject
        Dim args As Object
        Try
            For Each m In queryCollection
                If m.Item("Started").Equals("True") Then
                    If Not bStart Then
                        m.InvokeMethod("StopService", args)
                    End If
                Else
                    If bStart Then
                        m.InvokeMethod("StartService", args)
                    End If
                End If
            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
End Class
'''''''''''''''''''''''''''''''''''''''''''''''''''''''
0
 

Author Comment

by:sreejithm
Comment Utility
Hi joachim

Sorry for the delay in responding. I was down with fever.

I tried using your code. But it says "Access Denied". I am working with the administrator ID.

Regards,
0
 

Author Comment

by:sreejithm
Comment Utility
Hi

I just modifed the code by joachim and checked if I'm able to connect to WMI

Sub test_wmi()
        Dim myConnectionOptions As New System.Management.ConnectionOptions
        With myConnectionOptions
            .Username = "MESADXBDWNBRAED\Administrator"
            .Password = "Password2"

            Dim myManagementScope As System.Management.ManagementScope

            Dim myServerName As String = "."
            myManagementScope = New System.Management.ManagementScope("\\" & "MESADXBDWNBRAED"         & "\root\cimv2", myConnectionOptions)

            myManagementScope.Connect()
            If myManagementScope.IsConnected = False Then
                MsgBox("Could not connect to WMI namespace")
            ElseIf myManagementScope.IsConnected = True Then
                MsgBox("connected to WMI namespace")
            End If
End Sub

----------------

This code works perfectly.. I'm able to connect to WMI.

However When I query the namespace like in the below code,

 Dim myObjectSearcher As System.Management.ManagementObjectSearcher
            Dim myCollection As System.Management.ManagementObjectCollection
            Dim myObject As System.Management.ManagementObject
            myObjectSearcher = New System.Management.ManagementObjectSearcher( _
              myManagementScope.Path.ToString, "Select * From Win32_Product")
            myCollection = myObjectSearcher.Get()

            For Each myObject In myCollection
                Console.WriteLine(myObject.GetPropertyValue("Caption"))
            Next

I get the access denied error at the like "myCollection = myObjectSearcher.Get()".

--------------------

Is there any need to specify any access /login rights at the server itself ?

Regards,

0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 3

Expert Comment

by:joachim.claeys@teleatlas.com
Comment Utility

Try to replace your code with this: ( untested - should work )
Change options.username, options.password and strComputername to the appropriate values.

        Dim scope As ManagementScope = New ManagementScope
        Dim strComputerName As String = "MyServerName"
        Dim query As ObjectQuery
        Dim searcher As ManagementObjectSearcher        
        Dim queryCollection As ManagementObjectCollection
        Dim options As ConnectionOptions = New ConnectionOptions
        options.Username = "testAccount"
        options.Password = "fooo"
        Dim query As New SelectQuery("Win32_Product")
        scope = New ManagementScope("\\" & strComputerName & "\root\cimv2", options)
        scope.Connect()
        queryCollection = searcher.Get()
        For Each m As ManagementObject In queryCollection
            Console.WriteLine(myObject.GetPropertyValue("Caption"))
        Next
Regards,
Joachim
0
 

Author Comment

by:sreejithm
Comment Utility
Hi Joachim,

Thanks a lot. The code works for majority of our servers. However it shows "Access Denied " error on some of our
servers. Few of my teammates are of the opinion that there are some WMI parameters that needs to be configured on these servers inorder to allow remote access to the root\cimv2 namespace. But we are not sure how this can be done.
 Or is there any other solution to this ?

Thanks and best regards,

0
 
LVL 3

Expert Comment

by:joachim.claeys@teleatlas.com
Comment Utility
Which WMI parameters are you unable to access ?

Thanks,
Joachim
0
 

Author Comment

by:sreejithm
Comment Utility
Hi Joachim,

Basically I've written my code to work with the TSM service on our servers.. So I query Win32_Service from root\cimv2 for this service and then work with that.

On some servers I get the error "Access Denied" for the line scope.Connect() as per your code.

Regards,

0
 
LVL 3

Accepted Solution

by:
joachim.claeys@teleatlas.com earned 500 total points
Comment Utility
Hi,

This article from Microforge.net helps you identify WMI "Acccess Denied" errors:

http://www.microforge.net/kb/62

Hope this gets you further ...

Joachim.
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Here we come across an interesting topic of coding guidelines while designing automation test scripts. The scope of this article will not be limited to QTP but to an overall extent of using VB Scripting for automation projects. Introduction Now…
This article will show, step by step, how to integrate R code into a R Sweave document
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now