Oracle Weblogic password reset script

If you want to reset the ‘GOD’ password for Weblogic Server

Start the script and follow instructions

  <path_to_wlst>/wlst.sh resetWLS_password.py

Code for resetWLS_password.py

import datetime
import os
import random
import re
import string
import sys
import traceback

def tempname():
    return "/tmp/resetPassLog" + str(random.randint(1000, 9999))

def shout(cmd, check_returncode=False, check_output=False):
    tmpfile = tempname()
    retval = os.system(cmd + " >" + tmpfile + " 2>&1")
    file = open(tmpfile)
    out = file.read()
    file.close()
    os.system("rm -f " + tmpfile + " >/dev/null 2>&1")
    if check_returncode:
        if retval <> 0:
            print string.strip(out)
            raise Exception("Error: return code " + str(retval) + " from command: " + cmd)
    if check_output:
        if re.search(('ERROR|[Ee]rror|FAIL|[Ff]ail|TIMEOUT|[Tt]imeout'), out):
            print string.strip(out)
            raise Exception("Error message found from command: " + cmd)
    return string.strip(out)

def shlines(cmd):
    return string.split(shout(cmd), "\n")

# RETURN LIST OF PROCESS IDS FROM GREPING PROCESS COMMANDS
def psgrep(str):
    pat = re.compile(str)
    cmd = "ps -e -o pid,command"
    lines = shlines("ps -e -o pid,command")
    pids = []
    for line in lines:
        cols = string.split(line)
        if cols[1] == "grep": continue
        for col in cols[1:]:
            if pat.search(col):
                pids.append(cols[0])
                continue
    return pids
def stop_process_tree(ppid):
    java.lang.Thread.sleep(1)
    pids = get_child_processes(ppid)
    while len(pids) > 0:
        for pid in pids:
            stop_process_tree(pid)
        pids = get_child_processes(ppid)
    kill_process(ppid)
    return

def kill_process(pid):
    if pid == None or pid == '':
        return
    java.lang.Thread.sleep(1)
    if shout("ps -o pid= --pid " + pid) != '':
        os.system("kill " + pid)
    for i in range(30):
        java.lang.Thread.sleep(1)
        if shout("ps -o pid= --pid " + pid) == '':
            return
    os.system("kill -9 " + pid)
    for i in range(30):
        java.lang.Thread.sleep(1)
        if shout("ps -o pid= --pid " + pid) == '':
            return
    error("Cannot kill " + pid)
    return

def get_child_processes(ppid):
    return string.split(shout("ps -o pid= --ppid " + ppid))

#Stop adminserver
def stop_adminserver(name, domain_home):
    print "stopping adminserver " + name
    pids = psgrep("weblogic.Name=" + name)
    for pid in pids:
        stop_process_tree(pid)
    pids = psgrep(domain_home + "/startWebLogic.sh")
    for pid in pids:
        stop_process_tree(pid)
    pids = psgrep(domain_home + "/pointbase.ini")
    for pid in pids:
        stop_process_tree(pid)
    lok = domain_home + "/servers/" + name + "/tmp/" + name + ".lok"
    os.system("rm -f " + lok)
    print "stopped  adminserver " + name
    return ""

def start_adminserver(name, domain_home):
    if len(psgrep(domain_home + "/startWebLogic.sh")) > 0:
        print "adminserver " + name + " already running"
        return ""
    print "starting adminserver " + name
    scriptfile = domain_home + "/startAdminServer.sh"
    outfile = domain_home + "/nohup.out"
    file = open(scriptfile, "w")
    file.write("#!/bin/bash\n")
    file.write(domain_home + "/startWebLogic.sh >" + outfile + " 2>&1 &\n")
    file.close()
    os.system("rm -f " + outfile)
    os.system("chmod 0755 " + scriptfile)
    os.system(scriptfile)
    n = 1900
    while n > 0:
        n = n - 1
        java.lang.Thread.sleep(1)
        file = open(outfile, "r")
        text = file.read()
        file.close()
        if string.find(text, "Server state changed to RUNNING") > -1:
            print "started  adminserver " + name
            return ""
        if string.find(text, "Server state changed to FAILED") > -1:
            errmsg = "ERROR STARTING ADMIN SERVER " + name
            print errmsg
            return errmsg
    errmsg = "ERROR: timeout starting " + name
    return errmsg

##############################
print "Please enter domain data: "
now = datetime.datetime.now()
adminUser = raw_input("Enter Admin user: ")
oldAdminPassword = raw_input("Enter OLD password: ")
newAdminPassword = raw_input("Enter NEW password: ")
url = raw_input("Please, enter url (t3 or http): ")

print "Connection to Oracle Weblogic Adminserver"
connect(adminUser, oldAdminPassword, url)
domainName=cmo.getName()
domainHome = cmo.getRootDirectory()
adminServerName = cmo.getAdminServerName()

cd('/SecurityConfiguration/'+domainName+'/Realms/myrealm/AuthenticationProviders/DefaultAuthenticator')
cmo.resetUserPassword(adminUser,newAdminPassword)
disconnect()
print "Adminpassword succesfully changed"
print "Connecting Using New Credentials....."
connect(adminUser,newAdminPassword,url)
print "Successfully Connected Using New Credentials !!!!"
disconnect()

print " Resetting boot.properties "
bootfile = domainHome + "/boot.properties"
f = open(bootfile, "w")
bootfilestr = "Password file changed by reset adminpass script on " + str(now) + "\n"
bootfilestr += "username=" + adminUser + "\n"
bootfilestr += "password=" + newAdminPassword
f.write(bootfilestr)
f.close()
print "Boot.properties succesfully set"
stop_adminserver(adminServerName, domainHome)
os.system("rm " + domainHome + "/servers/" + adminServerName + "/security/boot.properties")
os.system("cp " + bootfile + " " + domainHome + "/servers/" + adminServerName + "/security/")
start_adminserver(adminServerName, domainHome)

Jdeveloper: Remove/edit subversion repo connection

To remove a subversion connection from your jdeveloper installation do this:

1. Navigate to
D:\oracle\middleware\jdeveloper\jdev\bin\Developjdev\system11.1.1.5.37.60.13\o.jdeveloper.subversion

2. Edit or remove the file repositories.xml

 

Oracle Virtual Box Kernel driver not installed (rc=-1908)

To solve this problem run this script as root:

#!/bin/bash
sudo apt-get install linux-headers-$(uname -r)
sudo apt-get remove virtualbox-dkms
sudo apt-get install virtualbox-dkms

Java -xmx -xms total memory set in bash

Use following commands to know how much memory all java processes take of your Linux server with bash. Handy for Oracle Weblogic administrators:

MINIMUM

[oracle@heuring.com ~]$ ps -ef | grep -oh 'Xms[0-9]*' | cut -d's' -f2 | awk '{SUM += $1} END { print SUM}'

MAXIMUM

[oracle@heuring.com ~]$ ps -ef | grep -oh 'Xmx[0-9]*' | cut -d'x' -f2 | awk '{SUM += $1} END { print SUM}'

 

Expanding Oracle Enterpise Repository

A nice tool to expand you’re Oracle Repository with functional documentation by Marc Kuijpers:

https://blogs.oracle.com/soacommunity/entry/expanding_the_oracle_enterprise_repository

Oracle JDBC URL types

In Oracle Weblogic we define an url for every datasource. Hereby an overview of the different types URL’s. Note the database service name which points to the RAC listeners.

Simple JDBC Connection String

jdbc:oracle:thin:@localhost:1521:xe

Load-Balanced JDBC Connection String

jdbc:oracle:thin:@(description=(address_list=
(load_balance=on)
(failover=on)
(address=(protocol=tcp)(host=dev-database-2.org.com)(port=1521))
(address=(protocol=tcp)(host=dev-database-2.org.com)(port=1521)))
(connect_data=(service_name=rac1)))

Failover JDBC Connection String

jdbc:oracle:thin:@(description=(address_list=
(load_balance=off)
(failover=on)
(address=(protocol=tcp)(host=dev-database-2.org.com)(port=1521))
(address=(protocol=tcp)(host=dev-database-2.org.com)(port=1521)))
(connect_data=(service_name=rac1)))

Oracle Weblogic WLST console helper!!!

Every Weblogic administrator or WLST developer get’s at some point, close by a psychopathic brain state when using the WLST console. backspaces, arrows and other stuff work like an old school unix server.
The solution: Jline:

To use JLIne with WLST, follow these steps.

  1. Download JLine from http://jline.sourceforge.net/downloads.html
  2. Unzip the file and put the jline jar (current version is jline-0.9.94.jar) into a directory on your machine.
  3. Add the jline jar (current version is jline-0.9.94.jar) to the CLASSPATH
  4. Run JLine as follows:
    java jline.ConsoleRunner weblogic.WLST
    Alternatively, you can copy the $WL_HOME/common/bin/wlst.sh and then add jline.ConsoleRunner before weblogic.WLST

Oracle Weblogic nodemanager STOP script Bash and Python

Everyone who is using Oracle Weblogic must had a thought like  “Where the *** is the stop script to kill my nodemanager proces”…. Well, i did. So i wrote a simple stop script which can be better probally, but it does the job.

#!/bin/bash
PID=`ps -efw | grep -i "Xms128m" | grep -i nodemanager | awk '{print $2}'`
if [ ! -z $PID  ]; then
  echo "Killing nodemanager with PID: $PID"
  kill $PID
  CHECK=`ps -e -o pid | grep $PID`
  if [ -z $CHECK ]; then
    echo "Nodemanager stop success"
  fi
else
  echo "No nodemanager process running"
fi

Remember to copy this snippet into a bash file and set the correct permissions.

Some developers like to stop nodemanager programmaticly. I.E.
Note: You could use it to stop and start adminservers for example…
You could use following python definitions:

# RETURN LIST OF PROCESS IDS FROM GREPING PROCESS COMMANDS
def psgrep(str):
    pat = re.compile(str)
    cmd = "ps -e -o pid,command"
    lines = shlines("ps -e -o pid,command")
    pids = []
    for line in lines:
        cols = string.split(line)
        if cols[1] == "grep": continue
        for col in cols[1:]:
            if pat.search(col):
                pids.append(cols[0])
                continue
    return pids

def stop_process_tree(ppid):
    time.sleep(1)
    pids = get_child_processes(ppid)
    while len(pids) > 0:
        for pid in pids:
            stop_process_tree(pid)
        pids = get_child_processes(ppid)
    kill_process(ppid)
    return

def kill_process(pid):
    if pid == None or pid == '':
        return
    time.sleep(1)
    if shout("ps -o pid= --pid " + pid) != '':
        os.system("kill " + pid)
    for i in range(30):
        time.sleep(1)
        if shout("ps -o pid= --pid " + pid) == '':
            return
    os.system("kill -9 " + pid)
    for i in range(30):
        time.sleep(1)
        if shout("ps -o pid= --pid " + pid) == '':
            return
    error("Cannot kill " + pid)
    return

def get_child_processes(ppid):
    return string.split(shout("ps -o pid= --ppid " + ppid))

Oracle Weblogic mail sessions

Sometimes it’s handy to send mail reports from your newly created application… If we choose to do so and we have the expensive obligation of using $$ Oracle Weblogic in our project, we sure can use it 🙂

You need two things:

  1. A J2EE java application with JavaMail
  2. A Weblogic domain which is the container for the application

1. The java snippet


public class RepportMailArchiveerder implements IRapportArchiveerder{
    private static final Logger logger = Logger.getLogger(RepportMailArchiveerder.class);

    public RepportMailArchiveerder() {
        super();
    }

    /**
     * Send email.
     */
    public void mail(Rapport rapport){

        String content = rapport.toString();

        try {
            // Lookup the WLS context
            InitialContext ic = new InitialContext();
            Session session = (Session) ic.lookup("myTestMailSetup");

            //Construct the email
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(session.getProperty("mail.from")));
          msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(session.getProperty("mail.to"), false));
            msg.setSubject(session.getProperty("mail.subject"));
            msg.setText(content);
            Transport.send(msg);
        } catch (MessagingException mex) {
            logger.error("Send mail error: " + mex);
            } catch (NamingException ne){
                ne.getMessage();
            }
    }
}

2. The WLS configuration : SERVICES >> MAIL SESSIONS


Control Oracle HTTP server with EM

A nice feature of EM is the metric gathering and control of Oracle HTTP server. If you follow the standard installation method provided by the Oracle ‘bugy’ wizards, you could have troubles with EM and oracle HTTP server.

Most of the time the HTTP server is not registered with the EM console to gather state information.

The reason:

[wc_dev_adminserver] [NOTIFICATION:32] [] [oracle.sysman.emas.sdk.discovery.discover.WeblogicTargetDiscovery] [tid: [ACTIVE].ExecuteThread: '4' for queue: 'weblogic.kernel.Default (self-tuning)'] [userId: weblogic] [ecid: fe7afd919a7a61df:-1896f1d5:13739376179:-8000-0000000000000ad7,0] [APP: em] Failed to get Attributes:[[javax.management.InstanceNotFoundException: Unable to contact MBeanServer fororacle.as.management.mbeans.register:type=SystemComponent,
name=/instance1/ohs1,instance=instance1,component=ohs1,
Location=AdminServer,EMTargetType=oracle_apache at weblogic.rmi.internal.ServerRequest.sendReceive(ServerRequest.java:205)

...

As you can see, the location of the OHS is not correct defined.

Solution:
We need to delete and redeploy the system components. Make sure AdminServer is up and running at the time you do this.
Run the commands below on the OHS server. Make sure you use your correct instancename.

cd /apps/oracle/middleware/Oracle_WT1/instances/instance1/bin

echo -n unregister the OHS in EM
./opmnctl unregisterinstance -instanceName ohs1 -adminHost 145.83.73.5 -adminPort 8100

echo -n redeply to the EM adminserver
./opmnctl redeploy -adminHost 145.83.73.5 -adminPort 8100

echo -n register instance in EM
./opmnctl registerinstance -adminHost 145.83.73.5 -adminPort 8100

The Result: