• WebLogic Scripting Tool


    Using the WebLogic Scripting Tool

    WebLogic Scripting Tool

        
    Previous 
    Next 
     
    Open TOC in new window 
    Open Index in new window 
    View as PDF - New Window 
    Get Adobe Reader - New Window

    Content starts here


    Using the WebLogic Scripting Tool


    The following sections describe the WebLogic Scripting Tool:



    What is the WebLogic Scripting Tool?


    The WebLogic Scripting Tool (WLST) is a command-line scripting interface that system administrators and operators use to monitor and manage WebLogic Server instances and domains. The WLST scripting environment is based on the Java scripting interpreter, Jython. In addition to WebLogic scripting functions, you can use common features of interpreted languages, including local variables, conditional variables, and flow control statements. WebLogic Server developers and administrators can extend the WebLogic scripting language to suit their environmental needs by following the Jython language syntax. See
    http://www.jython.org
    .


    What Does WLST Do?


    WLST lets you perform the following tasks:


    WLST functionality includes the capabilities of these WebLogic Server command-line utilities: the weblogic.Admin utility that you use to interrogate MBeans and configure a WebLogic Server instance (deprecated in this release of WebLogic Server), the wlconfig Ant task tool for making WebLogic Server configuration changes, and the weblogic.Deployer utility for deploying applications. For more information about these command-line utilities, see:


    You can create, configure, and manage domains using WLST, command-line utilities, and the Administration Console interchangeably. The method that you choose depends on whether you prefer using a graphical or command-line interface, and whether you can automate your tasks by using a script. See Script Mode.


    How Does WLST Work?


    You can use the scripting tool online (connected to a running Administration Server or Managed Server instance) and offline (not connected to a running server). For information on WLST online and offline commands, see WLST Online and Offline Command Summary.


    Using WLST Online


    Online, WLST provides simplified access to Managed Beans (MBeans), Java objects that provide a management interface for an underlying resource that you can manage through JMX. WLST is a JMX client; all the tasks you can do using WLST online, can also be done programmatically using JMX.


    For information on using JMX to manage WebLogic Server resources, see Developing Custom Management Utilities with JMX.


    When WLST is connected to an Administration Server instance, the scripting tool lets you navigate and interrogate MBeans, and supply configuration data to the server. When WLST is connected to a Managed Server instance, its functionality is limited to browsing the MBean hierarchy.


    While you cannot use WLST to change the values of MBeans on Managed Servers, it is possible to use the Management APIs to do so. BEA Systems recommends that you change only the values of configuration MBeans on the Administration Server. Changing the values of MBeans on Managed Servers can lead to an inconsistent domain configuration.


    Using WLST Offline


    Using WLST offline, you can create a new domain or update an existing domain without connecting to a running WebLogic Server—supporting the same functionality as the Configuration Wizard.


    Offline, WLST only provides access to persisted configuration information. You can create new configuration information, and retrieve and change existing configuration information that is persisted in the domain configuration files (located in the config directory, for example, config.xml) or in a domain template JAR created using Template Builder.

    Note:Because WLST offline enables you to access and update the configuration objects that appear in the configuration files only, if you wish to view and/or change attribute values for a configuration object that is not already persisted in the configuration files as an XML element, you must first create the configuration object.


    Modes of Operation


    WLST is a command-line interpreter that interprets commands either interactively, supplied one-at-a-time from a command prompt, or in batches, supplied in a file (script), or embedded in your Java code. The modes of operation represent methods for issuing WLST commands:


    Interactive Mode


    Interactive mode, in which you enter a command and view the response at a command-line prompt, is useful for learning the tool, prototyping command syntax, and verifying configuration options before building a script. Using WLST interactively is particularly useful for getting immediate feedback after making a critical configuration change. The WLST scripting shell maintains a persistent connection with an instance of WebLogic Server. Because a persistent connection is maintained throughout the user session, you can capture multiple steps that are performed against the server. See Recording User Interactions.


    In addition, each command that you enter for a WebLogic Server instance uses the same connection that has already been established, eliminating the need for user re-authentication and a separate JVM to execute the command.


    Script Mode


    Scripts invoke a sequence of WLST commands without requiring your input, much like a shell script. Scripts contain WLST commands in a text file with a .py file extension, for example, filename.py. You use script files with the Jython commands for running scripts. See Running Scripts.


    Using WLST scripts, you can:

    • Automate WebLogic Server configuration and application deployment
    • Apply the same configuration settings, iteratively, across multiple nodes of a topology
    • Take advantage of scripting language features, such as loops, flow control constructs, conditional statements, and variable evaluations that are limited in interactive mode
    • Schedule scripts to run at various times
    • Automate repetitive tasks and complex procedures
    • Configure an application in a hands-free data center


    In Listing 2-1, WLST connects to a running Administration Server instance, creates 10 Managed Servers and two clusters, and assigns the servers to a cluster.


    Edit the script to contain the username, password, and URL of the Administration Server and start the server before running this script. See Running Scripts.


    Listing 2-1 Creating a Clustered Domain

    from java.util import *
    from javax.management import *
    import javax.management.Attribute

    print 'starting the script .... '

    connect('username','password','t3://localhost:7001')
    clusters = "cluster1","cluster2"
    ms1 = {'managed1':7701,'managed2':7702,'managed3':7703, 'managed4':7704, 'managed5':7705}
    ms2 = {'managed6':7706,'managed7':7707,'managed8':7708, 'managed9':7709, 'managed10':7710}

    clustHM = HashMap()
    edit()
    startEdit()

    for c in clusters:
      print 'creating cluster '+c
      clu = create(c,'Cluster')
      clustHM.put(c,clu)

    cd('..\..')

    clus1 = clustHM.get(clusters[0]) 
    clus2 = clustHM.get(clusters[1])

    for m, lp in ms1.items():
      managedServer = create(m,'Server')
      print 'creating managed server '+m
      managedServer.setListenPort(lp)
      managedServer.setCluster(clus1)

    for m1, lp1 in ms2.items():
      managedServer = create(m1,'Server')
      print 'creating managed server '+m1
      managedServer.setListenPort(lp1)
      managedServer.setCluster(clus2)
    save()
    activate(block="true")
    disconnect()
    print 'End of script ...'
    exit()


    Embedded Mode


    In embedded mode, you instantiate an instance of the WLST interpreter in your Java code and use it to run WLST commands and scripts. All WLST commands and variables that you use in interactive and script mode can be run in embedded mode.


    Listing 2-2 illustrates how to instantiate an instance of the WLST interpreter and use it to connect to a running server, create two servers, and assign them to clusters.


    Listing 2-2 Running WLST From a Java Class

    package wlst;
    import java.util.*;
    import weblogic.management.scripting.utils.WLSTInterpreter;
    import org.python.util.InteractiveInterpreter;

    /**
     * Simple embedded WLST example that will connect WLST to a running server,
     * create two servers, and assign them to a newly created cluster and exit.
     * <p>Title: EmbeddedWLST.java</p>
     * <p>Copyright: Copyright (c) 2004</p>
     * <p>Company: BEA Systems</p>
     * @author Satya Ghattu (sghattu@bea.com)
     */

    public class EmbeddedWLST 
    {
      static InteractiveInterpreter interpreter = null;

      EmbeddedWLST() {
        interpreter = new WLSTInterpreter();
      }

    private static void connect() {
        StringBuffer buffer = new StringBuffer();
        buffer.append("connect('weblogic','weblogic')"); 
        interpreter.exec(buffer.toString());
      }

    private static void createServers() {
        StringBuffer buf = new StringBuffer();
        buf.append(startTransaction());
        buf.append("man1=create('msEmbedded1','Server')\n");
        buf.append("man2=create('msEmbedded2','Server')\n");
        buf.append("clus=create('clusterEmbedded','Cluster')\n");
        buf.append("man1.setListenPort(8001)\n");
        buf.append("man2.setListenPort(9001)\n");
        buf.append("man1.setCluster(clus)\n");
        buf.append("man2.setCluster(clus)\n");
        buf.append(endTransaction());
        buf.append("print ‘Script ran successfully ...’ \n");
        interpreter.exec(buf.toString());
      }

    private static String startTransaction() {
        StringBuffer buf = new StringBuffer();
        buf.append("edit()\n");
        buf.append("startEdit()\n");
        return buf.toString();
      }

    private static String endTransaction() {
        StringBuffer buf = new StringBuffer();
        buf.append("save()\n");
        buf.append("activate(block='true')\n");
        return buf.toString();
      }

      public static void main(String[] args) {
        new EmbeddedWLST();
        connect();
        createServers();
      }
    }


    Main Steps for Using WLST


    The following sections summarize the steps for setting up and using WLST:


    Setting Up Your Environment


    To set up your environment for WLST:

    1. Install and configure the WebLogic Server software, as described in the WebLogic Server Installation Guide.
    2. Add WebLogic Server classes to the CLASSPATH environment variable and WL_HOME\server\bin to the PATH environment variable, where WL_HOME refers to the top-level installation directory for WebLogic Server.

    3. You can use a WL_HOME\server\bin\setWLSEnv script to set both variables.


      On Windows, a shortcut on the Start menu sets the environment variables and invokes WLST (ToolsArrow symbolWebLogic Scripting Tool).


    Invoking WLST


    To invoke WLST:

    1. If you will be connecting to a WebLogic Server instance through an SSL listen port on a server that is using the demonstration SSL keys and certificates, invoke WLST using the following command:

    2. java -Dweblogic.security.SSL.ignoreHostnameVerification=true -Dweblogic.security.TrustKeyStore=DemoTrust weblogic.WLST


      Otherwise, at a command prompt, enter one of the following commands:

      • java weblogic.WLST
      • java weblogic.WLST -loadProperties propertyFilename
      • Note:You can use the -loadProperties option to loads property values from a file and make them available in a WLST session. The usage of this option is similar to the usage of the loadProperties command. For more information, see loadProperties


        A welcome message and the WLST prompt appears:


        wls:/(offline)>

    3. To use WLST offline, enter commands, set variables, or run a script at the WLST prompt.

    4. For more information, see Creating and Configuring WebLogic Domains Using WLST Offline.


      To use WLST online, start a WebLogic Server instance (see
      Starting and Stopping Servers
      ) and connect WLST to the server using the connect command.


      wls:/(offline)> connect('username','password','t3s://localhost:7002')
      Connecting to weblogic server instance running at t3s://localhost:7002 as username weblogic ...
      Successfully connected to Admin Server 'myserver' that belongs to domain 'mydomain'.


      wls:/mydomain/serverConfig>

      Note:BEA Systems strongly recommends that you connect WLST to the server through an SSL port or the administration port. If you do not, the following warning message is displayed:

    Note:Warning: An insecure protocol was used to connect to the server.
    To ensure on-the-wire security, the SSL port or Admin port should be used instead.


    For detailed information about the connect command, see connect.


    Requirements for Entering WLST Commands


    Follow these rules when entering WLST commands. Also see WLST Command and Variable Reference and WLST Online and Offline Command Summary.

    • Command names and arguments are case sensitive.
    • Enclose arguments in single or double quotes. For example, 'newServer' or "newServer".
    • If you specify a backslash character (\) in a string, for example when specifying a file pathname, you should precede the quoted string by r to instruct WLST to interpret the string in its raw form and ensure that the backslash is taken literally. This format represents standard Jython syntax. For example:
    • readTemplate(r'c:\mytemplate.jar')
    • When using WLST offline, the following characters are not valid in object names: period (.), forward slash (/), or backward slash (\).

    • If you need to cd to an object name that includes a forward slash (/) in its name, include the configuration object name in parentheses. For example:


      cd('JMSQueue/(jms/REGISTRATION_MDB_QUEUE)')

    • Display help information for WLST commands by entering the help command. See Getting Help.


    Securing Access to Security Data


    The user names and passwords of WebLogic Server users, security groups, and security roles are not stored in a domain’s XML configuration documents. Instead, a domain uses a separate software component called an Authentication provider to store, transport, and provide access to security data. Authentication providers can use different types of systems to store security data. The Authentication provider that WebLogic Server installs uses an embedded LDAP server.


    When you use WLST offline to create a domain template, WLST packages the Authentication provider’s data store along with the rest of the domain documents. If you create a domain from the domain template, the new domain has an exact copy of the Authentication provider’s data store from the domain template.


    You cannot use WLST offline to modify the data in an Authentication provider’s data store.


    You can, however, use WLST online to interact with an Authentication provider and add, remove, or modify users, groups, and roles. For more information, see Managing Security.


    Running Scripts


    WLST incorporates two Jython functions that support running scripts:


    To run the script examples in this guide, copy and save the commands in a text file with a .py file extension, for example, filename.py. Use the text file with the commands for running scripts that are listed below. There are sample scripts that you can use as a template when creating a script.py file from scratch. For more information, see WLST Sample Scripts.


    If the script will connect WLST to a running server instance, start WebLogic Server before running the script.


    Invoke WLST and Run a Script


    The following command invokes WLST, executes the specified script, and exits the WLST scripting shell. To prevent exiting WLST, use the -i flag.


    java weblogic.WLST filePath.py
    java weblogic.WLST -i
    filePath.py

    Note:If a WLST script named wlstProfile.py exists in the directory from which you invoke WLST or in user.home (the home directory of the operating system user account as determined by the JVM), the commands will be executed automatically once WLST is invoked. In this case, you do not need to specify the name of the WLST script file on the command-line.


    For example:


    c:\>java weblogic.WLST c:/temp/example.py
    Initializing WebLogic Scripting Tool (WLST) ...
    starting the script ...
    ...


    Run a Script From WLST


    Use the following command to execute the specified script after invoking WLST.

    execfile(filePath)


    For example:


    c:\>java weblogic.WLST
    Initializing WebLogic Scripting Tool (WLST) ...
    ...
    ...
    wls:/(offline)>
    execfile('c:/temp/example.py')
    starting the script ...
    ...


    Importing WLST as a Jython Module


    Advanced users can import WLST from WebLogic Server as a Jython module. After importing WLST, you can use it with your other Jython modules and invoke Jython commands directly using Jython syntax.


    The main steps include converting WLST definitions and method declarations to a .py file, importing the WLST file into your Jython modules, and referencing WLST from the imported file.


    To import WLST as a Jython module:

    1. Invoke WLST.

    2. c:\>java weblogic.WLST
      wls:/(offline)>

    3. Use the writeIniFile command to convert WLST definitions and method declarations to a .py file.

    4. wls:/(offline)> writeIniFile("wl.py")
      The Ini file is successfully written to wl.py
      wls:/(offline)>

    5. Open a new command shell and invoke Jython directly by entering the following command:

    6. c:\>java org.python.util.jython


      The Jython package manager processes the JAR files in your classpath. The Jython prompt appears:


      >>>

    7. Import the WLST module into your Jython module using the Jython import command.

    8. >>>import wl

    9. Now you can use WLST methods in the module. For example, to connect WLST to a server instance:

    10. wl.connect('username','password')
      ....

      Note:When using WLST as a Jython module, in all WLST commands that have a block argument, block is always set to true, specifying that WLST will block user interaction until the command completes. See WLST Command and Variable Reference.


    Exiting WLST


    To exit WLST:

    wls:/mydomain/serverConfig> exit()
    Exiting WebLogic Scripting Tool ...
    c:\>


    Running WLST from Ant


    The wlst Ant task is predefined in the version of Ant shipped with WebLogic Server and enables you to run WLST scripts from within your Ant build file.

    Note:If you want to use the task with your own Ant installation, add the following task definition in your build file:

    Note:<taskdef name="wlst" classname="weblogic.ant.taskdefs.management.WLSTTask" />


    To run WLST from an Ant script:

    1. Set your environment in a command shell.
      • On Windows NT, execute the setWLSEnv.cmd command, located in the directory WL_HOME\server\bin, where WL_HOME is the top-level directory of your WebLogic Server installation.
      • On UNIX, execute the setWLSEnv.sh command, located in the directory WL_HOME/server/bin, where WL_HOME is the top-level directory of your WebLogic Server installation.
    2. Add a call to the wlst Ant task to execute WLST commands. For example:
    3. <target name="runwlst"> 
         <wlst fileName="./myscript.py" executeScriptBeforeFile="true"
          debug="false" failOnError="false"> 
           <script>
              connect('weblogic','weblogic','t3://localhost:7001') 
           </script>
         </wlst>
      </target>


      Using the wlst Ant task, you can specify WLST commands within a WLST script, using the fileName attribute, or embed WLST script commands inside the build file, within the <script> tags. For more information about the Ant task command syntax, see wlst Ant Task Syntax.

    4. Execute the Ant task or tasks specified in the build.xml file by typing ant in the staging directory, optionally passing the command a target argument:
    5. prompt> ant runwlst

      Note:Use ant -verbose to obtain more detailed messages from the wlst task.


    wlst Ant Task Syntax


    The syntax of the wlst Ant task is as follows:

    <wlst properties="propsFile" fileName="fileName" arguments="arglist" failOnError="value" executeScriptBeforeFile="value" debug="value">
    <script>
       wlst-commands
    </script>


    You can specify WLST commands within a WLST script (.py) file and specify that file using fileName attribute, or embed WLST script commands inside the build file, enclosing them within the <script> tags.


    The following table defines the Ant task attributes that you can specify as part of the wlst Ant task.


    Table 2-1 Ant Task Attributes

    Attribute

    Definition 

    properties="propsFile"

    Optional. Name and location of the properties file that contains name-value pairs that you can reference in your script.

    fileName="fileName"

    Optional. Name and location of the WLST script file that you would like to execute. If the specified WLST script file does not exist, the wlst Ant task fails.

    arguments="arglist"

    Optional. List of arguments to pass to the script. These arguments are accessible using the sys.argv variable.

    failOnError="value"

    Optional. Boolean value specifying whether the Ant build script will fail if the wlst Ant task fails. This attribute defaults to true.

    executeScriptBeforeFile="value"

    Optional. Boolean value specifying whether the embedded script is executed before the specified WLST script file. This attribute defaults to true, specifying that the embedded script is executed first.

    debug="value"

    Optional. Boolean value specifying whether debug statements should be output when the WLST Ant Task is executed. This attribute defaults to false.

     


    Examples


    Example 1


    In the following example, the createServer target:

    • Executes the embedded script to connect to the server at t3://localhost():7001, edits the configuration to create a new server, and saves and activates the configuration changes. (Note that executeScriptBeforeFile is set to true, so the embedded script is executed first, before the specified WLST script file.)
    • Executes the WLST script file myscript.py that is located in the current directory.
    • Defines three arguments that are passed to the script. These arguments are accessible using the sys.argv variable.
    • Continues execution, as per the failOnError="false" setting, even if the wlst Ant task fails to execute.
    • Disables debugging.
    • <target name="configServer"> 
         <wlst debug="false" failOnError="false" executeScriptBeforeFile="true"  
          fileName="./myscript.py"> 
            <script>
               connect('weblogic','weblogic','t3://localhost:7001') 
           </script> 
         </wlst> 
      </target> 

    Example 2


    In the following example, the loop target:

    • Executes the WLST script file myscript.py in the current directory. (Note that executeScriptBeforeFile is set to false, so the WLST script file is executed first, before the embedded script.)
    • Executes the embedded script to connect to the server at t3://localhost():7001 and access and print the list of servers in the domain.
    • Results in a build failure if the wlst task fails to execute, as per the failOnError="true" setting.
    • Enables debugging.
    • <target name="loop"> 
         <wlst debug="true" executeScriptBeforeFile="false" 
          fileName="./myscript.py" failOnError="true"> 
            <script>
               print 'In the target loop' 
               connect('weblogic','weblogic','t3://localhost:7001') 
               svrs = cmo.getServers() 
               print 'Servers in the domain are' 
               for x in svrs: print x.getName()
            </script>
         </wlst> 
      </target> 

    Example 3


    In the following example, the error target:

    • Executes the embedded script to print the variable, thisWillCauseNameError.
    • Continues execution, as per the failOnError="false" setting, even if the thisWillCauseNameError variable does not exist and the wlst Ant task fails to execute.
    • Enables debugging.
    • <target name="error"> 
         <wlst debug="true" failOnError="false"> 
            <script>print thisWillCauseNameError</script> 
         </wlst> 
      </target>


    Getting Help


    To display information about WLST commands and variables, enter the help command.


    If you specify the help command without arguments, WLST summarizes the command categories. To display information about a particular command, variable, or command category, specify its name as an argument to the help command. To list a summary of all online or offline commands from the command line using the following commands, respectively:

       help('online')
       help('offline')


    The help command will support a query; for example, help('get*') displays the syntax and usage information for all commands that begin with get.


    For example, to display information about the disconnect command, enter the following command:


    wls:/mydomain/serverConfig> help('disconnect')


    The command returns the following:


    Description:
    Disconnect from a weblogic server instance.


    Syntax:
    disconnect()


    Example:
    wls:/mydomain/serverConfig>
    disconnect()



    Recording User Interactions


    To start and stop the recording of all WLST command input, enter:


    startRecording(recordFilePath,[recordAll])
    stopRecording()


    You must specify the file pathname for storing WLST commands when you enter the startRecording command. You can also optionally specify whether or not you want to capture all user interactions, or just the WLST commands; the recordAll argument defaults to false.


    For example, to record WLST commands in the record.py file, enter the following command:


    wls:/mydomain/serverConfig> startRecording('c:/myScripts/record.py')


    For more information, see startRecording and stopRecording.



    Redirecting WLST Output to a File


    To start and stop redirecting WLST output to a file, enter:


    redirect(outputFile,[toStdOut])
    stopRedirect()


    You must specify the pathname of the file to which you want to redirect WLST output. You can also optionally specify whether you want WLST output to be sent to stdout; the toStdOut argument defaults to true.


    For example, to redirect WLST output to the logs/wlst.log file in the current directory and disable output from being sent to stdout, enter the following command:

    wls:/mydomain/serverConfig> redirect('./logs/wlst.log', 'false')

    Note:There are some operations that are not redirected by WLST. For example, WLST does not redirect messages output from the Jython layer.


    For more information, see redirect and stopRedirect.



    Converting an Existing Configuration into a WLST Script


    To convert an existing server configuration (config directory) to an executable WLST script, enter:

    configToScript([domainDir], [scriptPath], [overwrite], [propertiesFile], [deploymentScript])


    You can optionally specify:

    • The domain directory that contains the configuration that you want to convert (defaults to ./config)
    • The path to the directory in which you want to write the converted WLST script (defaults to ./config/config.py)
    • Whether to overwrite the script if it already exists (defaults to true)
    • The path to the directory in which you want to store the properties file (defaults to pathname specified for scriptPath)
    • Whether to create a script that performs deployments only (defaults to false)

    Note:configToScript() creates ancillary user-config and user-key files to hold encrypted attributes.


    You can use the resulting script to re-create the resources on other servers. Before running the generated script, you should update the properties file to specify values that are appropriate for your environments. When you run the generated script:

    • If a server is currently running, WLST will try to connect using the values in the properties file and then run the script commands to create the server resources.
    • If no server is currently running, WLST will start a server with the values in the properties file, run the script commands to create the server resources, and shutdown the server. This may cause WLST to exit from the command shell.


    For example, the following command creates a WLST script from the domain located at c:/bea/user_projects/domains/mydomain, and saves it to c:/bea/myscripts.


    wls:/(offline)> configToScript('c:/bea/user_projects/domains/mydomain',
    'c:/bea/myscripts')


    For more information, see configToScript.



    Customizing WLST


    You can customize WLST using the WLST home directory, which is located at WL_HOME/common/wlst, by default, where WL_HOME refers to the top-level installation directory for WebLogic Server. All Python scripts that are defined within the WLST home directory are imported at WLST startup.

    Note:You can customize the default WLST home directory by passing the following argument on the command line:
    -Dweblogic.wlstHome=<another-directory>


    The following table describes ways to customize WLST.


    Table 2-2 Customizing WLST 

    To define custom...

    Do the following...

    For a sample s
  • 相关阅读:
    安卓强制杀死进程的几种方法收集汇总
    android studio :Timeout waiting to lock daemon addresses registry
    20170825遇到的问题
    百度地图的那些坑
    静态内部类的加载方式
    C#文本转语音并保存wav和MP3文件
    一个ASPX页面的生命周期?
    用SQL替换最后一个指定字符后面的所有字符
    用SQL求1到N的质数和
    谈谈托管代码、IL、CLR、ISAPI?
  • 原文地址:https://www.cnblogs.com/lexus/p/2372415.html
Copyright © 2020-2023  润新知