August 2025
M T W T F S S
 123
45678910
11121314151617
18192021222324
25262728293031

Categories

August 2025
M T W T F S S
 123
45678910
11121314151617
18192021222324
25262728293031

Resetting the root/postgres password for PostgreSQL

The following is required to reset the root/postgres user password for PostgreSQL. The distribution used in my example is CentOS 5.5 and PostgreSQL 8.4.

Note: By default there’s no password for the postgres user.

In step 2 and 5 you will most likely not be using “ident” but rather “password” or “md5?.

1. Shut down PostgreSQL

# service postgresql stop

2. Reset the authentication mechanism (assuming defaults are already being used)

Edit the /usr/lib/pgsql/data/pg_hba.conf file

# nano /usr/lib/pgsql/data/pg_hba.conf

Navigate down to the line that says

local all all ident

Edit it to

local all postgres trust

And now save the file.

3. Start PostgreSQL

# service postgresql start

4. Log in and change the password

# su - postgres
$ psql -d template1 -U postgres
alter user postgres with password 'new_password';

Or alternatively do it all in one go with the following command

> psql -U postgres template1 -c "alter user postgres with password 'new_password';"

5. Reverse the actions you did in step 2

Edit the /usr/lib/pgsql/data/pg_hba.conf file

# nano /usr/lib/pgsql/data/pg_hba.conf

Navigate down to the line that says

local all all trust

Edit it to

local all postgres ident

And now save the file.

6. Start PostgreSQL

# service postgresql start

Success!

View information about your BIOS from Linux using dmidecode

To get at this information we will use a utility called “dmidecode”. dmidecode is a tool for dumping a computer’s DMI (some say SMBIOS) table contents in a human-readable format.

On CentOS/RHEL/Fedora you may run the following to install it.

# yum install dmidecode

On Arch Linux you may run

# pacman -S dmidecode

The following examples will allow you to see a few important parts of information such as;

  • The manufacturer of your motherboard
  • What type of motherboard you have
  • The version of the BIOS running on your motherboard

To view the manufacturer and what type of motherboard you have, run the following

dmidecode --type system

Example

# dmidecode 2.11
SMBIOS 2.4 present.

Handle 0x0001, DMI type 1, 27 bytes
System Information
        Manufacturer: Gigabyte Technology Co., Ltd.
        Product Name: GA-MA78G-DS3H
        Version:
        Serial Number:
        UUID: 4E2F4100-0000-0000-0000-0000FFFFFFFF
        Wake-up Type: Power Switch
        SKU Number:
        Family:

Handle 0x0034, DMI type 32, 11 bytes
System Boot Information
        Status: No errors detected

To view the version of your BIOS you may run the following

#dmidecode --type bios

Example

# dmidecode 2.11
SMBIOS 2.4 present.

Handle 0x0000, DMI type 0, 24 bytes
BIOS Information
        Vendor: Award Software International, Inc.
        Version: FA
        Release Date: 09/19/2008
        Address: 0xE0000
        Runtime Size: 128 kB
        ROM Size: 1024 kB
        Characteristics:
                ISA is supported
                PCI is supported
                PNP is supported
                APM is supported
                BIOS is upgradeable
                BIOS shadowing is allowed
                Boot from CD is supported
                Selectable boot is supported
                BIOS ROM is socketed
                EDD is supported
                5.25"/360 kB floppy services are supported (int 13h)
                5.25"/1.2 MB floppy services are supported (int 13h)
                3.5"/720 kB floppy services are supported (int 13h)
                3.5"/2.88 MB floppy services are supported (int 13h)
                Print screen service is supported (int 5h)
                8042 keyboard services are supported (int 9h)
                Serial services are supported (int 14h)
                Printer services are supported (int 17h)
                CGA/mono video services are supported (int 10h)
                ACPI is supported
                USB legacy is supported
                AGP is supported
                LS-120 boot is supported
                ATAPI Zip drive boot is supported
                BIOS boot specification is supported
                Targeted content distribution is supported

Handle 0x0029, DMI type 13, 22 bytes
BIOS Language Information
        Language Description Format: Long
        Installable Languages: 3
                n|US|iso8859-1
                n|US|iso8859-1
                r|CA|iso8859-1
        Currently Installed Language: n|US|iso8859-1

There’s also additional options to use with dmidecode. You probably also want to try the following to get an idea of what type of information you can get your hands on.

#dmidecode --type keyword
Valid type keywords are:
  bios
  system
  baseboard
  chassis
  processor
  memory
  cache
  connector
  slot

Change the default MySQL data directory with SELinux enabled

This is a short article that explains how you change the default MySQL data directory and adjust SELinux to account for the changes. The article assumes that you’re running either RHEL, CentOS, Scientific Linux or Fedora with SELinux enabled. This works with the most recent EL (6.2) version.

We’ll be doing this in the following order.

  • Stopping the MySQL server
  • Create a new data directory and move the content from the old data directory
  • Correct the MySQL configuration file
  • Adjust SELinux parameters to accept our new change
  • Starting the MySQL server

Stopping the MySQL server

# service mysqld stop

Create a new data diretory and move the content from the old one

Creating a new data directory

# mkdir /srv/mysql/
# chown mysql:mysql /srv/mysql

Moving the original data files

 # mv /var/lib/mysql/* /srv/mysql/

Correct the MySQL configuration file

Edit the my.cnf file for your distribution. In my example it’s located in the /etc/mysql/ directory. RHEL/CentOS/Scientific Linux put the my.cnf file directly in /etc by default.

# nano /etc/mysql/my.cnf

Change

datadir=/var/lib/mysql

to

datadir=/srv/mysql

and

socket=/var/lib/mysql/mysql.sock

to

socket=/srv/mysql/mysql.sock

and save the file.

Adjust SELinux parameters to accept our new change

Should the following command output “Permissive” or “Disabled” then you may skip the details for SELinux.

# getenforce

Run the semanage command to add a context mapping for /srv/mysql.

# semanage fcontext -a -t mysqld_db_t "/srv/mysql(/.*)?"

Now use the restorecon command to apply this context mapping to the running system.

# restorecon -Rv /srv/mysql

Starting the MySQL server

# service mysqld start

Verifying access and connectivity

$ mysql -u root -p
mysql> show databases;

If this is working, you’re up and running. Should you get a message that says

ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’

then add the following to your /etc/my.cnf

[client]
socket = /srv/mysql/mysql.sock

Optionally you can just use

$ mysql -u root -p --protocol tcp

to avoid connecting via the socket.

Change the default SSH port and alter SELinux

Security through obscurity is not something one would generally recommend. But to thwart the effort of automated scanners changing the default OpenSSH port will yield you less pain in every day life. This will not fend off directed attacks or nullify vulnerabilities or bad security design.

Should you see an error message such as

shd[14221]: error: Bind to port 9898 on 192.168.0.50 failed: Permission denied

it indicates that the system prevented the daemon to bind that port. Most likely SELinux.

The instructions provided will be valid on Fedora 14/15, CentOS 6, RHEL 6, Scientific Linux 6 and newer versions.

To change the default SSH port you need to do the following.

  • Stop the SSH daemon
  • Alter the /etc/ssh/sshd_config with your new port
  • Alter the SELinux context with semanage
  • Start the SSH daemon

Stop the SSH daemon

# service sshd stop

Alter the /etc/ssh/sshd_config with your new port

Alter the configuration file with your favorite editor, in my case “nano”.

# nano /etc/ssh/sshd_config

Alter the port configuration parameter change the following line

Port 22

to

Port 9898

Alter the SELinux context with semanage

# semanage port -a -t ssh_port_t -p tcp 9898

Initially you would think the following would work. But it will not. For it to work you would have to alter the policy in the selinux-policy package, rebuild and install it. So skip it, but now you know why.

# semanage port -d -t ssh_port_t -p tcp 22

Start the SSH daemon

# service sshd start

Linux ACL

An access control list (ACL), with respect to a computer file system, is a list of permissions attached to an object. ACL allows you to grant or deny permissions for any user or group on a filesystem resource.

Enabling ACL

To enable ACL, edit your /etc/fstab file as such:

/dev/VolGroup00/LogVol00 /                       ext3    defaults,acl        1 1

Note: Moderm Redhat distributions enable ACL by default for the root filesystem.

Set ACL

To modify ACL use setfacl command. To add permissions use setfacl -m.

Add permissions to some user:

# setfacl -m "u:username:permissions"

or

# setfacl -m "u:uid:permissions"

Add permissions to some group:

# setfacl -m "g:groupname:permissions"

or

# setfacl -m "g:gid:permissions"

Add default ACL:

# setfacl -d -m "u:uid:permissions"

Remove all permissions:

# setfacl -b

Remove each entry:

# setfacl -x "entry"

To check permissions use:

# getfacl filename

Examples

Set read,write and execute permissions for user “johndoe” on the file named “abc”.

# setfacl -m "u:johndoe:rwx" abc

Check permissions.

# getfacl abc
# file: abc
# owner: someone
# group: someone
user::rw-
user:johny:rwx
group::r--
mask::rwx
other::r--

Change permissions for user “johndoe”.

# setfacl -m "u:johndoe:rw-" abc

Check permissions.

# getfacl abc
# file: abc
# owner: someone
# group: someone
user::rw-
user:johndoe:rw-
group::r--
mask::r-x
other::r--

Remove all extended ACL entries.

# setfacl -b abc

Check permissions.

# getfacl abc
# file: abc
# owner: someone
# group: someone
user::rw-
group::r--
other::r--

Additional Resources

man getfacl
man setfacl

Disable the filesystem check (fsck) at boot time

There’s several ways of accomplishing this. I will list all the methods beneath, just pick the one that fits the situation/you.

  • Filesystem tunable
  • Grub boot parameter
  • Placing command files on your root device
  • Active reboot without FSCK

Filesystem tunable

Use the tune2fs command to tell your filesystem to have a max count of mounts before a check to 0 to disable it.

# tune2fs -c 0 /dev/sda1

Parameter reference:

-c max-mount-counts
 Adjust the number of mounts after which the filesystem will be  checked  by  e2fsck(8).   If max-mount-counts  is  0  or -1, the number of times the filesystem is mounted will be disregarded by e2fsck(8) and the kernel.

Grub boot parameter

Add the following at the end of your grub boot linux line.

fastboot

This can be done by editing “grub.conf” or by editing the boot command via the grub menu at boot.

Placing command files on your root device

To disable the filesystem check on boot.

# touch /fastboot

To enable a filesystem check on boot.

# touch /forcefsck

Active reboot without FSCK

# shutdown -rf

Parameter reference:

-r     Reboot after shutdown.
-f     Skip fsck on reboot.

Setting up a 2-node GlusterFS file-system

This will be a quick howto on how you would set up a 2-node GlusterFS filesystem. You may look up more information at http://www.gluster.org/.

Volume types for GlusterFS

– Distributed. Distributed volumes distributes files throughout the bricks in the volume
– Replicated. Replicated volumes replicates files across bricks in the volume
– Striped. Striped volumes stripes data across bricks in the volume
– Distributed Striped. Distributed striped volumes stripe data across two or more nodes in the cluster
– Distributed Replicated. Distributed replicated volumes distributes files across replicated bricks in the volume
– Distributed Striped Replicated. Distributed striped replicated volumes distributes striped data across replicated bricks in the cluster
– Striped Replicated. Striped replicated volumes stripes data across replicated bricks in the cluster

The high level overview of how the process will be is as follows
•Installing the required software
•Disable or add proper firewall rules
•Adding nodes into the cluster
•Preparing “bricks” for use on each server
•Creating and starting the actual GlusterFS volume
•Mounting the GlusterFS volume

Installing the required software

I will be providing examples for CentOS, Fedora, Debian and Arch Linux. The examples for CentOS will work for RHEL and Scientific Linux as well.
CentOS
The following command will install all dependencies.
# yum install glusterfs

Fedora
The following command will install all dependencies.
# yum install glusterfs-server

Debian
The following command will install all dependencies.
# apt-get install glusterfs-server

Arch Linux
The following command will install all dependencies.
# pacman -S glusterfs

Disable or add proper firewall rules

You will need to open the following ports for GlusterFS.
24007 – GlusterFS Daemon
24008 – Management
24009 – Each brick for every volume on your host requires it’s own port. For every new brick, one new port will be used starting at 24009. (For GlusterFS versions earlier than 3.4)
49152 – Each brick for every volume on your host requires it’s own port. For every new brick, one new port will be used starting at 49152 (GlusterFS 3.4 and later)
38465:38467 – This is required if you use the GlusterFS NFS service.

CentOS
Disabling the default firewall
# chkconfig iptables off
# service stop iptables

Fedora
systemctl disable firewalld
systemctl stop firewalld

Debian
There are no default firewall installed on Debian.
Arch Linux
There are no default firewall installed on Arch Linux.

Adding nodes into the cluster

This is incredibly easy. You may do the following command from either server. In my example I am on server1. If you don’t have a solid DNS you should add each server to each others hosts file.
# gluster peer probe server2
Probe successful

Preparing “bricks” for use on each server

Nothing fanzy, you just need to create folders. It’s also important to note that you will need to use a folder, even if you intended to use a single disk.
Execute the following on both of your servers
# mkdir -p /data/brick>

Creating and starting the actual GlusterFS volume

Creating the GlusterFS volume
Syntax:
gluster volume create NEW-VOLNAME [replica COUNT] [transport [tcp | rdma | tcp,rdma]] NEW-BRICK…

Example:
# gluster volume create test-volume replica 2 transport tcp server1:/data/brick server2:/data/brick
Creation of test-volume has been successful
Please start the volume to access data.

Starting the GlusterFS volume
# gluster volume start test-volume

Mounting the GlusterFS volume

It’s important to note that you will need to mount the GlusterFS to use it. WARNING: Adding files directly to a brick will not be included in a GlusterFS volume.
Syntax:
# mount.glusterfs servername:volumename /mnt/mountpoint

Examples:
# mount.glusterfs server1:test-volume /mnt/glusterfs/

OR
# mount -t glusterfs server1:test-volume /mnt/glusterfs/

Python Tutorial

 Data Type Conversion

a) int(55.89)

b) float(36)

my_string=str(9500)

Tuple
 
>>> tuple(“This is a string.”)
(‘T’, ‘h’, ‘i’, ‘s’, ‘ ‘, ‘i’, ‘s’, ‘ ‘, ‘a’, ‘ ‘, ‘s’, ‘t’, ‘r’, ‘i’, ‘n’, ‘g’, ‘.’)
>>>

list(“This will be a list”)

>>> list(“This will be a list”)
[‘T’, ‘h’, ‘i’, ‘s’, ‘ ‘, ‘w’, ‘i’, ‘l’, ‘l’, ‘ ‘, ‘b’, ‘e’, ‘ ‘, ‘a’, ‘ ‘, ‘l’, ‘i’, ‘s’, ‘t’]

chr(65)

ord(‘a’)

hex(4500)

bin(42)
================================================================================

Arithmetic & Comparison Operators

7 kind of operators   

Arithmetic = + , – , / , % , **

a=10
b=15
a+b

>>> a=10
>>> b=10
>>> a+b
20

a*b

comparison operator = a==b   check a equal to b
a!=b , a>b , a<b , a<=b ,  a>=b

>>> a=10
>>> b=10
>>> a+b
20
>>>
>>> a==b
True
>>>
>>> a=15
>>> b=10
>>> a==b
False
>>>

Bitwise & Logical Operators

>>> a=15
>>> b=20
>>> bin(a)
‘0b1111’
>>> bin(b)
‘0b10100’
>>> bin(a&b)
>>> bin(a&b)
‘0b100’
>>> bin(a|b)
‘0b11111’
>>> bin(a^b)
‘0b11011’

AND Operation

a=True
b=False
a  and b
False

a or b
True

not a
False

not b
True

===============================================================================
Membership & Identity Operators

Membership Operators
str1=”I have a lazy dog”
>>> str1=”I have a lazy dog”
>>> str1
‘I have a lazy dog’
>>> “dog” in str1
True

>>> mylist=[1,3,19,32,48,77]
>>> 65 in mylist
False
>>>

>>> 19 in mylist
True
>>>

Identity Operators

>>> a = 43
>>> b= ’43’
>>> a is b
False
>>>

>>> c=42
>>> a is c
False
>>> c=43
>>> a is c
True
>>>

===============================================================================
Operator Precedence

Multiple operator proceeds first
>>>5+4*2
13

>>>
>>> (5+4)*2
18
>>>

=====================================================================================
The IF statement

>>> myvar=50
>>> if myvar<100:
print(“You are 100 %”)

You are 100 %
>>>

>>> myvar=150
>>> if myvar<100:
print(“You are 100 %”)

>>>
=====================================================================================
The ELSE Statement

>>> myvar=50
>>> if myvar<100:
print(“your are short of 100 %”)
else:
print (“your in 100 %”)
print (“thank you”)

your are short of 100 %
>>>

============================================================================
The ELIF Statement

>>> sp=1500
>>> cp=1200
>>> if (sp>cp):
print(“congrats!”)
print(“You’ve made profit of “, sp-cp,”bucks”)
elif (cp>sp):
print(“oops!”)
print(“You ve made a loss of “, cp-sp,”bucks”)
else:
print(“You did or lose money”)

congrats!
You’ve made profit of  300 bucks

>>> sp=1500
>>> cp=1500
>>> if (sp>cp):
print(“congrats!”)
print(“You’ve made profit of “, sp-cp,”bucks”)
elif (cp>sp):
print(“oops!”)
print(“You ve made a loss of “, cp-sp,”bucks”)
else:
print(“You did or lose money”)

You did or lose money

============================================================================
Nested IF-ELSE

>>> char=input()
if ord(char)>=65  and ord(char)<=90:
print(“You entered an uper case alpabet.”)
if char in [‘A’,’E’,’I’,’O’,’U’]:
print(“You entered a Vowel.”)
else:
print(“You entered a consonant.”)
elif ord(char)>=97  and ord(char)<=122:
print(“You entered a lower case alaphabet.”)
if char in [‘a’,’e’,’i’,’o’,’u’]:
print(“you entered a vowel.”)
else:
print(“You entered a consonant.”)
else:
print(“you did not enter an alphabet.”)

============================================================================

The WHILE Loop

>>> var=1
>>> while(var<=10):
print(“Hi! i am”, var)
var=var+1
print(“good bye!”)

var=1
>>> while(var<=10):
print(“Hi! i am”, var)
var=var+1
print(“hello”)
print(“good bye!”)

============================================================================
    
The FOR Loop

>>> count=0
>>> print(“Enter your name:”)
Enter your name:
>>> name=input()
>>> for letter in name:
if (letter in [‘A’,’E’,’I’,’O’,’U’,’a’,’e’,’i’,’o’,’u’]):
count=count+1
print(“You have”,count, “Vowels in your name.”)

You have 1 Vowels in your name.
You have 2 Vowels in your name.
You have 3 Vowels in your name.
You have 4 Vowels in your name.
You have 5 Vowels in your name.
You have 6 Vowels in your name.
You have 7 Vowels in your name.
You have 8 Vowels in your name.
You have 9 Vowels in your name.
>>>

============================================================================
The Break Statement

var=1
while(var<=15):
print(var)
var=var+1
print(“Good bye”)

1
Good bye
2
Good bye
3
Good bye
4
Good bye
5
Good bye
6
Good bye
7
Good bye
8
Good bye
9
Good bye
10
Good bye
11
Good bye
12
Good bye
13
Good bye
14
Good bye
15
Good bye
>>>

>>> var=1
>>> while(var<=15):
if(var==10):
break
print(var)
var=var+1
print(“Good bye”)

1
Good bye
2
Good bye
3
Good bye
4
Good bye
5
Good bye
6
Good bye
7
Good bye
8
Good bye
9
Good bye
============================================================================

Application of Break Statement

while True:
print(“Enter  a digit:”)
num=input()
var=str(num)
if(ord(var) in range(48,58)):
break
print(“You are very obedient!”)

============================================================================
Nested Loops

for var1 in range(2,101):
flag=True
for var2 in range(2,var1-1):
if(var1%var2==0):
print(var1,”is not a prime number”)
flag=False
break
if flag:
print(var1, “is a prime number.”)

============================================================================

The Continue Statement

for var in range(1,16):
if(var in range(9,14)):
continue
else:
print(var)

print(“Enter a string:”)
Enter a string:
var=input()
for letter in var:
if(leter==’ ‘):
continue
else:
print(letter)
========================================================================
Numeric Functions

abs(5)
abs(-5)

import math
math.ceil(35.74)

>>> import math
>>> math.ceil(35.74)
36
>>> math.e
2.718281828459045
>>> math.exp(7)
1096.6331584284585
>>> math.e**7
1096.6331584284583
>>> math.floor(16.94)
16
>>> math.floor(-16.94)
-17
>>>
>>> math.sqrt(25)
5.0
>>>
>>> math.log(5)
1.6094379124341003
>>> math.log(math.e)
1.0
>>> >>> math.log10(10)
1.0
>>>

>>> max(10,15,20,45-18)
27
>>> max(10,15,20,45-18)
27
>>> min(11,19,17,6-213)
-207
>>>

>>> round(17.234234)
17

>>> math.modf(11.971)
(0.9710000000000001, 11.0)

>>> math.pow(4,2)
16.0
>>>

>>> math.hypot(5,12)
13.0
>>> math.hypot(3,14)
14.317821063276352
>>>

>>> math.degrees(math.pi)
180.0
>>> math.degrees(-4)
-229.1831180523293
>>> math.radians(-229.18311)
-3.9999998594603414
>>>

========================================================================

String Functions 

 

>>> str1=”hey, how are you?”
>>> str1.capitalize()
‘Hey, how are you?’

>>> str1=”””tom is a good guy
tom is hard working
tom is honest
tom is team player
tom work out”””
>>> str1
‘tom is a good guy\ntom is hard working\ntom is honest\ntom is team player\ntom work out’
>>>

>>> str1.count(‘tom’)
5

>>> str1=”rmohan.com”
>>> str1.endswith(‘.org’)
False
>>> str1.endswith(‘.com’)
True
>>>

 

>>> str1=”catch me if you can”
>>> str1.find(‘you’)
12
>>>

>>> str1=”hey, how are you?”
>>> str1=”””tom is a good guy
tom is hard working
tom is honest
tom is team player
tom work out”””
>>> str1.count(‘tom’)
5
>>>
>>>
>>> str1=”rmohan.com”
>>> str1.endswith(‘.org’)
False
>>> str1.endswith(‘.com’)
True
>>> str1.endswith(‘.com’)
True

>>> str1=”Hello World”
>>> str1.islower()
False
>>> str1=”hello world”
>>> str1.islower()
True
>>>

>>> str1=”!!!!!!what’s up dudes?”
>>> str1.lstrip(‘!’)
“what’s up dudes?”
>>> str1=”!!!!!!what’s up dudes?”
>>> str1.lstrip(‘!’)
“what’s up dudes?”
>>> str1=”This is so cool!!!!!!”
>
>>> str1.rstrip(‘!’)
‘This is so cool’
>>> str1=”This is so cool!!!!!!”
>>> str1.rstrip(‘!’)
‘This is so cool’
>>> str1.upper()
‘THIS IS SO COOL!!!!!!’

 

>>> str=”I once had a fox”
>>> str1.replace(‘fox’,’lion’)
‘This is so cool!!!!!!’
>>> str1
‘This is so cool!!!!!!’
>>> str1=”I once had a fox”
>>> str1.replace(‘fox’,’lion’)
‘I once had a lion’
>>> str1=”I once had a fox”
>>> str1.replace(‘fox’,’lion’)
‘I once had a lion’
>>> str1
‘I once had a fox’
>>> str1=”Tom cuise”
>>> str1.split()
[‘Tom’, ‘cuise’]
>>>

>>> str1=”########GOOD MORNING########”
>>> str1.strip(‘#’)
‘GOOD MORNING’
>>>

>>>
>>> str1=”I LOVE python”
>>> str1.swapcase()
‘i love PYTHON’
>>> str1.swapcase()
‘i love PYTHON’
>>> str1.title()
‘I Love Python’
>>>

 

List Functions 

>>> mylist=[1,3,5,9,4]
>>> len(mylist)
5
>>> max(mylist)
9
>>> min(mylist)
1
>>> mylist=[3,3,3,3,3,1,1,5,5,5,7,7,7,7,9,9]
>>> mylist.count(7)
4
>>> mylist.append(8)
>>> mylist
[3, 3, 3, 3, 3, 1, 1, 5, 5, 5, 7, 7, 7, 7, 9, 9, 8]
>>> mylist.append(8)
>>> mylist
[3, 3, 3, 3, 3, 1, 1, 5, 5, 5, 7, 7, 7, 7, 9, 9, 8, 8]
>>>

>>> mylist=[4,1,9,3,7,2]
>>> mylist.insert(5,6)
>>> mylist
[4, 1, 9, 3, 7, 6, 2]
>>>

>>> mylist=[4,1,9,3,7,2]
>>> mylist.insert(5,6)
>>> mylist
[4, 1, 9, 3, 7, 6, 2]
>>> mylist.remove(9)
>>> mylist
[4, 1, 3, 7, 6, 2]
>>> mylist.reverse()
>>> mylist
[2, 6, 7, 3, 1, 4]
>>> mylist.sort()
>>> mylist
[1, 2, 3, 4, 6, 7]
>>>

 

 

===========================================================================

Reading Specific Lines  Text File

cat file.txt
line 1
line 2
line 3
line 4
line 5

#!/usr/bin/env python

f = open(“file.txt”)
for x, line in enumerate(f):
if x==3:
print line
f.close()

 

#!/usr/bin/env python

f = open(“file.txt”)
for x, line in enumerate(f):
if x==3:
print line
elif x ==2:
print line
f.close()

 

Reading from a text file

>>> infile = open(“test.txt”)
>>> dataline = infile.read()
>>> dataline
‘Hello world\nTest1’
>>> dataline.split()
[‘Hello’, ‘world’, ‘Test1’]
>>>

======================================================================

Tuple Functions

>>> mytuple=(1,2,’lamb’,’apple’,7)
>>> len(mytuple)
5
>>> mytuple=(78,84,112,-91,43,221)
>>> max(mytuple)
221
>>> min(mytuple)
-91
~

Dictionary Functions

>> movies={1994: ‘Pulp Fiction’ , 1997: ‘Seven’,2000: ‘Cast Away’ ,2006: ‘Blood Diamond’}
>>> movies.keys()
dict_keys([2000, 1994, 1997, 2006])
>>> movies.values()
dict_values([‘Cast Away’, ‘Pulp Fiction’, ‘Seven’, ‘Blood Diamond’])
>>> new={1972:”The GodFather”,1980:”Raging Bull”,2004:”The Aviator”}
>>> new
{1980: ‘Raging Bull’, 1972: ‘The GodFather’, 2004: ‘The Aviator’}
>>>

>>> movies.update(new)
>>> movies
{2000: ‘Cast Away’, 1972: ‘The GodFather’, 2006: ‘Blood Diamond’, 2004: ‘The Aviator’, 1994: ‘Pulp Fiction’, 1980: ‘Raging Bull’, 1997: ‘Seven’}
>>> movies.clear()
>>> movies
{}
>>>

 

 

e2label, fdisk, /etc/fstab, mount, linux rescue, rescue disk, CentOS

Tutorial: e2label, fdisk, /etc/fstab, mount, linux rescue, rescue disk, CentOS
Let’s run through an example of a fresh disk, that needs to be configured, going through partitioning with fdisk, make filesystem, filesystem labelled using e2label, /etc/fstab edited, and mounted using mount. This is relevent for CentOS 3.x, 4.x 5.x; YMMV for other flavours.First, a run through of each command, with usage examples.

fdisk

if the partitioning of the drive is unknown, fdisk -l can be used to list the partition table of the drive. eg. fdisk -l /dev/sdb

following is an example of a disk without a partition table

# fdisk -l /dev/sdb

Disk /dev/sdb: 74.3 GB, 74355769344 bytes
255 heads, 63 sectors/track, 9039 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Disk /dev/sdb doesn’t contain a valid partition table

and here’s an example of a disk with valid partition table

# fdisk -l /dev/sda

Disk /dev/sda: 299.9 GB, 299974524928 bytes
255 heads, 63 sectors/track, 36469 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot Start End Blocks Id System
/dev/sda1 * 1 13 104391 83 Linux
/dev/sda2 14 268 2048287+ 82 Linux swap
/dev/sda3 269 36469 290784532+ 83 Linux

to change the partitions on a drive without partition table, such as a new drive, use fdisk
eg. fdisk /dev/sdb

# fdisk /dev/sdb
Device contains neither a valid DOS partition table, nor Sun, SGI or OSF disklabel
Building a new DOS disklabel. Changes will remain in memory only,
until you decide to write them. After that, of course, the previous
content won’t be recoverable.

The number of cylinders for this disk is set to 9039.
There is nothing wrong with that, but this is larger than 1024,
and could in certain setups cause problems with:
1) software that runs at boot time (e.g., old versions of LILO)
2) booting and partitioning software from other OSs
(e.g., DOS FDISK, OS/2 FDISK)

Command (m for help):

m will list the options available.
eg. p will print the partition table, n is for adding new partition table;
and after the changes are done, w will commit the changes, and exit the program.

e2label

Usage of e2label is simple. manpage for e2label shows following command line options,

e2label device [ new-label ]

device can be the entire drive or a partition.
eg.
/dev/sda is the entire drive
/dev/sda1 is the first partition of device /dev/sda
/dev/sda2 is the second partition of device /dev/sda

eg. to show the label of /dev/sda1 and /dev/sda3

# e2label /dev/sda1
/boot

# e2label /dev/sda3
/

To change the label for /dev/sda3, do as follows,
# e2label /dev/sda3 changed-label

and to confirm the change was done sucessfully,
# e2label /dev/sda3
changed-label

if you want a / in front of the label,

# e2label /dev/sda3 /changed-label

to verify that the change was done,

# e2label /dev/sda3
/changed-label

if you want the server to be able to boot next time round, ensure changes are made to /etc/fstab as well. Otherwise, on the next boot, you may be prompted with errors, eg.

fsck.ext3: Unable to resolve ‘LABEL=/boot’
fsck.ext3: Unable to resolve ‘LABEL=/’

in which case, you can boot up with a rescue disk, eg. CentOS installation disk, enter “linux rescue” at prompt; chroot /mnt/sysimage and edit /etc/fstab accordingly. Alternatively, if you are prompted for root password, and gets a shell, you may be able to edit /etc/fstab. If the filesystem is readonly, remount the filesytem readwrite. eg. mount -o remount,rw /

mount, umount

# mount /dev/sdb5 /tmp/mnt

will mount /dev/sdb5 on the /tmp/mnt directory
if /tmp/mnt does not exist, it needs to be created, using mkdir

to unmount the device, use umount /dev/sdb5 or umount /tmp/mnt

Example of partitioning, formatting and labelling of a new drive

2 partitions to be created
100MB and rest of the drive

# fdisk /dev/sdb
Device contains neither a valid DOS partition table, nor Sun, SGI or OSF disklabel
Building a new DOS disklabel. Changes will remain in memory only,
until you decide to write them. After that, of course, the previous content won’t be recoverable.

The number of cylinders for this disk is set to 9039.
There is nothing wrong with that, but this is larger than 1024,
and could in certain setups cause problems with:
1) software that runs at boot time (e.g., old versions of LILO)
2) booting and partitioning software from other OSs
(e.g., DOS FDISK, OS/2 FDISK)

Command (m for help): n
Command action
e extended
p primary partition (1-4)
p
Partition number (1-4): 1
First cylinder (1-9039, default 1):
Using default value 1
Last cylinder or +size or +sizeM or +sizeK (1-9039, default 9039): +100M

Command (m for help): n
Command action
e extended
p primary partition (1-4)
p
Partition number (1-4): 2
First cylinder (14-9039, default 14):
Using default value 14
Last cylinder or +size or +sizeM or +sizeK (14-9039, default 9039):
Using default value 9039

Command (m for help): p

Disk /dev/sdb: 74.3 GB, 74355769344 bytes
255 heads, 63 sectors/track, 9039 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot Start End Blocks Id System
/dev/sda1 1 13 104391 83 Linux
/dev/sda2 14 9039 72501345 83 Linux

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.
Syncing disks.

Next: format both partitions as ext3 filesystems

# mkfs.ext3 /dev/sdb1
mke2fs 1.39 (29-May-2006)
Filesystem label=
OS type: Linux
Block size=1024 (log=0)
Fragment size=1024 (log=0)
26104 inodes, 104388 blocks
5219 blocks (5.00%) reserved for the super user
First data block=1
Maximum filesystem blocks=67371008
13 block groups
8192 blocks per group, 8192 fragments per group
2008 inodes per group
Superblock backups stored on blocks:
8193, 24577, 40961, 57345, 73729

Writing inode tables: done
Creating journal (4096 blocks): done
Writing superblocks and filesystem accounting information: done

This filesystem will be automatically checked every 22 mounts or
180 days, whichever comes first. Use tune2fs -c or -i to override.

# mkfs.ext3 /dev/sdb2
mke2fs 1.39 (29-May-2006)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
9076736 inodes, 18125336 blocks
906266 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=4294967296
554 block groups
32768 blocks per group, 32768 fragments per group
16384 inodes per group
Superblock backups stored on blocks:
32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208, 4096000, 7962624, 11239424

Writing inode tables: done
Creating journal (32768 blocks): done
Writing superblocks and filesystem accounting information: done

This filesystem will be automatically checked every 33 mounts or
180 days, whichever comes first. Use tune2fs -c or -i to override.

next: use e2label to label the volumes. Although both mkfs3.ext and
tune2fs is capable of labelling, with the -L option, I am deliberately
using e2label in this example to demonstrate the use of e2label.

# e2label /dev/sdb1 /drive2-100MB

confirm its done.

# e2label /dev/sdb1
/drive2-100MB

label sdb2 next,

# e2label /dev/sdb2 /drive2-restofdrive
Warning: label too long, truncating.
# e2label /dev/sdb2
/drive2-restofdr

the description used was too long, and got truncated. maximum for label is 16 characters.

next, we try to mount and unmount the 2 filesystems created,

mount shows what has already been mounted. in addition, the -l option shows the filesystem label

# mount -l
/dev/sda3 on / type ext3 (rw) [/]
proc on /proc type proc (rw)
sysfs on /sys type sysfs (rw)
devpts on /dev/pts type devpts (rw,gid=5,mode=620)
/dev/sda1 on /boot type ext3 (rw) [/boot]
tmpfs on /dev/shm type tmpfs (rw)
none on /proc/sys/fs/binfmt_misc type binfmt_misc (rw)
sunrpc on /var/lib/nfs/rpc_pipefs type rpc_pipefs (rw)

We are mainly concerned with the drives, so let’s grep for the relevent entries

#mount -l | grep /dev/sd
/dev/sda3 on / type ext3 (rw) [/]
/dev/sda1 on /boot type ext3 (rw) [/boot]

We need mount points; the following mount points are created,
# mkdir /mountpt1
# mkdir /mountpt2

to manually mount the drives,
# mount /dev/sdb1 /mountpt1

check that it is mounted,
# mount -l|grep /dev/sd
/dev/sda3 on / type ext3 (rw) [/]
/dev/sda1 on /boot type ext3 (rw) [/boot]
/dev/sdb1 on /mountpt1 type ext3 (rw) [/drive2-100MB]

# mount /dev/sdb2 /mountpt2
# mount -l|grep /dev/sd
/dev/sda3 on / type ext3 (rw) [/]
/dev/sda1 on /boot type ext3 (rw) [/boot]
/dev/sdb1 on /mountpt1 type ext3 (rw) [/drive2-100MB]
/dev/sdb2 on /mountpt2 type ext3 (rw) [/drive2-restofdr]

to unmount, use umount
# umount /dev/sdb1
# umount /dev/sdb2
# mount -l|grep /dev/sd
/dev/sda3 on / type ext3 (rw) [/]
/dev/sda1 on /boot type ext3 (rw) [/boot]

we can also mount the filesystems using the filesystem labels,
# mount -L /drive2-100MB /mountpt1/
# mount -L /drive2-restofdr /mountpt2/
# mount -l |grep /dev/sd
/dev/sda3 on / type ext3 (rw) [/]
/dev/sda1 on /boot type ext3 (rw) [/boot]
/dev/sdb1 on /mountpt1 type ext3 (rw) [/drive2-100MB]
/dev/sdb2 on /mountpt2 type ext3 (rw) [/drive2-restofdr]

unmount can also use the mount point instead of the device, eg.

# umount /mountpt1
# umount /mountpt2
# mount -l |grep /dev/sd
/dev/sda3 on / type ext3 (rw) [/]
/dev/sda1 on /boot type ext3 (rw) [/boot]

next: edit /etc/fstab, add in entries for the new drive if we want it to be mounted at boot up.

following is existing /etc/fstab for the server, which was installed for purpose of this tutorial,

LABEL=/ / ext3 defaults 1 1
LABEL=/boot /boot ext3 defaults 1 2
tmpfs /dev/shm tmpfs defaults 0 0
devpts /dev/pts devpts gid=5,mode=620 0 0
sysfs /sys sysfs defaults 0 0
proc /proc proc defaults 0 0
LABEL=SWAP-sda2 swap swap defaults 0 0

add the following entries,

LABEL=/drive2-100MB /mountpt1 ext3 defaults 1 1
LABEL=/drive2-restofdr /mountpt2 ext3 defaults 1 2

mount has a -a option which reads /etc/fstab and mounts all filesystems mentioned in the file,

# mount -a
# mount -l |grep /dev/sd
/dev/sda3 on / type ext3 (rw) [/]
/dev/sda1 on /boot type ext3 (rw) [/boot]
/dev/sdb1 on /mountpt1 type ext3 (rw) [/drive2-100MB]
/dev/sdb2 on /mountpt2 type ext3 (rw) [/drive2-restofdr]

next, reboot, and ensure the new drive is mounted automatically, and accessible via the mount points, /mountpt1, /mountpt2

WLST: Tree Commands

custom

* Navigates to the root of custom MBeans that are registered in the Runtime MBean Server.
– WLST navigates, interrogates, and edits custom MBeans as it does domain MBeans;
– however, custom MBeans cannot use the cmo variable because a stub is not available.
* Online
* Syntax:

  1. custom()

* Example:

  1. wls:/basicWLSDomain/serverConfig> custom()
  2. Location changed to custom tree. This is a writable tree with No root.
  3. For more help, use help(custom)
  4. wls:/basicWLSDomain/custom> ls()
  5. drw- JMImplementation
  6. drw- com.oracle.jrockit
  7. drw- com.sun.management
  8. drw- java.lang
  9. drw- java.util.logging
  10. drw- oracle.jrockit.management

domainConfig

* Navigates to the last MBean to which you navigated in the domain Configuration hierarchy or to the root of the hierarchy, DomainMBean.
– This read-only hierarchy stores the configuration MBeans that represent your current WebLogic domain.
* Online
* Syntax:

  1. domainConfig()

* Example:

  1. wls:/basicWLSDomain/custom> domainConfig()
  2. Location changed to serverRuntime tree. This is a read-only tree with DomainMBea
  3. n as the root.
  4. For more help, use help(domainConfig)

domainCustom

* Navigates to the domain custom tree of custom MBeans that are registered in the Domain Runtime MBean Server.
– WLST navigates, interrogates, and edits domain custom MBeans as it does domain MBeans;
– however, domain custom MBeans cannot use the cmo variable because a stub is not available.
* Online
* Syntax:

  1. domainCustom(ObjectNamePattern)

– ObjectNamePattern: A JMX query pattern, such as sip:*. The default value is null or *:*.
* Example:

  1. wls:/basicWLSDomain/domainConfig> domainCustom()
  2. Location changed to domain custom tree. This is a writable tree with No root.
  3. For more help, use help(domainCustom)
  4. wls:/basicWLSDomain/domainCustom> ls()
  5. drw- JMImplementation
  6. drw- com.oracle.jrockit
  7. drw- com.sun.management
  8. drw- java.lang
  9. drw- java.util.logging
  10. drw- oracle.jrockit.management

domainRuntime

* Navigates to the last MBean to which you navigated in the domain Runtime hierarchy or to the root of the hierarchy, DomainRuntimeMBean.
– This read-only hierarchy stores the runtime MBeans that represent your current WebLogic domain.
* Online
* Syntax:

  1. domainRuntime()

* Example:

  1. wls:/basicWLSDomain/domainCustom> domainRuntime()
  2. Location changed to domainRuntime tree. This is a read-only tree with DomainMBea
  3. n as the root.
  4. For more help, use help(domainRuntime)
  5. wls:/basicWLSDomain/domainRuntime>

edit

* Navigates to the last MBean to which you navigated in the edit configuration MBean hierarchy or to the root of the hierarchy, DomainMBean.
– This writable hierarchy stores all of the configuration MBeans that represent your current WebLogic domain.
– To edit configuration beans, you must be connected to an Administration Server. If you connect to a Managed Server, WLST functionality is limited to browsing the configuration bean hierarchy.
* Online
* Syntax:

  1. edit()

* Example:

  1. wls:/basicWLSDomain/domainRuntime> edit()
  2. Location changed to edit tree. This is a writable tree with
  3. DomainMBean as the root. To make changes you will need to start
  4. an edit session via startEdit().
  5. For more help, use help(edit)
  6. wls:/basicWLSDomain/edit> startEdit()
  7. Starting an edit session …
  8. Started edit session, please be sure to save and activate your
  9. changes once you are done.
  10. wls:/basicWLSDomain/edit !>

jndi

* Navigates to the JNDI tree for the server to which WLST is currently connected.
– This read-only tree holds all the elements that are currently bound in JNDI.
* Online
* Syntax:

  1. jndi()

* Example:

  1. wls:/basicWLSDomain/edit !> jndi()
  2. Location changed to jndi tree. This is a read-only tree with No root.
  3. For more help, use help(jndi)
  4. wls:/basicWLSDomain/jndi> ls()
  5. dr– AdminServer
  6. wls:/basicWLSDomain/jndi>

serverConfig

* Navigates to the last MBean to which you navigated in the configuration MBean hierarchy or to the root of the hierarchy, DomainMBean.
– This read-only hierarchy stores the configuration MBeans that represent the server to which WLST is currently connected. The MBean attribute values include any command-line overrides that a user specified while starting the server.
* Online
* Syntax:

  1. serverConfig()

* Example:

  1. wls:/basicWLSDomain/jndi> serverConfig()
  2. wls:/basicWLSDomain/serverConfig>

serverRuntime

* Navigates to the last MBean to which you navigated in the runtime MBean hierarchy or to the root of the hierarchy, ServerRuntimeMBean.
– This read-only hierarchy stores the runtime MBeans that represent the server to which WLST is currently connected.
* Online
* Syntax:

  1. serverRuntime()

* Example:

  1. wls:/basicWLSDomain/serverConfig> serverRuntime()
  2. Location changed to serverRuntime tree. This is a read-only tree with ServerRunt
  3. imeMBean as the root.
  4. For more help, use help(serverRuntime)

 

WLST – Presentation Transcript

 

  1. Topics of Discussion
        • What is WLST?
        • Modes of Operation
        • Features
        • Online and Offline WLST
        • Advantages of WLST
        • MBean
        • Create Domain through WLST
        • Demo
        • FAQs
  2. Puzzle
    • WLST
    • Python
    • Jython
    • Mode of WLST Interaction
    • Is WLST Case Sensitive
    • Interactive, Scripting
    • OOPS Language
    • True
    • Weblogic Scripting Tool
    • Embedded, Script, Interactive

    Match the Following:

  3. Let’s Check out what’s right and what’s wrong!
    • WLST – Weblogic Scripting Tool
    • Python – OOPS Language
    • Jython – Embedded scripting language
    • Mode of WLST Interaction – Interactive, Scripting and Embedded
    • WLST Case Sensitive – true
  4. What is WLST?
    • Monitor, Manage & Configure WebLogic Server (online/offline)
    • Based on Jython
    • Similar to any programming language
    • Built on Jython 2.1
          • Simple & clear syntax
          • Use jython libraries
          • Fast in performance
          • Platform Independent
    • Includes capabilities of
          • weblogic.Admin
          • weblogic.Deployer
          • wlconfig Ant Tasks
          • config wizard(silent mode)
  5. Modes of Operation
    • 1. Interactive
      • Navigation/Interrogation
      • Prototyping command syntax
      • Record Interactions to a script to play it later
  6. Modes of Operation
    • 2. Script
      • Sequence of commands via file
      • Use loops, flow control, conditional statements, variables
  7. Modes of Operation
    • 3. Embedded
      • Uses Jython libraries
      • Able to Call WLST interpreter from within your Java code
  8. Executing WLST Script File
    • Different ways:
      • 1. java weblogic.WLST filePath.py
      • 2. execfile (filePath.py)

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

  9. Using WLST- Online
    • WLST is a JMX client
    • Access to Managed Beans (MBeans).
    • Navigate and interrogate MBeans
    • Browsing the MBean hierarchy on connecting to a Server instance
    • BEA Systems recommends changes in the values of configuration MBeans on the Administration Server but not on Managed Server
  10. Using WLST- Offline
      • Create a new domain or update an existing domain
      • You can create new config info., and retrieve and change existing config info from config.xml
  11. WLST Syntax Restrictions
      • Control Commands – connect, disconnect, exit
      • Commands and arguments are case sensitive
      • Use only forward slash (/) in a file pathname:
      • Following characters are not valid in object names:
        • (.), (/), ()
      • cd (‘c:/temp/mytemplate.jar’)
  12. Using WLST- Help
    • Display help information for WLST commands by entering the help command:
    • help(‘online’)
    • help(‘offline’)
    • help(‘get*’)

    wls:/mydomain/serverConfig> help(‘disconnect’)

  13. Features -Advantages
    • Easily move resources from one Domain to another
    • Make reliable changes to config.xml without a running server
    • Use WLST in conjunction with any java utility tools (e.g. ant, jython scripts)
    • Extend WLST to add any Custom commands
    • WLST helps in retrieving MBeans names in a similar fashion to navigating
    • hierarchy of files in a file system.
  14. Configuration MBean Hierarchy
    • Configuration MBean Hierarchy
    • Domain MBean (root)
    • |- – – MBean type (LogMBean)
    • |- – – MBean instance (medrec)
    • |- – – MBean attributes & operations (e.g. FileName)
    • |- – – MBean type (SecurityConfigurationMBean)
    • |- – – MBean type (ServerMBean)
    • |- – – MBean instance (ManagedServer1)
    • |- – – MBean attributes & operations (e.g.AutoRestart)
  15. Current Management Object
    • When WLST first connects to an instance of WebLogic Server, cmo is initialized to the root of all configuration management objects: DomainMBean.
      • MBean type, the value of cmo reflects the parent MBean.
      • MBean name, gives the name of the mbean object
  16. Edit Configuration MBeans
    • DomainMBean root contains editable copy of all configuration MBeans in the domain. The “ change management process” controls distributing configuration changes in a domain representing a DB transaction
      • edit()- used to create, delete, get, set, invoke
      • startEdit() – initiates modifications that are treated as a part of a batch change that is not committed to the repository until you enter the save command.
      • validate() – ensures that changes are valid before saving
      • save() – saves your changes to a pending version
      • activate() – initiates the distribution of the changes and releases the loc
      • stopEdit() – stops the current editing session and releases edit lock.
      • isRestartRequired(‘true’) – determines if a change made to an MBean attribute requires re-start
  17. Feature – Create/Configure Domain
    • WLST enables creating a new domain or updating an existing domain without connecting to a running WebLogic Server
    • Creating a Domain (Offline)
      • Create a new domain using a specified template – createDomain (domainTemplate,domainDir, user, password)
      • Open an existing domain template for domain creation – readTemplate (templateFileName)
      • writeDomain (domainDirName)
      • closeTemplate ()
    • Updating an Existing Domain (Offline)
      • Open an existing domain for update – readDomain (domainDirName)
      • Extend the current domain – addTemplate (templateFileName)
      • Save the domain – updateDomain ()
  18. Sample Code – Create a Domain
    • readTemplate(‘ d:/bea_9.2/weblogic92/common/templates/domains ‘)
    • // Create Admin server with SSL enabled
    • cd(‘Servers/AdminServer’)
    • set(‘ListenAddress’,”)
    • set(‘ListenPort’, 7001)
    • //Setting password
    • cd(‘/’)
    • cd(‘Security/base_domain/User/weblogic’)
    • cmo.setPassword(‘weblogic’)
    • CONTD..
  19. Sample Code – Create a Domain
    • //Creating JMS Server
    • cd(‘/’)
    • create(‘myJMSServer’, ‘JMSServer’)
    • cd(‘/’)
    • create(‘myJmsSystemResource’, ‘JMSSystemResource’)
    • cd(‘JMSSystemResource/myJmsSystemResource/JmsResource/NO_NAME_0’)
    • //Creating JMS Queue
    • myq=create(‘myQueue’,’Queue’)
    • myq.setJNDIName(‘jms/myqueue’)
    • myq.setSubDeploymentName(‘myQueueSubDeployment’)
    • cd(‘/’)
    • cd(‘JMSSystemResource/myJmsSystemResource’)
    • create(‘myQueueSubDeployment’, ‘SubDeployment’)
    • CONTD..
  20. Sample Code – Create a Domain
    • // Creating Datasource
    • cd(‘/’)
    • create(‘myDataSource’, ‘JDBCSystemResource’)
    • cd(‘JDBCSystemResource/myDataSource/JdbcResource/myDataSource’)
    • create(‘myJdbcDriverParams’,’JDBCDriverParams’)
    • cd(‘JDBCDriverParams/NO_NAME_0’)
    • set(‘DriverName’,’com.pointbase.jdbc.jdbcUniversalDriver’)
    • set(‘URL’,’jdbc:pointbase:server://localhost/demo’)
    • set(‘PasswordEncrypted’, ‘PBPUBLIC’)
    • set(‘UseXADataSourceInterface’, ‘false’)
    • create(‘myProps’,’Properties’)
    • cd(‘Properties/NO_NAME_0’)
    • create(‘user’, ‘Property’)
    • cd(‘Property/user’)
    • cmo.setValue(‘PBPUBLIC’)
    • CONTD..
  21. Sample Code – Create a Domain
    • //Creating JDBC Pool
    • cd(‘/JDBCSystemResource/myDataSource/JdbcResource/myDataSource’)
    • create(‘myJdbcDataSourceParams’,’JDBCDataSourceParams’)
    • cd(‘JDBCDataSourceParams/NO_NAME_0’)
    • set(‘JNDIName’, java.lang.String(&quot;myDataSource_jndi&quot;))
    • cd(‘/JDBCSystemResource/myDataSource/JdbcResource/myDataSource’)
    • create(‘myJdbcConnectionPoolParams’,’JDBCConnectionPoolParams’)
    • cd(‘JDBCConnectionPoolParams/NO_NAME_0’)
    • set(‘TestTableName’,’SYSTABLES’)
    • CONTD..
  22. Sample Code – Create a Domain
    • //Targetiing JMS and JDBC to AS
    • cd(‘/’)
    • assign(‘JMSServer’, ‘myJMSServer’, ‘Target’, ‘AdminServer’)
    • assign(‘JMSSystemResource.SubDeployment’, ‘myJmsSystemResource.myQueueSubDeployment’, ‘Target’, ‘myJMSServer’)
    • assign(‘JDBCSystemResource’, ‘myDataSource’, ‘Target’, ‘AdminServer’)
    • //Giving a name to the Domain
    • setOption(‘OverwriteDomain’, ‘true’)
    • writeDomain(‘C:/bea_9.2.2/user_projects/domains/Bhavya’)
    • closeTemplate()
    • exit()
  23. Feature – Control Servers & Server Lifecycle
    • Starting an Administration Server Without Node Manager
    • Server name > Domain name > URL > username > password > path of the domain directory > block user interaction while server startup > server log > system properties > jvm arguments

    wls:offline/> startServer(‘AdminServer’,’mydomain’,’t3://localhost:7001′, ‘weblogic’,’weblogic’,’c:/bea/user_projects/domains/mydomain’,’true’)

  24. Feature – Control Servers & Server Lifecycle
    • Using Node Manager to start the Admin Server helps starting, stopping and restarting it if it fails
    • Starting Managed Servers and Clusters With Node Manager
    • startNodeManager(verbose=’true’,
    • NodeManagerHome=’D:/bea10.2/wlserver_10.0/common/nodemanager’, ListenPort=‘5556′)
    • Connect(‘weblogic’,’weblogic’,’t3://localhost:7001’)
    • wls:/mydomain/serverConfig>start(‘managed1′,’Server’,’t3://localhost:7701′)
  25. Feature – Control Servers & Server Lifecycle
    • Using WLST and Node Manager to Manage Servers
      • Start Node Manager
      • Connect WLST to Node Manager
      • Start an Administration Server
      • Monitor the status of the server you started by entering the nmServerStatus command.
      • Stop the server

    nmConnect(‘weblogic’, ‘weblogic’, ‘localhost’, ‘5556’,’mydomain’, ‘c:/bea/user_projects/domains/mydomain’)

      • wls:/nm/mydomain>nmStart(‘serverName’)
      • wls:/nm/mydomain>nmServerStatus(‘serverName’)
      • wls:/nm/mydomain>nmKill(‘serverName’)
  26. Feature – Deploying Applications
    • WLST deploys application to a WebLogic Server instance similar to weblogic.Deployer utility. The deploy command returns a WLSTProgress object that can be used to check the status.
      • Deploy
    • application name
    • path of the ear or war file
    • target
    • plan path (deployment plan file )
    • options

    wls:/mydomain/serverConfig/Servers> deploy(‘demoApp’, ‘c:/myapps/demos/app/demoApp.ear’, targets=’myserver’, planPath=’c:/myapps/demos/app/plan/plan.xml’, timeout=120000)

  27. Feature – Deploying Applications
      • Redeploy
    • application name
    • path of the ear or war file
    • returns progress state (completed)
      • Undeploy:

    wls:/mydomain/serverConfig> progress = redeploy(‘myApp’ ‘c:/myapps/plan.xml’) wls:/mydomain/serverConfig/Servers> progress.getState() wls:/mydomain/serverConfig> undeploy(‘businessApp’, timeout=60000)

  28. Demo 1 – Check the status of WLS Instances
      • connect(‘weblogic’,’weblogic’,’t3://localhost:7010′);
      • print ‘Status’,state(‘AdminServer’,’Server’);
      • print ‘Status’,state(‘MS1′,’Server’);
      • print ‘Status’,state(‘MS2′,’Server’);
      • print ‘Status’,state(‘MS3′,’Server’);
      • print ‘Status’,state(‘MS4′,’Server’);
      • disconnect();
  29. Demo 2 – Deploy a jar file on Managed Server
      • appPath=’D:/WLST/netuix_common.jar’
      • appName=’netuix_common.jar’
      • targets=’MS1′
      • username=’weblogic’
      • password=’weblogic’
      • serverURL=’t3://localhost:7010′
      • connect(username,password,serverURL)
      • edit()
      • startEdit()
      • deploy(appName=appName, path=appPath, targets=targets)
      • save()
      • activate()
  30. Demo 3 – Edit the attribute of Running Server
      • connect(‘weblogic’,’weblogic’,’t3://localhost:7010’)
      • ls()
      • cd(’Servers’)
      • cd(‘MS1’)
      • ls()
      • edit()
      • startEdit()
      • set (‘ IdlePeriodsUntilTimeout ‘,10)
      • save()
      • activate()
  31. Demo 4 – Changing the Current Management Object
      • connect(‘username’,’password’)
      • cmo
      • cd(‘Servers’)
      • cmo
      • cd(‘myserver’)
      • cmo
  32. Demo 5 – Navigating and Displaying Configuration MBeans
      • connect(‘username’,’password’)
      • ls()
      • cd(‘Servers’)
      • ls()
      • cd(‘myserver’)
      • ls()
  33. Demo 6 – Fire GC for a specific server
      • cd(‘/ServerRuntimes/’+sname+’/JVMRuntime/’+sname)
      • cmo.runGC()
  34. Demo 7 – Edit the DataSource database password
      • connect() // connect to the domain
      • cd(‘Servers/MS1’)
      • edit()
      • cd(‘JDBCSystemResources’)
      • cd(‘samplesDataSource’)
      • cd(‘JDBCResource’)
      • cd(‘samplesDataSource’)
      • cd(‘JDBCDriverParams’)
      • cd(‘samplesDataSource’)
      • set(‘PasswordEncrypted’, ‘PBPUBLIC’)
      • Save()
      • Activate()
  35. Demo 8 – Script to monitor threads
      • connect() // connect to the domain domainRuntime() cd(‘ServerRuntimes/AdminServer/ThreadPoolRuntime/
      • ThreadPoolRuntime’) ls() // it will list all the thread pool information
  36. Demo 9 – Script to get the count of stuck threads
      • Retrieivng the StuckThreadCount using WLST.
      • Can be retrieved using WLST from the path
      • connect() // connect to the domain domainRuntime() cd(‘ ServerRuntimes/SERVERNAME/WorkManagerRuntimes/
      • DataRetirementWorkManager/ StuckThreadCount ‘)
  37. Demo 10 – Start the server
      • startServer(‘AdminServer’, ‘mydomain’,
      • username=’weblogic’, password=’weblogic’, block=’true’, timeout=300000,
      • serverLog=’./test-right.log’,
      • systemProperties=’weblogic.ListenPort=14521′,
      • jvmArgs=’-Xms256m -Xmx512m -XX:MaxPermSize=128m’)
      • To summarize,
      • You should specify url in the startServer command
      • OR
      • You should specify weblogic.ListenPort in the systemProperties of the startServer() command.
  38. Check server state and start if not running
    • # Connect WLST to the running server
    • connect(‘weblogic’,’weblogic’,’t3://localhost:7010′);
    • #The following command willl print the state of the servers
    • print ‘Status’,state(‘AdminServer’,’Server’);
    • serverRuntime()
    • a = get(‘State’)
    • if a == ‘RUNNING’
    • print ‘Status’,state(‘MS1′,’Server’);
    • print ‘Status’,state(‘MS2′,’Server’);
    • print ‘Status’,state(‘MS3′,’Server’);
    • print ‘Status’,state(‘MS4′,’Server’);
    • startServer(‘AdminServer’,’mydomain’,’t3://localhost:7001′,
    • ‘weblogic’,’weblogic’,’c:/bea/user_projects/domains/mydomain’,’true’)
    • # Disconnect the WLST from Adminserver
    • disconnect();
    • # Node Manager needs to be running to run this script.
    • connect(‘weblogic’,’weblogic’,’t3://localhost:7010′)
    • domainRuntime()
    • slrBean = cmo.lookupServerLifeCycleRuntime(‘MS1’)
    • status = slrBean.getState()
    • print ‘Status of Managed Server is ‘+status
    • if status != &quot;RUNNING&quot;:
    • start(‘MS1’, block=&quot;true&quot;)
    • print ‘Starting server MS1’
    • nmConnect(‘weblogic’, ‘weblogic’, ‘localhost’,’5556′,’WLST’,’D:/bea10.2/user_projects/domains/WLST’)
    • a = nmServerStatus(‘AdminServer’)
    • print a
    • b = 1
    • while b == 1:
    • if a == &quot;RUNNING&quot;:
    • b = 0
    • connect(‘weblogic’,’weblogic’,’t3://localhost:7010′)
    • print ‘Successfully connected’
    • else:
    • a = nmServerStatus(‘AdminServer’)
    • print ‘Starting Admin Server’
  39. Reorder Authentication Providers WLST Script
    • edit() startEdit(-1,-1,’false’)
    • cd(‘/SecurityConfiguration/WLST_Machine/Realms/myrealm’)
    • set(‘AuthenticationProviders’,jarray.array([ObjectName(‘Security:Name=myrealmDefaultIdentityAsserter’), ObjectName(‘Security:Name=myrealmDefaultAuthenticator’)], ObjectName))
    • save() activate()
    • cd(‘/Security/ domainname /User/ username ‘) cmo.setPassword(‘ password ‘)
  40. Edit WLS password
    • Connect(‘weblogic’,’weblogic’,’t3://loclahost:7001’)
    • from weblogic.management.security.authentication import UserPasswordEditorMBean
    • print &quot;Changing password …&quot;
    • atnr=cmo.getSecurityConfiguration().getDefaultRealm().lookupAuthenticationProvider(&quot;DefaultAuthenticator&quot;)
    • atnr.changeUserPassword(‘weblogic’,’weblogic’,’weblogic123′)
  41. Set the server mode to production while creating a domain
    • # read the domain template
    • readTemplate(&quot;D:/bea10.2/wlserver_10.0/common/templates/domains/wls.jar&quot;)
    • setOption(‘ServerStartMode’, ‘prod’)
    • # create a domain
    • writeDomain(‘D:/bea10.2/user_projects/domains/basicWLSDomain’)
    • # close the template
    • closeTemplate()
  42. For More Information …
    • Documentation (for WLS 10.0) at:
      • http://e-docs.bea.com/wls/docs90/config_scripting/using_WLST.html
      • UseFul Links
      • http://www.jython.org – download Jython
      • FQA
      • http://edocs.bea.com/wls/docs92/config_scripting/wlst_faq.html
  43. Thank You Quest Time