Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 51 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
51
Dung lượng
2,13 MB
Nội dung
"user " & sUserName ElseIf sUserName = "" Then Wscript.Echo "viewlogs.vbs: Displaying information for " & _ "computer " & sComputerName Else Wscript.Echo "viewlogs.vbs: Displaying information for " & _ "user " & sUserName & " on computer " & sComputerName End If Wscript.Echo "" ’ ’ 3. Generate SQL statement that will be used to retrieve ’ user login details ’ sSQL = "SELECT UserName, Computer, Time " & _ "FROM wsh.dbo.Users Users, wsh.dbo.UserLogins UserLogins " & _ "WHERE (Users.UserID = UserLogins.UserID) " If sComputerName <> "" Then sSQL = sSQL & _ "AND (UserLogins.Computer = ’" & sComputerName & "’) " End If If sUserName <> "" Then sSQL = sSQL & _ "AND (Users.UserName = ’" & sUserName & "’) " End If ’ ’ 4. Set parameters for database connection ’ sDriver = "SQL Server" sServer = "TLFSRV1" sUser = "sa" sPassword = "" sDatabase = "wsh" ’ ’ Create connection string ’ sConnect = "driver=" + sDriver + ";server=" + sServer + ";uid=" + _ sUser + ";pwd=" + sPassword + ";database=" + sDatabase Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com ’ ’ Now attempt to connect to the database ’ Set connDb = WScript.CreateObject("ADODB.Connection") connDb.ConnectionString = sConnect connDb.Open If Err.Number <> 0 Then ShowErr "Unable to connect to database." End If ’ ’ 5. Create a recordset using the SQL command that ’ we defined above ’ Set rsetLogs = WScript.CreateObject("ADODB.Recordset") rsetLogs.Open sSQL, connDb, adOpenForwardOnly, _ adLockReadOnly, adCmdText If Err.Number <> 0 Then ShowErr "Error running logs query" End If ’ ’ 6. Now we iterate through the results and dump them to ’ the screen ’ Do While Not rsetLogs.EOF Wscript.Echo rsetLogs("UserName") & _ rsetLogs("Computer") & " " & _ rsetLogs("Time") rsetLogs.MoveNext Loop ’ ’ 7. cQuit with no error ’ Wscript.Quit 0 ’ ’ SUBR: ShowErr(sDesc) ’ DESC: Displays information about the current error then quits. ’ Sub ShowErr(sDesc) Wscript.Echo "Error: " & sDesc Wscript.Echo "Err# " & Err.Number & " - " & Err.Description Wscript.Quit Err.Number End Sub Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com ’ ’ SUBR: ShowUsage() ’ DESC: Displays usage details for this script. ’ Sub ShowUsage() Wscript.Echo "USAGE: viewlogs -c[computer] - u[username]" Wscript.Echo "" Wscript.Echo " Displays details of user logins. You may" Wscript.Echo " specify either a computer or a username," Wscript.Echo " or both." Wscript.Echo "" Wscript.Echo " Example:" Wscript.Echo " " Wscript.Echo " viewlogs -cTlfsrv1 -uThomas" Wscript.Echo " " End Sub When you run the script, you’ll see something like the output depicted in Figure 17.9. Figure 17.9: The results of running the viewlogs.vbs script. The script performs the following steps: 1. The script checks the parameters that were specified on the command line. There must be at least one parameter, and the parameter must be in the form specified in the ShowUsage() function. 2. A message is displayed indicating the type of query that will occur. 3. The script dynamically generates a SQL statement that will be used to Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com retrieve the user login details. If you examine the code, you’ll notice that the WHERE clause is modified dynamically depending on the command- line parameters used to execute the script. 4. The script sets connection parameters, creates a connection string, and attempts to connect to the database that contains the user login information. 5. The database query is performed. First create a Recordset object, and then call the Open() method using the SQL statement that was dynamically generated in step 3. 6. Assuming that the query in step 5 was successful, iterate through the returned Recordset and display the query results. 7. This is the end of the script; it quits with no error code. Like the addlog.vbs script, this script builds on the steps discussed earlier in this chapter. You can easily modify it to incorporate your own database connection parameters, and you can change it to incorporate whatever SQL statement you need to use. Summary This chapter demonstrates how you can use the ADO objects to access databases to create useful WSH scripts. Our example provides the capability to record user login details in a database and to retrieve the details dynamically using a command-line interface. You can use the code from the examples as a building block for your own code that leverages ADO objects. The objects are easy to use, and you’ll find that they integrate naturally with the scripts that you create. Q&A Q Is it necessary to create a separate Connection object before you create a Command object? A No. You can pass a valid connection string directly to a Command object using the ActiveConnection property. Q Is it necessary to create a separate Connection object before you create a Recordset object? A No. If you want, you can pass a connection string directly to the Recordset.Open() method. Q What object can you use to retrieve the current username and computer? A You can get the current username and computer using the WshNetwork object, which provides Username and Computer properties. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Day 18: Using WSH to Manipulate the Microsoft Active Directory By Stephen Campbell Overview Today, you will use Windows Scripting Host and the Microsoft Active Directory to manage users and computers in a Windows NT domain. But the Active Directory enables you to do much more. It provides a standard set of tools to access any directory object, whether it is part of a Windows NT or Windows 2000 domain, a Novell Netware user list, or any other directory that supports the Lightweight Directory Access Protocol (LDAP). Today you will do the following: • Get a basic understanding of the Microsoft Active Directory and its underlying technologies. • See the Active Directory Object Model for Windows NT 4 and Windows 2000 systems. • See examples of managing the computer's resources such as printer queues and share names. • See examples of adding and removing users and groups. • See how what you have learned applies to the Windows 2000 environment. Before You Get Started Before you can run the Windows NT 4 examples in this chapter, you need to install ADSI version 2.0 or higher, the Active Directory components, onto your Windows NT 4 or Windows 95 system. This is available for no charge from the Microsoft Web site at http://www.microsoft.com/ntserver/nts/downloads/ other/ADSI2/default.asp. At the time of this writing, a beta of ADSI Version 2.5 is available at http://www.microsoft.com/ntserver/nts/downloads/ previews/ADSI25/default.asp. The full Active Directory is the central component of Windows 2000 Server, formerly called Windows NT 5 Server. The examples at the end of this chapter require Windows NT 5 Beta 2, Windows 2000 Server Beta 3, or later. (As an aside, Windows NT 5 Workstation has been renamed to Windows 2000 Professional.) Overview of the Microsoft Active Directory What is a directory? In an abstract sense, it is a list of objects, such as people, companies, computers, or buildings, with some information about those objects, such as street address, phone number, SSN, name, or digital signature certificate. Most of the time, you use a directory to find information about an object when you know some other information about that object. For example, you find a phone number when you know the name of the person. You find the name of the laser printer when you know its location. The directory you use most often, of course, is the telephone book, but there are lots of others that you use, such as the zip code directory, your NT domain accounts Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com database, and your email address book. Directories look a lot like databases, and in many cases they are implemented using database technology. Some of the important things that make directories unique are the following: • The information is retrieved much more often than it is updated. It must support browsing (give me a list of people in Topeka born in January 1995) and searching (what's the phone number of Janice Doe on Broad Street in Austin?). • The information is not updated very often. Janice doesn't move or change her phone number frequently. • The information can be a bit out of date. You don't mind too much if Janice moved last week and the directory doesn't show that, but you do mind if the bank didn't record your deposit this morning when you try to pay your utility bill this afternoon. Each item of information describing an object in a directory is called an attribute or property. For instance, the telephone number and name are attributes of the person object. The list of attributes available for a particular object, with their characteristics, is called a schema. In the past, each organization has developed schemas to meet their own needs, even though they might describe the same thing, such as the employee of a company. Efforts to standardize key schemas such as an "organizational person" have achieved some success. In the past, automated directories were implemented using proprietary software and technologies. This made development cumbersome because each directory had its own programs. Integration of multiple directories was nearly impossible, and you had to use those proprietary programs to access any information in the directory. Examples of proprietary directories include the Windows NT 4 domain accounts database and Microsoft Mail's Global Address List. A directory standard called X.500 was adopted in the late 1980s that tried to provide a standard set of definitions to meet all directory needs. This complex standard continues to evolve to meet new requirements, such as supporting multiple languages at the same time (What's your department name in English? In French?). The X.500 protocol used to access and update information in a directory is called the Directory Access Protocol, or DAP. A simpler protocol, call Lightweight Directory Access Protocol, LDAP, was developed in the early 1990s. The LDAP protocol has now become the de facto standard for accessing and updating directory information. Microsoft also realized that proprietary access methods were not cost-effective, but took a slightly different approach to use new technologies to manage their proprietary directories. The Active Directory is a Windows 2000 concept that incorporates an LDAP- accessible directory that includes users, groups, computers, share names, and all other aspects of the current Windows NT domain. It also includes the Active Directory Services Interface (ADSI), which is available now. The ADSI provides a consistent method to access any directory regardless of its underlying technology. Microsoft and other vendors supply Service Provider Interfaces (SPIs), which translate standard ADSI requests from an application into the format required by the target directory. The standard ADSI package comes with SPIs for Windows NT 4, Novell NetWare (both Bindery and NDS directories), and LDAP. Microsoft also has an SPI for managing the configuration of the Internet Information Server 4. Providers support namespaces, which are the top-level items of the directory. LDAP and WinNT are examples of namespaces. Windows NT 4 Domains Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Every Windows NT 4 workstation or server has an accounts database, or SAM. A Windows NT 4 domain is simply a group of computers with a common accounts database. Users are kept in the domain SAM. Global groups, which can contain users in that domain, are also kept in the domain accounts database. Changes to the accounts database are always done via the Primary Domain Controller, or PDC. There can be many Backup Domain Controllers (BDCs), and they receive updates to the SAM from their PDC. When you log in to the network, your computer finds a domain controller for the domain you are logging in to and validates you. Another type of server is called a member server. Each server has a local accounts database where you can create accounts and groups on this one computer. Member servers can belong to a domain and enable users and groups in that domain to access resources on the server. NT Workstation works in the same way as member servers. In NT 4, domains can trust each other. If domain ATLANTA trusts domain ACME, an administrator on ATLANTA can give a user or group in domain ACME access to a local printer or share name. This saves a lot of work because users no longer have to have an account in domain ATLANTA to access resources there. Trusts are defined in one direction—you have to establish separate trusts from domain ACME to ATLANTA and from ATLANTA to ACME. Also, trusts are not transitive: If ATLANTA trusts ACME and ACME trusts UNIVERSAL, ATLANTA does not implicitly trust UNIVERSAL. This provides additional security but also imposes additional work in complex organizations. Trusts lead to four basic enterprise permissions models: • Single domain A small organization might have a single domain. • Network All domains in the company trust all other domains in the company. This is simplest in small organizations or where administration is completely decentralized. It becomes increasingly difficult to manage as the number of domains grows. • Single master All users and global groups are created in a master domain. Resource domains contain all the users' sharenames and printers, and each trusts the master domain. This is preferred at most medium-sized organizations. Permissions on the resource domains can be delegated, but administrative access to the master domain is usually strictly controlled. • Multiple master In very large organizations or where account management is delegated, you establish a small number of master domains that hold users and groups for their scope of operations, such as a continent or subsidiary. These master domains trust all other master domains, and each resource domain trusts all the master domains. This enables an administrator in any domain to give permissions to a user or group from any of the master domains. A variation of this model has a third "security" domain that is trusted by all the other domains. The small number of "super administrators" in this domain can see the entire enterprise while protecting themselves from access. Remember that trusts do not imply that permissions are granted. It simply enables the administrator to assign permissions to users and groups from the trusted domains. Individual computers have local groups. You usually assign permissions on resources (printers, share names, and so on) to local groups. Local groups then contain users and global groups from the local domain or from trusted domains. There are a number of preconfigured local groups on each server and Windows NT workstation: Administrators, Server Operators or Power Users, Account Operators, Backup Operators, and Users. You can add your own. You should note that all domain controllers in a domain share the same local group. For example, adding a user to the local Administrators group on one domain controller grants them administrative rights to all the domain controllers there. This can be a blessing (no separate permissions needed) and a curse ("I didn't know they could do that there!"). Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com There are several other directories in the Windows NT 4 environment: • Computers in a domain • Share names on a computer • Printer queues • DHCP, DNS, and WINS services, which map co mputer names to their TCP/IP network addresses There are few attributes defined for the NT 4 directories. For example, groups have only their ID, description, and members. In Windows 2000 Server, an integrated directory becomes its central component. Windows 2000 Active Directory There are a number of limitations to the Windows NT 4 directory. There are many proprietary directories meeting specialized needs. As enterprises become more complex, Windows NT 4 becomes more difficult to administer. Probably the single most important component of Windows 2000 is the Active Directory. With the Active Directory, Microsoft has achieved most if not all the requirements for a directory: • It's standards-based. The directory is accessed and updated using LDAP. • It's extensible. You can add your own attributes to objects that are currently defined, and you can even add your own objects. • It's manageable. You can grant or revoke administrative or access permissions anywhere in the directory. • It's scalable. The directory is designed to support millions of objects. • It's malleable. As your organization changes, as companies merge or divest, the organization of the directory can be changed. • It's secure. Updates to all objects, including the directory, are authenticated using a secure, efficient, standard protocol called Kerberos. The Active Directory is organized as a forest of trees. Each tree is a single Windows 2000 domain, and the collection of all domains in an enterprise is a forest. Users can search the entire forest. Permissions between trees can be assigned. A domain is given an Internet name such as acme.com, and domain controllers are found using DNS. A domain is no longer a flat structure. It can include a hierarchy of Organizational Units, as shown in the Figure 18.1, taken from a Windows 2000 directory management Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com computers in the Atlanta Organizational Unit. By default, having permissions at one level of the hierarchy gives permissions at all lower levels. Figure 18.1: Windows 2000 directory hierarchy. The schema is much bigger too. There are about 200 objects, called classes in Windows 2000, and about 1500 attributes. Figures 18.2 and 18.3 show some of the information that can be filled in for users. You can see all the Windows NT 4 fields are still there, but there are many more. Figure 18.2: Windows 2000 User—General tab. Figure 18.3: Windows 2000 User—Account tab. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Active Directory Services Active Directory services are relatively straightforward for Windows Scripting Host. A comprehensive set of access facilities exists for C++ programmers, but the discussion here will limit itself to the Automation access methods available from Windows Scripting Host. Retrieving Directory Objects First, you retrieve an object using GetObject(), passing in the directory object you want or the name of the directory service provider. This establishes a session to your object with your current login credentials. Note that the provider name is case sensitive, whereas attributes and methods are not. For example: set oProvider=GetObject("WinNT:") set oProvider=GetObject("LDAP:") In the rare case where you need to access the object using other credentials, use the DSOpenObject() method for any existing directory object, or the provider itself, as follows: Set oDirEntry=oProvider.OpenDSObject(<ADSPath>,<userid>,<password>,<flags>) The <ADSPath> is the directory object you want to open; the <userid> and <password> are straightforward. Flags depend on what directory provider you are using and can usually be omitted. How you name a directory object depends on its directory service provider. ADSPath Each directory object has a unique identifier. This is usually the namespace and each element of the directory hierarchy to the object. For example, the ADSPath of a Windows NT user is WinNT://domain/userid. Objects in Microsoft Exchange Server and the Windows 2000 Active Directory are accessed using LDAP. Each item in the list is the next element as you work down the tree. For example, the ADSPath to an Exchange mailbox is as follows: LDAP://ExchangeServer/o=organization/ou=site/cn=container/cn=mailbox A Note to Microsoft Exchange Administrators ADSI is a good way to automate many administration tasks for Exchange 5.5 mailboxes and distribution lists. There are a couple of excellent articles on this topic in Microsoft Technet. Search for the keywords exchange and adsi. If you want to go beyond those articles, you can find the LDAP name of any attribute or class. Use admin in raw mode (admin -r), and look at its definition in the schema. The description field of the attribute contains the LDAP name. If you are not sure what class a particular object has, open the raw properties of that Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... you haven’t specified a domain The WinNT object is a container object that holds each domain it can find using the NT or Windows 95 /98 browser service.à à The following line will therefore go through this collection and return each available domain:à à for each oDomain in oWinNTà à The following line returns each item in the domain:à à for each oDomainItem in oDomainà à This includes all the userids,... from ShowDomainInfo_NT4.vbs.à à Ãà à à à à à à à à à à à à à à à à à à à à à à à à à à à à à ’ ShowDomainInfo_NT4.vbs - Display information about each object in a domainà ’ 199 8-12-13 stephen.campbell@marchview.comà set oWinNT = GetObject("WinNT:") ’ WinNT is casesensitive!!à for each oDomain in oWinNTà WScript.echo oDomain.nameà for each oDomainItem in oDomainà WScript.echo " " + oDomainItem.Class... "/" + sPrintQueue)à à The list of print jobs in a queue can be examined using the collection oPrintQueue.PrintJobs:à à à à à à à à à à à à à à à à à à à à à à à à à à set oPrintJobs = oServerItem.PrintJobsà for each oPrintJob in oPrintJobsà WScript.echo " " + oPrintJob.class + " Name=" + oPrintJob.name + _à " User=" + oPrintJob.userà WScript.echo " Description=" + oPrintJob.Descriptionà WScript.echo... job in the print queueà ’ 199 8-12-13 stephen.campbell@marchview.comà sDomain="MARCH"à sServer="SABER"à sPrintQueue="HP"à sPrintJob="84"à set oPrintQueue = GetObject("WinNT://" + sDomain + "/" + sServer + "/" + sPrintQueue)à set oPrintJobs=oPrintQueue.PrintJobsà set oPrintJob = oPrintJobs.GetObject(sPrintJob)à WScript.echo "Job=" + oPrintJob.Nameà iPriority = oPrintJob.Priority + 1à oPrintJob.Priority... FormatDateTime(oServerItem.UntilTime)à set oPrintJobs = oServerItem.PrintJobsà for each oPrintJob in oPrintJobsà WScript.echo " " + oPrintJob.class + " Name=" + oPrintJob.name + _à " User=" + oPrintJob.userà WScript.echo " Description=" + oPrintJob.Descriptionà WScript.echo " TimeSubmitted=" + _à à à à à à à à à à à formatdatetime(oPrintJob.TimeSubmitted)à WScript.echo " TotalPages=" + formatnumber(oPrintJob.TotalPages,0)à WScript.echo... FormatNumber(oSession.IdleTime,0) + "minutes."à nextà Using ADSI with Windows NT 2000à à Many of the concepts discussed in earlier sections can be applied now to manage your Windows NT 2000 environment You might want to go back and review the discussion of Windows 2000 domains at the beginning of this section before you move into this.à à Remember that you use the ADSI LDAP interface to interact with the Windows 2000 domain To manipulate... Managing NT Resources Using ADSIà à As you saw earlier in this chapter, you can retrieve information about printer queues and print jobs using ADSI.à à Print Queuesà à à à à à à à à à à à à The printqueue objectand within Unregistered Versiondefined in the Simpo PDF Merge lies Split the computer object It is - http://www.simpopdf.com à following:à à à à set oPrintQueue = GetObject("WinNT://" + sDomain... contain, as shown in Figure 18.11à à à à à à à à Figure 18.11: MMC Console showing attributes associated with a class.à à à Ãà à Ãà à Cautionà Do not modify the Schema without knowing what you are doing Like ÃRegistry changes in Windows NT 4, you can do irreversible damage to your configuration.à à à à à Accessing the Windows 2000 Domainà à Now, look at this script, which shows the information about a Windows. .. http://www.simpopdf.com Qà How do I find out the meanings of the error codes and messages that I à receive?à à à Ãà à Aà At the time of this writing, documentation of ADSI is "evolving" (in other words, bad), especially in the area of error messages Most of ADSI debugging these days involves à going back to something that works and trying one new thing at a time Often the errors are inexplicable Keep going to the Microsoft... work with other Microsoft messaging clients such as Windows Inbox, Microsoft Exchange Client, and so on, it is not supported by Microsoft The examples in this chapter were tested with the Windows Messaging Inbox and CDO 1.2.1 installed.à à To determine whether the libraries are installed and what version they are, run the following script from a command prompt:à à cscript CDOVersion.vbsà à By now, . domain: for each oDomain in oWinNT The following line returns each item in the domain: for each oDomainItem in oDomain This includes all the userids, groups, computers, and the schema again. You. each oDomain in oWinNT WScript.echo oDomain.name for each oDomainItem in oDomain WScript.echo " " + oDomainItem.Class + " " + oDomainItem.Name select case oDomainItem.Class . haven’t specified a domain. The WinNT object is a container object that holds each domain it can find using the NT or Windows 95 /98 browser service. The following line will therefore go through