Read tar.gz files without extracting

I had a need to look for certain commands in a list of Oracle audit logs what had been tarred and zipped (*.tar.gz format). I created a list with an ls command:

ls *.gz > dean.txt

I then used the below python code to read through the zipped tar balls looking for certain strings:

#!/usr/bin/python
import tarfile,os
import sys
 
list_of_tar = open('dean.txt', 'r')
for tar_name in list_of_tar:
    tar_name = tar_name.rstrip()
    print tar_name
    tar = tarfile.open(tar_name,'r:gz')
    for member in tar.getnames():
        file_name=tar.extractfile(member)
        for line in file_name:
            line = line.lower()
            if 'alter ' in line:
                if ' system ' in line:
                    if 'kill' in line:
                        print tar_name, member , line
tar.close()

This was a quick and dirty python to fulfill an immediate need. With more time the search condition could be improved.

Calling a function with multiple arguments

The below code snippet demonstrates how you can call a Python function with multiple arguments:

def say_hi (first, last):
    print('Hi {} {}!'.format(name))
 
say_hi('Jane','Doe')

The above line of code is calling with positional parameters. The first parameter is associated with first variable and so on. The function can also be called as

say_hi(last = 'Doe', first = 'Jane')

Python script setting a shell environment variable

os.environ is a useful way to set an environment variable in the shell as shown below:

#!/usr/bin/python
import pdb
import os
import sys
import subprocess
import commands
import time
import socket
import locale
locale.setlocale(locale.LC_ALL, 'en_US')
 
team_name = 'Delta Team'
msg_line = 'The '+team_name+' is executing this script.'
os.environ['msg_line'] = msg_line
os.system('echo "${msg_line}" | mail -s "Email subject goes here" "Dean.Capps@somecompany.com"')

(I may have extra imports as this was taken from a much larger script.)

Python script to list the user account and full name of the current user

I had a requirement to identify the actual user account and full name of the current user who was currently “Sued” to a higher privileged user account such as Oracle. The below script provides me with that functionality:

#!/usr/bin/python
import pdb
import os
import sys
import subprocess
import commands
import time
import socket
import locale
locale.setlocale(locale.LC_ALL, 'en_US')
 
user_name = os.popen("who am i| awk '{print $1}'").read()
user_name=user_name.rstrip('\n')
print user_name
 
os.environ['py_user_name'] = user_name
user_name = os.popen("cat  /etc/passwd | grep ${py_user_name} | awk -F \":\" '{print $5}'").read()
user_name=user_name.rstrip('\n')
print user_name

(I may have extra imports as this was taken from a much larger script.)

142
51
73
77