Arquivo

Archive for the ‘wlst’ Category

Stop Start Weblogic Server

Recentemente fiz um script para parar e iniciar todos servers de um domínio weblogic, bem mais complexo pois tinha cluster e dois node Manager, era necessário subir cada Node depois conectar via node e subir todos servidores da lista de Mbeans do AdminServer.

Esse script você coloca o nome de um servidor específico e ele faz o Stop e Start via AdminServer.

  1. cria-se um arquivo restartServer.py com o seguinte conteúdo:

    import getopt
    ################################################################
    # Script para reniciar um server do weblogic.
    ################################################################
    # 1 – Conecta no AdminServer
    # 2 – Para o servidor
    # 3 – Inicia o servidor
    #
    # @author Herivelto Gabriel
    # @Date Abril/2014
    ###############################################################

    ################################################################
    # Variaveis.
    ################################################################
    adminusername=’weblogic’
    adminpassword=’weblogic11′
    adminurl=’t3://172.18.4.62:7001′
    serverRestart=’Server-DB’

    ################################################################
    # Conecta no AdminServer entra em runtime e ler o server
    ################################################################

    connect(adminusername, adminpassword, adminurl)
    domainRuntime()

    ################################################################
    # STOP – Server
    ################################################################
    bean = getMBean(‘ServerRuntimes/’ + serverRestart)
    if bean:
    print ”
    print ‘======================================’
    print ‘ STOP Server, Please wait……….!!!’
    print ‘======================================’
    shutdown(serverRestart, ‘Server’ , force=’true’)
    print ‘======================================’
    print ‘ START Server, Please wait…………….!!!’
    print ‘======================================’
    start(serverRestart, ‘Server’, block=’true’)
    print ‘======================================’
    print ‘Started Server ‘ + serverRestart
    print ‘======================================’
    print ”
    print ”

    ################################################################
    # START – Server
    ################################################################

    bean = getMBean(‘ServerRuntimes/’ + serverRestart)
    if bean:
    print ‘Server ‘ + serverRestart + ‘ is ‘ + bean.getState()
    else:
    print ”
    print ‘======================================’
    print ‘ START Server, Please wait…………….!!!’
    print ‘======================================’
    start(serverRestart, ‘Server’, block=’true’)
    print ‘======================================’
    print ‘Started Server ‘ + serverRestart
    print ‘======================================’
    print ”
    print ”

    ################################################################
    # Desconecta e sai do script
    ################################################################
    disconnect()
    exit()

  2. Excutando o script:

    /var/Oracle/Middleware/wlserver/common/bin/wlst.sh restartServer.py

  3. Saída do Script:

    ===================================================
    STOP Server, Please wait……………..!!!
    ===================================================
    Shutting down the server Server-DB with force=true while connected to AdminServer …
    ===================================================
    START Server, Please wait…………….!!!
    ===================================================
    Starting server Server-DB ……………
    Server with name Server-DB started successfully
    ===================================================
    Started Server Server-DB !!
    ==================================================

Anúncios
Categorias:weblogic, wlst Tags:

Criar Dominio Weblogic 12 WLST

O weblogic 12c(12.1.2) não tem mais o modo console para instalação e nem criação de domínio. Fiz um script para criar domínio que simula um pouco o modo console como era nas versões anteriores.

  1. cria-se um arquivo createDomain.py com o seguinte conteúdo
    ###############################################################
    # Script para criar dominio weblogic 12c
    # Para : Oracle WebLogic 12c
    # Author : Herivelto Gabriel
    ###############################################################
      
    print'#========================================================'
    print'# Enter Weblogic Home: Ex: /var/Oracle/Middleware'
    print'#========================================================'
    print'
    WLHOME=raw_input('Please Enter Weblogic Home install: ') 
    print'
    #Ler o template padrão do weblogic
    readTemplate(WLHOME+'/wlserver/common/templates/wls/wls.jar')
     
    print'#========================================================'
    print'# Create Domain in Weblogic 12c.'
    print'#========================================================'
    print''
    cd('Servers/AdminServer')
    set('Name',"AdminServer")
    
    domainName=raw_input('Please Enter domain name: ')
    domainPath=raw_input('Please Enter the domain path: ')
    AdminListenAdr=raw_input('Please Enter Admin Listen Address: ')
    AdminListenPort=input('Please enter Admin listen Port: ')
     
    set('ListenAddress',AdminListenAdr)
    set('ListenPort', AdminListenPort)
    
    cd('/')
    cd('Security/base_domain/User/weblogic')
    usr=raw_input('Please Enter AdminUser Name: ')
    set('Name',usr)
    AdminPassword=raw_input('Please enter Admin password:')
    cmo.setPassword(AdminPassword)
     
    # - OverwriteDomain: Se existir dominio com o mesmo nome sobrescreve
    setOption('OverwriteDomain', 'true')
    print'' 
    print'# Please wait ... Creating Domain '
    print'' 
    writeDomain(domainPath+"/"+domainName)
    
    print'#========================================================'
    print'# Domain create with sucesso !' 
    print'#========================================================'
    print'' 
    print'Domain Name = ',domainName  
    print'Path Name = ', domainPath
    print'Username = ', usr
    print'Listern = ',AdminListenAdr
    print'Port = ', AdminListenPort
    print'' 
    print '#========================================================'
    
    closeTemplate()
    exit()
    
  2. Excutando o script:

      /var/Oracle/Middleware/wlserver/common/bin/wlst.sh createDomain.py
    
  3. Saída do Script:

    #========================================================
    # Enter Weblogic Home: Ex: /var/Oracle/Middleware
    #========================================================
    
    Please Enter Weblogic Home install: /var/Oracle/Middleware12
    
    #========================================================
    # Create Domain in Weblogic 12c.
    #========================================================
    
    Please Enter domain name: weblogic12c
    Please Enter the domain path: /var/Oracle/domains
    Please Enter Admin Listen Address: 192.168.14.129
    Please enter Admin listen Port: 7001
    Please Enter AdminUser Name: weblogic
    Please enter Admin password:weblogic12
    
    # Please wait ... Creating Domain 
    
    #========================================================
    # Domain create with sucesso !
    #========================================================
    
    Domain Name =  weblogic12c
    Path Name =  /var/Oracle/domains
    Username =  weblogic
    Listern =  192.168.14.129
    Port =  7001
    
    #========================================================
    
Categorias:weblogic, wlst Tags:,

Criar Usuarios no Weblogic com WLST

Criando usuários no Weblogic via script wlst no modo online.
O Script é composto de dois arquivos, um script.py e um arquivo.properties, o arquivo de properties é usado para definir as configurações do servidor e dos usuários a serem criados.

  1. criarUsuarios.properties
    #==================CRIAR USUARIOS ==================
    # Os tipos de GROUP_USER padrão do Weblogic são:
    # Monitors, Deployers, Administrators, AppTesters,
    # CrossDomainConnectors, AdminChannelUsers.
    #
    # @autor Herivelto Gabriel
    # em Fevereiro 2013
    #==================================================
    
    #Dados do Servidor
    DOMAIN_NAME=1033
    ADMIN_URL=t3://172.16.145.162:7001
    ADMIN_USERNAME=weblogic
    ADMIN_PASSWORD=weblogic11
    
    # Realm default do Weblogic
    SECURITY_REALM_NAME=myrealm
    
    #Para cada Usuario repetir esse bloco
    USER_1=deployer
    PASSWORD_USER_1=deploy
    DESCRIPTION_USER_1=Usuario deploy
    GROUP_USER_1=Deployers
    
    USER_2=Monitor
    PASSWORD_USER_2=Monitor
    DESCRIPTION_USER_2=Usuario Monitoracao
    GROUP_USER_2=Monitors
    #====================================================
  2. criarUsuarios.py

    #====================================================
    # Criar Usuarios no weblogic com configuracoes definidas em
    # criarUsuario.properties'
    #
    # @autor : Herivelto Gabriel
    # Fevereiro/2013
    #====================================================
    #imports
    from java.util import Properties
    from java.io import FileInputStream
    from java.io import File
    from java.util import Enumeration
    from string import split
    
    #=====================================================
    # CARREGA DADOS ARQUIVO PROPRIEDADES
    #=====================================================
    #arquivo de propriedades a ser carregado
    localizacaoArquivoPropriedadesConfiguracao = 'criarUsuario.properties'
    
    myProps = Properties()
    
    #carrega arquivo de propriedades
    myProps.load(FileInputStream(File(localizacaoArquivoPropriedadesConfiguracao)))
    
    #======================================================
    # SEPARA ELEMENTOS SERVIDOR DA LISTA DE PROPRIEDADES
    #======================================================
    
    usuarios = []
    propertyNames = myProps.propertyNames()
    
    while propertyNames.hasMoreElements():
    chave = propertyNames.nextElement()
    elemento = split(chave, '_')
    if elemento[0] == 'USER':
    usuarios.append(chave)
    
    print 'Os seguintes usuarios serao criado(s) aguarde....'
    
    for a in usuarios:
    print 'Nome do User ==>> ' + myProps.get(a)
    
    #======================================================
    #Connecta com o adminServer
    #======================================================
    def connection():
    
    print'\n========> START CONNECTING <==========' username = myProps.get('ADMIN_USERNAME') password = myProps.get('ADMIN_PASSWORD') url = myProps.get('ADMIN_URL') print 'Connecting as ', username ,' To WebLogic URL ', url ,'...' try: print'Connecting .......' connect(username, password, url) except WLSTException: print '==> Error Connecting to The URL ', url
    CancelEdit('y')
    exit()
    
    #=======================================================
    #Criando Usuarios
    #=======================================================
    
    domainName = myProps.get('DOMAIN_NAME')
    realmName = myProps.get("SECURITY_REALM_NAME")
    
    connection()
    serverConfig()
    
    for user in usuarios:
    userName = myProps.get(user)
    userPassword = myProps.get('PASSWORD_'+user)
    userDescription = myProps.get('DESCRIPTION_'+user)
    userGroupName = myProps.get('GROUP_'+user)
    #userGroup = myProps.get('GROUP_' + usuario)
    authenticatorPath= '/SecurityConfiguration/' + domainName + '/Realms/' + realmName + '/AuthenticationProviders/DefaultAuthenticator'
    cd(authenticatorPath)
    
    #CRIANDO USUARIO
    print '-------------------------------------'
    try:
    cmo.createUser(userName , userPassword , userDescription)
    print '- User Created : ',userName
    except WLSTException:
    print '* Check If the User With the Name : ' , userName ,' already Exists...'
    
    #ADICIONANDO USUARIO AO GRUPO
    try:
    cmo.addMemberToGroup(userGroupName,userName)
    print '- User Add in group : ',userGroupName
    except WLSTException:
    print '* Erro add user in group !: ',userGroupName
    
    print '-------------------------------------'
    
    #save()
    #activate(block="true")
    print ' '
    disconnect()
    print ' '
    
    #====================================================
    print '==> Finished ... Reloud and Check from AdminConsole...'
    #====================================================
  3. Executando o Script
../Oracle/Middleware/wlserver_10.3/common/bin/wlst.sh criarUsuario.py
Categorias:weblogic, wlst Tags:,

Descriptografando Senha Weblogic com WLST

Quando você não lembra a senha do weblogic, não desespere, existe algumas formas de recuperar a senha criptografada no config.xml.Vou mostrar uma forma utilizando o WLST, mais também pode utilizando java. Isso serve tanto para critografar como para decriptografar.

1. Copie esse código do Scritp wlst e salve como:

decryptPassword.py

 
#================================================================
# Decriptografar Senha do Weblogic
# 
# decryptPassword.py  
#
#================================================================
import os
import weblogic.security.internal.SerializedSystemIni
import weblogic.security.internal.encryption.ClearOrEncryptedService

def decrypt(domainHomeName, encryptedPwd):
    domainHomeAbsolutePath = os.path.abspath(domainHomeName)
    encryptionService = weblogic.security.internal.SerializedSystemIni.getEncryptionService(domainHomeAbsolutePath)
    ces = weblogic.security.internal.encryption.ClearOrEncryptedService(encryptionService)
    clear = ces.decrypt(encryptedPwd)
    print "RESULT:" + clear

try:
    if len(sys.argv) == 3:
        decrypt(sys.argv[1], sys.argv[2])
    else:
                print "INVALID ARGUMENTS"
                print " Usage: java weblogic.WLST decryptPassword.py  "
                print " Example:"
                print " java weblogic.WLST decryptPassword.py D:/Oracle/Middleware/user_projects/domains/base_domain {AES}819R5h3JUS9fAcPmF58p9Wb3syTJxFl0t8NInD/ykkE="
except:
    print "Unexpected error: ", sys.exc_info()[0]
    dumpStack()
    raise

2. Copie o arquivo decryptPassword.py para o dentro do diretório do seu wlst.sh

 
# cp decryptPassword.py /opt/Oracle/wlserver_10.3/common/bin

3. Copie o conteúdo do password criptografado que está no arquivo boot.properties

 
cat /opt/Oracle/1036/servers/AdminServer/security/boot.properties

#Mon Sep 10 00:50:24 EDT 2012
password={AES}za5Gi1OKSSoLf3wxbwhE+92rJwi5Vuy8zLxZf/rC99E\=
username={AES}fo+72/DBQpjinLmRcAve6wHz4JAr3XFZxuJ8Kav4aCk\=

4. Execute o Script passando o caminho do Domínio e o conteúdo a ser decriptografado

 
/opt/Oracle/wlserver_10.3/common/bin/wlst.sh decryptPassword.py /opt/Oracle/1036/ {AES}za5Gi1OKSSoLf3wxbwhE+92rJwi5Vuy8zLxZf/rC99E\=

A Saída mostra o valor do password decryptografado.

 

#Initializing WebLogic Scripting Tool (WLST) ...
#Welcome to WebLogic Server Administration Scripting Shell
#Type help() for help on available commands

RESULT:weblogic11



*Obs: Uma dica rápida é copiar os arquivos SerializedSystemIni.datconfig.xml utilizar o site de recover online, ele te mostra o usuário e senha desencriptando os arquivos: Veja o Site.

Categorias:weblogic, wlst Tags:,

WLST easeSyntax

Com WLST é muito chato ficar navegando pelos MBeans, pois sempre é necessário colocar parênteses nos comandos ( ) e aspas ‘ ‘, quando esquecemos é necessário redigitar todo comando novamente.

Encontrei um comando que ajuda muito na hora de navegar, ele elimina a necessidade de ‘parênteses e aspas’ depois de entrar no wlst digite:

 
wls:/offline>easeSyntax()

* Obs: Ele funciona bem quando você está navegando por comandos, não utilize em script wlst.py.

Categorias:weblogic, wlst Tags:,

WLST Stop Start Server

Script para Para e Iniciar um Server específico.

  1. startStop.py
  2.   
    
    #=============================================================
    # @author: Herivelto Gabriel
    #
    #=============================================================
    #Variaveils
    USUARIO_ADMIN='weblogic'
    PASSWORD_ADMIN='weblogic10'
    URL_ADMIN='t3://localhost:7001'
    #nome e porta do Server
    SERVER='Server-1'
    URL_SERVER='t3://localhost:8011'
    
    #=============================================================
    # connect adminServer
    #=============================================================
    def connection():
        try:
            connect(USUARIO_ADMIN,PASSWORD_ADMIN,URL_ADMIN)
        except WLSTException:
            print 'Error while shutting down Server',e
            exit()
    
    #=============================================================
    # Stop & Start Server
    #=============================================================
    
    connection()
    domainRuntime()
    
    mBean = cmo.lookupServerLifeCycleRuntime(SERVER)
    status = mBean.getState()
    
    #Testa se o server está rodando para Parar
    if status != 'RUNNING':
     shutdown(SERVER,force='true')
    elif status != 'SHUTDOWN' :
     start(SERVER,'Server',URL_SERVER)
    
    exit()
    #=============================================================
    
  3. Executando o Script
  4. Chama-se o script do weblogic wlst.sh e passa o nome do script com parâmetro. EX:

      
      ../Oracle/Middleware/wlserver_10.3/common/bin/wlst.sh startStop.py
    
  5. Start Stop automático com hora agendada
  6. Este script foi utilizado para fazer restart de um servidor todas as noites em um horário agendado, foi adicionado ao crontab do Solaris/linux

      
    #Parar o Servidor 02:00 e Iniciar 02:05
    00 02 *  *  * ../wlserver_10.3/common/bin/wlst.sh startStop.py 
    05 02 *  *  * ../wlserver_10.3/common/bin/wlst.sh startStop.py
    

    WLST Oracle Reference

Categorias:weblogic, wlst Tags:,

WLST Criar Clusters

Criando Cluster no Weblogic via script wlst no nodo online.

O Script é composto de dois arquivos um script.py e um arquivo.properties, esse arquivo properties é usado para definir as configurações de cada cluster.

  1. cluster.properties
  2. No Exemplo já temos um domínio weblogic (domain1)

      
    
    #==========================================================
    # @author : 
    # Herivelto Gabriel 
    #==========================================================
    
    USUARIO_ADMIN=weblogic
    SENHA_ADMIN=weblogic10
    ADMIN_SERVER_URL=t3://localhost:7001
    DIRETORIO_DOMINIO=/opt/Oracle/Middlewar1036/domains/domain1/
    
    #CLUSTER
    CLUSTER_1=cluster-linux
    
    CLUSTER_2=cluster-solaris
    
    CLUSTER_3=cluster-macos
    
    #==========================================================
    
    
  3. criarclusters.py
  4. O Script vai criar os clusters definidos no arquivo de properties:



      
    
    #==========================================================
    # @author : 
    # Herivelto Gabriel 
    #==========================================================
    from java.util   import Properties
    from java.io     import FileInputStream
    from java.io     import File
    from java.util   import Enumeration
    from string      import split
    
    #=========CARREGA DADOS ARQUIVO PROPRIEDADES===============
    #arquivo de propriedades a ser carregado
    localizacaoArquivoPropriedadesConfiguracao = 'cluster.properties'
    
    myProps = Properties()
    
    #carrega arquivo de propriedades
    myProps.load(FileInputStream(File(localizacaoArquivoPropriedadesConfiguracao)))
    
    #ler o Domínio
    readDomain(myProps.get('DIRETORIO_DOMINIO'))
    
    #========SEPARA ELEMENTOS DO ARQUIVO DE PROPRIEDADES ======
    cluters = []
    propertyNames = myProps.propertyNames()
    
    while propertyNames.hasMoreElements():
        chave = propertyNames.nextElement()
        elemento = split(chave, '_')
        if elemento[0] == 'CLUSTER':
            cluters.append(chave)
            
    print 'Lista de cluters a serem criado(s) aguarde....'
    for a in cluters:
        print 'Nome do Cluste == ' + myProps.get(a)
        
    
    #============ CRIACAO DOS CLUTERS  ========================
    print 'Iniciando configuração e criação dos Clusters ....'
    
    username = myProps.get('USUARIO_ADMIN')
    password = myProps.get('SENHA_ADMIN')
    adminServerURL = myProps.get('ADMIN_SERVER_URL')
    
    connect(username,password,adminServerURL);
    edit()
    startEdit()
    
    cd('/')
    
    for cluste in cluters:
        clusterName = myProps.get(cluste)
        print 'Criando cluster ...'+ clusterName
        
        clu = create(clusterName,'Cluster')
        clu.setClusterMessagingMode('unicast');
        clu.setClusterBroadcastChannel("channel-"+clusterName)            
        print''
        print'ClusterCriado com Sucesso !!'
    
    activate()
    #=================== FIM ================================
    
  5. Executando o Script
  6. Os dois arquivos (cluster.properties e criarClusters.py) devem está no mesmo diretório para a execução, chama-se o script do weblogic wlst.sh e passa o nome
    do script python com parâmetro. EX:

      
      ../Oracle/Middleware/wlserver_10.3/common/bin/wlst.sh criarclusters.py
    
Categorias:weblogic, wlst Tags:,