Tuesday, November 17, 2015

Parse Oracle tnsnames.ora into alias list using Python

#!/bin/python
# tns_parser.py

import os
import re

os.chdir('/opt/oracle/etc') # move to tns directoy

tns = open('tnsnames.ora', 'r')              # open file
vlist = tns.read()                           # read file into string
vlist = re.sub("#.*\n","",vlist)             # strip all comments
vlist = re.sub("\(.*\n","",vlist)            # remove "(" to end of line
vlist = re.sub("\)","",vlist)                # clean up ")"
vlist = re.sub(" ","",vlist)                 # remove spaces
vlist = re.sub("\n","",vlist)                # remove carriage returns
vlist = re.sub("=$","",vlist)                # remove last "="
vlist = vlist.split("=")                     # create list
tns.close()
#print '\n'.join(vlist)
#print(vlist)
#print vlist[4]
for i in vlist:
         # do anything you want with this list now.  YAY!
                 print i


# run it.
oracle@localhost $ python tns_parser.py 
dev.world.net 
uat.world.net
prod.world.net

target tnsnames.ora sample:
dev.world.net =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = host_name_or_ip )(PORT = 1571))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = dev.world)
    )
  )

uat.world.net =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = host_name_or_ip )(PORT = 1571))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = uat.world)
    )
  )

prod.world.net =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = host_name_or_ip )(PORT = 1571))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = prod.world)
    )
  )

this can probably be accomplished with a single line but i'm new to this language, give me a break.

enjoy...

No comments:

Post a Comment