Vb. NET Development Scan Client Service tool

Source: Internet
Author: User
Tags exit garbage collection goto sleep table name thread thread stop tostring
Clients in large and medium-sized enterprise information systems, the management of client PCs, is often a problem-prone link. As a result, many large companies have introduced a variety of distributed management systems, such as the Norton Antivirus,blackice Firewall for Anti-Virus, Microsoft's SMS (System Management Server), and so on, These systems will install the appropriate client software on the client side, are generally in the form of services, but for a variety of reasons, these services will stop running or the client does not install these client services, so that the management system will be overlooked, may cause problems, such as the inability to protect the virus to become a source of viruses, Cannot publish software for this client, cannot manage client PCs, and so on. Here, we provide a program that can periodically scan the network according to the IP address and report the status of a particular service.

This scheme uses the Microsoft.NET technology and also uses the Ado.net, WMI Management,xml in the. NET framework. Its core is a program written by VB.net and its two configuration files, the configuration file is XML format, the program by IP Scan Network, get the status of each system service, if the IP address does not correspond to the system, then ignore the IP, For systems that do not have a service or service to stop, we run the nbtstat command on another thread to get information such as its machine name, username, MAC address domain, etc. so that we can find the machine to solve the problem. Second, in order to save the results of the scan, we need a very small database ms-access or Ms-sql server can be, this article uses SQL2000. Finally, in order to show the results of the scan so that we can take action, here we use the form of web pages to show the results of the database.

1. Vb. NET Program

The program uses two XML-formatted configuration files that are read in when the program starts. One of the files defines the network segment that needs to be scanned, including the excluded address segments. Another file defines the information that connects the database and the definition of the data table. The contents of these two documents are as follows:

<IPLIST>

<IP lanid= "192.168.100." ><exp l= "1" h= "/>" </IP>

<IP lanid= "192.168.101."/>

<IP lanid= "192.168.102."/>

<IP lanid= "192.168.103."/>

<IP lanid= "192.168.104." ><exp l= "1" h= "a"/> </IP>

</IPLIST>


This file definition will scan 5 network segments, of which two network segments have some addresses to exclude (assigned to printers and other devices), for 192.168.100, we exclude from 1 to 30, for 192.168.104 We exclude 1 to 40.

<DBINFO>

<SERVER> DBServer </SERVER>

<DATABASE> DB </DATABASE>

<UID> a </UID>

<PWD> a </PWD>

<service table= "SERVICE" >service </SERVICE>

</DBINFO>

This file defines the information required to connect to the database

TAG meaning
<SERVER> the server name of the Scanservice database
<DATABASE> Scanservice Database name
<UID> the database user name used to update the Scanservice database
<PWD> the password for the database user to update the Scanservice database
<SERVICE> the tag's inner defines the name of the SERVICE we want to scan,
Here we assume that we want to scan the service name.
The Tag property defines the table name in the database that is used to save the scan results.

' First we define a class that is used primarily to get the status information of a service for an IP address and to trigger another thread to get details of the system when the service state is not normal.

Imports system.serviceprocess

Imports System.Xml

Imports System.Threading

Public Class GetStatus

Private Iservicename as String ' service name

Private Imachineip as String ' IP address

Private itable as String ' table name in Dateset

' Constructor

Sub New (ByVal Ip As String, ByVal Svcname as String, ByVal updatetable as String)

IMACHINEIP = Ip

Iservicename = Svcname

itable = updatetable

End Sub

' The method used by each thread to get the state of the service and trigger another thread to get the IP information if the state is not normal

Sub GETSTAUSF ()

Dim Servicep as New ServiceController () ' Instantiate a ServiceController class

Servicep.machinename = Imachineip

Servicep.servicename = Iservicename

Dim Myrow as DataRow

Dim status as String

Dim Run as Boolean = False

Myrow = ds. Tables (itable). NewRow

Try

If ServiceP.Status.ToString <> "Running" Then

Status = ServiceP.Status.ToString ' If the state is not running then assign the state to the string variable

Else

Run = True ' If the status is running, do nothing

End If

Catch er as Exception ' The exception that occurs when a state is processed

Status = Left (Er. Message, 35)

If InStr (status, Service control Manager) = 0 Then

Status = "Not installed or open service failed" ' does not have the service installed

ElseIf InStr (Er. Message, "Manager") > 0 Then

Status = "Can not detected" ' service state is not available

End If

End Try

Servicep.close () ' Close ServiceController instance

' The following determines that if the state is not running, the system is logged and the thread is triggered to get its details.

If not Run Then

Myrow ("msg") = Status

Myrow ("IP") = Imachineip

SyncLock GetType (addrow) ' To ensure multithreading, there is only one write operation on the dataset, locking AddRow class

Dim Addrowins as New addrow (myrow) ' inserts IP and state into the dataset through our own written AddRow class

End SyncLock

' Triggers another thread to get the machine information

Dim HostInfo2 as New hostinfo (IMACHINEIP)

Dim HOSTTHR2 as New Thread (new ThreadStart (AddressOf hostinfo2.sysinfo))

Hostthr2.start ()

SyncLock GetType (Hostinfothreadcounter)

Hostinfothreadcounter.counter + + 1 ' boot thread number plus 1

End SyncLock

End If

SyncLock GetType (Stoppcounter)

Stopthr.addstop ()

End SyncLock

End Sub

End Class

' This class has only one method, which is to reduce the number of threads stopped by 1

Class Stoppcounter

Sub Addstop ()

threadcounterstopped = threadcounterstopped + 1

End Sub

End Class

' This class is used to insert an existing row into the dataset

Class AddRow

' The first constructor to enter parameters for the constructed behavior

Sub New (ByVal row as DataRow)

Try

Ds. Tables (0). Rows.Add (Row)

Catch EE as Exception



End Try

End Sub

' second constructor, updating existing rows with a machine name, such as a string as a user name

Sub New (ByVal IP As String, ByVal user As String, ByVal hostname As String, ByVal Mac as String, ByVal domain as String, B Yval Timeout as Char)

Dim Rowtimeout as DataRow

Try

For each rowtimeout in DS. Tables (0). Select ("ip= '" & IP & "")

Rowtimeout.item ("lastuid") = User

Rowtimeout.item ("Name") = hostname

Rowtimeout.item ("mac") = Mac

Rowtimeout.item ("domain") = Domain

Rowtimeout.item ("Timeout") = Timeout ' Set Timeout flag to this Item

Exit for ' just run once

Next

Catch ER as Exception



End Try

End Sub

End Class

Because of space limitations, the code for the class that obtains machine information based on IP is omitted.

Imports system.threading ' is used to support multithreading

Imports System.Xml ' used to parse parameter files in XML format

Imports System.Data ' for saving results to the database

Module Module1

Public DS as New DataSet ()

Public conn1 as Sqlclient.sqlconnection ' database connection

Public ipf as String ' ip list file name

Public dbf as String ' database information file

Public threadcounterstopped as Integer

Public Stopthr as New Stoppcounter ()

Sub Main () ' program main program

Dim Machineip as String

Dim IPLISTF as New xml.xmldocument ()

Dim IPList as Xml.xmlnode

Dim Ipitem as Xml.xmlnode

Dim Dbinfof as New xml.xmldocument ()

Dim DBinfo as Xml.xmlnode

Dim Lanid as String

Dim I as Integer

Dim Timestart as Integer

Dim threadcounterstarted as Integer


threadcounterstarted = 0

threadcounterstopped = 0

Dim Server as String

Dim Database as String

Dim UID as String

Dim pwd as String

Dim table as String

Dim connstr, connstr1 as String

Dim ServiceName as String

Dim Purgestr as String

Try

Dbinfof.load (DBF) ' Read the database information file

Catch Nodb as Exception

MsgBox (Nodb. Message & "wrong DB info file name.")

Exit Sub

End Try

Try

Iplistf.load (IPF) ' Read IP list file

Catch Noip as Exception

MsgBox (Noip. Message & "Wrong IP list file name.")

Exit Sub

End Try

' Analyze Database information files

DBinfo = dbinfof.childnodes (0)

Server = dbinfo.childnodes (0). InnerText

Database = Dbinfo.childnodes (1). InnerText

UID = dbinfo.childnodes (2). InnerText

PWD = Dbinfo.childnodes (3). InnerText

ServiceName = Dbinfo.childnodes (4). InnerText

Table = Dbinfo.childnodes (4). Attributes (0). Value

' Construct the connection string based on the analysis

CONNSTR1 = "server=" & Server & ";d atabase=" & Database & "Uid=" & uid & ";p assword=" & pwd

Conn1 = New sqlclient.sqlconnection (connstr1) ' Instantiate database connection

Conn1. Open () opens the database connection

Dim sa as Sqlclient.sqldataadapter = New sqlclient.sqldataadapter ("SELECT * from" & Table, CONN1)

Dim Combu as New sqlclient.sqlcommandbuilder (SA)

Sa. Fill dataset with Fill (DS, table)

Ds. Clear () ' empty old data '

Dim IPAddress as String

' Analyze IP List files

IPList = iplistf.childnodes (0)

Dim Ai as Integer

Dim Ipexcepcount as Integer

Dim Ipexcep as Xml.xmlnode

For each ipitem in IPList. ChildNodes

Dim excep (2,) as Integer

Lanid = Ipitem. Attributes (0). Value ' Gets the network ID

For i = 2 to 254 ' from 2 to 254 constructs an IP address based on each network ID

Ai = 0

' The following judgment is to skip the reserved address section

If Ipitem. HasChildNodes Then

Ipexcepcount = Ipitem. Childnodes.count

ReDim excep (2, ipexcepCount-1)

For each ipexcep in Ipitem. ChildNodes

EXCEP (0, Ai) = CInt (ipexcep. Attributes (0). Value)

EXCEP (1, Ai) = CInt (ipexcep. Attributes (1). Value)

AI = ai + 1

Next

End If

For Ai = 0 to IpexcepCount-1

If i >= excep (0, AI) and I <= excep (1, AI) Then

Console.WriteLine ("Skip reserved Address:" & Lanid & i.ToString)

GoTo Skipip

End If

Next

Machineip = lanid & i.tostring ' IP address

' The following trigger line Cheng to get service status

Dim getst as New getstatus (MACHINEIP, ServiceName, table)

Dim Getstthread as New Thread (new ThreadStart (AddressOf GETST.GETSTAUSF))

Getstthread.start ()

threadcounterstarted = threadcounterstarted + 1 ' boot thread number plus 1

Console.WriteLine (Thread & Machineip &) started. Detection "& ServiceName)

' 100 threads per boot, program main thread stop 15 seconds, avoid too many threads causing memory overflow

If (threadcounterstarted Mod) = 0 Then

Console.WriteLine ("Wait .......")

Thread.CurrentThread.Sleep (15000)

Gc. Collect () ' Force garbage collection to Aviod outofmemory while run with long IP list

End If

SKIPIP:

Next

Next

Console.WriteLine ("Exiting program ...") ' all threads have been triggered

Finish:

Thread.CurrentThread.Sleep (5000) ' The following program waits for all threads to end

Gc. Collect ()

If threadcounterstopped = threadcounterstarted and Hostinfothreadcounter.counter = Hostinfothreadcounter.counterstop Then ' If the triggering thread equals the end thread

Dim Row as Data.datarow

For each row in DS. Tables (table). Rows

Row. Item ("systime") = Now

Next

purgestr = "Delete" & Table

Dim com1 as New Sqlclient.sqlcommand (PURGESTR, CONN1)

COM1. ExecuteNonQuery () ' Delete old records

Sa. InsertCommand = Combu. GetInsertCommand

Sa. Update (DS, table) writes new records to the database

Else

Goto Finish ' goto finish and wait another seconds

End If

End Sub

You can use the following command to start the program in a DOS window.

Scanservice–i iplist.xml–d Dbinfo.xml


2. Scanservice Database

The database holds the results of the save program running so that it can be displayed in the form of a web. Here is the script to create the table, including the domain name, username, machine name, IP and service status.

CREATE TABLE [dbo]. [Service] (

[IP] [varchar] (m) NULL,

State [varchar] (m) NULL,

[User Name] [varchar] (m) NULL,

[Machine name] [varchar] (m) NULL,

[MAC address] [varchar] (m) NULL,

[domain] [varchar] (NULL),

Timeout [varchar] (a) NULL,

[Time Ann] [DateTime] (8) NULL,

)

Summarize:

The above is a complete method, but also a relatively simple and clear solution, if the requirements of skills and performance, there are some places can do some improvement, such as the use of the thread pool. There are other areas that need to be done by yourself, such as presenting information in the database as a web.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.