Category: Coding

Posts that have coding in it.

Working with sqlite in Python

Working with sqlite in Python

#!/bin/python

import datetime
import timedelta
import os.path
import sqlite3
import sys

#Global Variables
DBPath='test.db'

#from datetime import datetime, timedelta
#then = datetime.now() - timedelta(hours = 2)
#now = datetime.now()
#(now - then) > timedelta(days = 1)
#False
#>>> (now - then) > timedelta(hours = 1)
#True

StuffToLoad = [
	(0 , 'example.domain.com'  , 'Maintenance' ,'2014-08-10 15:07:15.067766'),
	(1 , 'example2.doman.com'  , 'Maintenance' ,'2014-08-10 15:07:15.067766'),
	(2 , 'exmaple3.domain.com' , 'Maintenance' ,'2014-08-10 15:07:15.067766'),
]

def CreateDB():
	print "Creating Database....."
	conn = sqlite3.connect(DBPath)
	conn.execute('''CREATE TABLE MInMant (ID INT PRIMARY KEY NOT NULL, Machine TEXT NOT NULL, HostState INT NOT NULL, date CHAR(50))''')
	conn.commit()
	conn.close()

def InsertDB(x):
	conn = sqlite3.connect(DBPath)
	c = conn.cursor()
	t = ('Maintenance',)
	c.execute('SELECT * FROM MInMant WHERE HostState=?', t)
	c.executemany('INSERT INTO MInMant VALUES (?,?,?,?)', StuffToLoad)
	conn.commit()
	conn.close()

def PrintDBContents():
	print "DEBUG PrintDB Contents"
	conn = sqlite3.connect(DBPath)
	c = conn.cursor()
	for row in c.execute('SELECT * FROM MInMant'):
	        print(row)

#We start out program
#if os.path.isfile(DBPath) == 'True':
CreateDB()

#Load data into our DB
InsertDB(StuffToLoad)

#Print data from our DB
PrintDBContents()
Simple useful Python Function

Simple useful Python Function

These are functions that I have been useful and flexible to me.

import sys
import subprocess
import string
import socket
import re
import syslog
import smtplib
import os
import sys, getopt
from optparse import OptionParser

# Function that does basic standard output
def message(message):
    sys.stdout.write(message)
    sys.stdout.flush()

#Get command line options then return the variables to be used in other parts of the script.
def CliOptions():
    """
    Setup command-line parsing options
    """
    parser = OptionParser()
    parser.add_option('-o', '--output', default = '',    dest = 'output', help = 'Where to output the file to.')
    parser.add_option('-i', '--input',  default = '',    dest = 'input',  help = 'The Input file.')
    parser.add_option('--TrueOrFalse',	default = False, dest = 'TOF', help = 'True or false value.')
    return parser.parse_args()

#Take the contents of data and write it in a file.
def WriteFile(outputFile, outputInformation): 
    fileHandle = open(outputFile + ".out", "w")
    fileHandle.write(outputInformation)
    fileHandle.close()
 
#Read a file and remove newline and return charaters. Then return the data back.
def readFileFunction(inputFile):
    InputFromFile = []
    with open(inputFile, "r") as ins:
        for inputFileLineItem in ins:
            InputFromFile.append(line.rstrip('\r\n'))
    ins.close()
    return InputFromFile

#Have it output to syslog
def MsgLogging(msg):
	syslog.syslog(syslog.LOG_INFO, msg)

#This function calls shell commands. Clean the output but removing the any newline and return charaters using lambda.
def ExternalCommands(command):
    p1 = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    results = p1.stdout.readlines()

    resultsFromPopen = map(lambda s: s.rstrip('\r\n'), results)
    return resultsFromPopen

How to use the above functions:


#The messaging function:
message ("Hello World\n")

#For the CliOptions function, The function gets called, it getting the commandline arguments. The function will return data into an array.
(options,args) = CliOptions()

#For the msgLogging
MsgLogging("Hello World")

#For ExternalCommands
results = ExternalCommands("ls /")

#For readFileFunction
results = readFileFunction(pathToFile)

#For WriteFile
WriteFile("/tmp/test.txt", "Hello World")
Sample List (PHP)

Sample List (PHP)

Date: 08/21/2009
Program Name: Sample List (PHP)
Description: The purpose of this PHP program is get records of a database, and show only the last 30 items.

<?php
  session_start();
  include ('request_processor.php');
  include ('********.php');
  include ('menu.php');
  include ('head.php');
 
  //were going to check of the were able to connect to the database.  If we can not then print a message that we can not
  $result = con_test();
  if (!$result) 
  {
      echo ('Connection status: <b><span style="color:red">error</span></b> <br /> <p>Please check to see if the MySQL database service is on.');
      exit(0);
  }
  else
  {
    if ($_SESSION['login'] == '') //indicating that if the variable is not set than the 
    {  //print the login page
      print ("<table align=\"center\" border=\"0\"><form action=\"login.php\" method=\"post\"><table border=\"0\" align=\"center\">");
      print ("<tr><td>User Name:</td><td><input type=\"text\" size=\"30\" maxlength=\"28\" name=\"Name\" /></td>");
      print ("</tr><tr><td>Password:</td><td><input type=\"text\" size=\"30\" maxlength=\"28\" name=\"pass\" /></td>");
      print ("<tr><td align=\"center\" colspan=\"2\"><input type=\"submit\" value=\"Login\" />");
      print ("<input type=\"button\" value=\"Lost Password\" /></td></tr></table></form></body></html>");
      $_SESSION['login'] = 'check';
      exit(0);
    }
    elseif($_SESSION['login'] == 'check')
    {
      //Will start first by openning a connection to mysql
      $connection = con();
 
      //get the name and password from the login page
      $name = $_POST["Name"];
      $pass = $_POST["pass"];
 
      //Create the query command for MySQL
      $query = "select * from users where UserName = '$name' and password = '$pass'";
 
      $result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
 
      if (!mysql_fetch_object($result))
      {
				$_SESSION['login'] = '';
				print ("I am sorry but the username or password does not match!<br /><a href=\"/portfilo/login.php\"><td>Go Back</a>");
				exit(0);
      }
      else
      {
				$_SESSION['login'] = 'ja';
				head();  //Create the html headers
				styles(); //Then the styles
				menu();   //Menu option
				print ("This is a sample programming Work.");
      }
 
      // close connection
      mysql_close($connection);
    }
    elseif ($_SESSION['login'] == 'ja')
    {
      head();  //Create the html headers
      styles(); //Then the styles
      menu();   //Menu option
 
      print ("This is a sample programming Work.");
    }
    // Session cleanup
    session_destroy();
  }
?>
Sample Login Program (PHP)

Sample Login Program (PHP)

Date: 08/18/2009
Program Name: Sample Login Program (PHP)
Description: The purpose of this PHP program is allow a user to login and view the content of a page. If the user does not supply the correct login information, then the program will print out a message stating that the information is incorrect. In addition, The program checks to see if it’s able to connect to the database. If it can not than it will display a message stating that it can not connect to the database.

<?php
  session_start();
  include ('request_processor.php');
  include ('********.php');
  include ('menu.php');
  include ('head.php');
 
  //were going to check of the were able to connect to the database.  If we can not then print a message that we can not
  $result = con_test();
  if (!$result) 
  {
      echo ('Connection status: <b><span style="color:red">error</span></b> <br /> <p>Please check to see if the MySQL database service is on.');
      exit(0);
  }
  else
  {
    if ($_SESSION['login'] == '') //indicating that if the variable is not set than the 
    {  //print the login page
      print ("<table align=\"center\" border=\"0\"><form action=\"login.php\" method=\"post\"><table border=\"0\" align=\"center\">");
      print ("<tr><td>User Name:</td><td><input type=\"text\" size=\"30\" maxlength=\"28\" name=\"Name\" /></td>");
      print ("</tr><tr><td>Password:</td><td><input type=\"text\" size=\"30\" maxlength=\"28\" name=\"pass\" /></td>");
      print ("<tr><td align=\"center\" colspan=\"2\"><input type=\"submit\" value=\"Login\" />");
      print ("<input type=\"button\" value=\"Lost Password\" /></td></tr></table></form></body></html>");
      $_SESSION['login'] = 'check';
      exit(0);
    }
    elseif($_SESSION['login'] == 'check')
    {
      //Will start first by openning a connection to mysql
      $connection = con();
 
      //get the name and password from the login page
      $name = $_POST["Name"];
      $pass = $_POST["pass"];
 
      //Create the query command for MySQL
      $query = "select * from users where UserName = '$name' and password = '$pass'";
 
      $result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
 
      if (!mysql_fetch_object($result))
      {
				$_SESSION['login'] = '';
				print ("I am sorry but the username or password does not match!<br /><a href=\"/portfilo/login.php\"><td>Go Back</a>");
				exit(0);
      }
      else
      {
				$_SESSION['login'] = 'ja';
				head();  //Create the html headers
				styles(); //Then the styles
				menu();   //Menu option
				print ("This is a sample programming Work.");
      }
 
      // close connection
      mysql_close($connection);
    }
    elseif ($_SESSION['login'] == 'ja')
    {
      head();  //Create the html headers
      styles(); //Then the styles
      menu();   //Menu option
 
      print ("This is a sample programming Work.");
    }
    // Session cleanup
    session_destroy();
  }
?>
Security Update Check Using GLSA

Security Update Check Using GLSA

Date: 08/20/2009
Program Name: Security Update Check Using GLSA
Description: The object of this script is to get an update respiratory from a Gentoo server and check to see if their is any security issues that effect a system.

#!/bin/bash
 
# The script will check for new Security updates available in portage

#Information needed inorder to mail the admin
echo "From: root@test.com" >> $stat
echo "To: admin@test.com" >> $stat
echo "Subject: System Security Check" >> $stat
 
echo -e "Security Check Report for $HOSTNAME $(date)\n-------------------------------------------\n" >> $stat
#Were going to update The package Libarary
emerge --sync >> $stat
 
# Then check if it went ok
result=$(grep 'metadata/glsa/timestamp.chk' /tmp/test.txt)
 
if [ !$result ]; then
    echo -e "The Portage Library Update Failed. Here is the last message that was picked up by Portage.\n" >> $stat
    tail -n10 /tmp/test.txt >> $stat
    echo -e "\n-------------------------------------------\n" >> $stat
    echo -e "\nThings to Check with the system:\nPlease check if the system is able to resovle name server.\nCheck if their is any conitivity on the network.\nCall an Admin!!" >> $stat
else
    echo -e "The Portage Library Update Works! Doing a security Check on the system\n" >> $stat
    glsa-check --list affected >> $stat
    echo -e "\n System security Check Completed.\n-------------------------------------------" >> $stat
fi
 
#Mail the Results
cat $stat | /usr/sbin/sendmail -t -bm -v
#Clean up the mess
echo "" > $stat
%d bloggers like this: