Tuesday, July 27, 2010

Shell Script: automated backup to external hard disk

Making backups is very essential. But good backups run automatically. So you do not need to take care of them (except the moment you set them up).


I've written a small script. It checks if the hard disk is mounted and then it starts to copy the data or it warns the user that the disk is not mounted yet. You have five minutes until the script will check again. It's not perfect but it does it's work.




#!/bin/sh

homeFolder="/home/user"
backupDir="/media/backupMedia"
externalDisk="fda1"

mount | grep /dev/$externalDisk >/dev/null
if [ "$?" -eq "0" ]; then
  #mounted create backup
  rsync "$homeFolder" "$backupDir"
else
  #not mounted
  xmessage -center External hard drive not available.
  sleep 300
  mount | grep /dev/$externalDisk >/dev/null
  if [ "$?" -eq "0" ]; then
    #mounted create backup
    rsync "$homeFolder" "backupDir"
  else
    xmessage -center Couldn't backup data.
  fi
fi

Tuesday, July 6, 2010

A simple python webserver


Today i wrote a simple webserver in python. He can display static content (.html pages) and interpret python scripts and display their output. You can configure "virtual hosts" (domains that the server is listening to) and specify a server root where all the files are stored.

This server doesn't implement any security functions and is not for productive use nor it wants to compete with any existing webserver. It's just for demonstration purpose/ learning.
It runs only on > python 3 interpreters. For some parts of the code is used the friendly support of the German python forum. Thank you again ;)

Server.py 
'''
Created on 05.07.2010

@author: Benny Gaechter
'''

from ServerRootPath import *
from VirtualHosts import *
from subprocess import Popen, PIPE
import http.server
import socketserver

class HttPythonServer(http.server.SimpleHTTPRequestHandler):

    server_version = "HttPythonServer/0.0.1-alpha"
    sRP = ServerRootPath()
    vH = VirtualHosts()
    fullDocumentPath =""
    outPut = ""
    
    def do_GET(self): 
        self.fullDocumentPath = self.sRP.getDocumentRoot()[0] + self.path
        self.checkForVirtualHost()
        
            
    def checkForVirtualHost(self):
        hostsList = self.vH.getHostList()
        foundHost = False
        
        for line in hostsList:
            if line == self.headers.get("host"):
                foundHost = True

        try:    
            if foundHost == False:
                raise Exception("Host not Found")
            else:
                self.checkIfInterpretable()
            
        except Exception:
            self.send_error(401, "Invalid Host name")
            
    def checkIfInterpretable(self):
        #Try & catch doesn't work because there is no exception raised    
        try:    
            if self.path.endswith(".py"):
                    p = Popen(["python", self.fullDocumentPath], stdin=PIPE, stdout=PIPE)
                    self.outPut = p.stdout.read()
                    self.sendHeaders()
                    self.wfile.write(str(self.outPut).encode())
            else:
                self.displayStaticContent()
                
        except IOError:
            self.send_error(404, "File not found")
                                   
    def displayStaticContent(self):
        try:
            self.f = open (self.fullDocumentPath)
            self.outPut = self.f.read()
            self.sendHeaders()
            self.wfile.write(str(self.outPut).encode())
        except IOError:
            self.send_error(404, "File not found")
        
    def sendHeaders(self):
        self.send_response(200)
        self.send_header("content-type", "text/html")
        self.end_headers()
        
            
if __name__ == '__main__':
    try:
        server = socketserver.ThreadingTCPServer(("", 6060), HttPythonServer) 
        print("Server started ..... press C^ to stop")
        server.serve_forever()
    except KeyboardInterrupt:
        print("Received C^... shutting server down")
        server.socket.close()

To use the webserver under windows change line 47 python to C:\Python31\python.exe


 VirtualHosts.py
'''
Created on 05.07.2010

@author: Benny Gaechter
'''

class VirtualHosts():
    '''
    classdocs
    '''
    hostList = []
    
    '''
    Constructor
    '''
    def __init__(self):
        fobj = open("./VirtualHosts.conf", "r") 
        for line in fobj: 
            self.hostList.append(line)
            #print (line) 
        fobj.close()

    def getHostList(self):
        return self.hostList
        

ServerRootPath.py
'''
Created on 05.07.2010

@author: Benny Gaechter
'''

class ServerRootPath():
    '''
    classdocs
    '''
    documentRootList = []
    
    '''
    Constructor
    '''
    def __init__(self):
        fobj = open("./ServerRoot.conf", "r") 
        for line in fobj: 
            self.documentRootList.append(line)
            #print (line) 
        fobj.close()

    def getDocumentRoot(self):
        return self.documentRootList


ServerRoot.conf (you need to create this folder an put the .html or py files in here)
/tmp/WebServerTest

VirtualHosts.conf  (you may want to add your hostname here, too)
localhost:6060

Monday, July 5, 2010

Syntax highlighting for blogger

Today i added syntax highlighting function for my blog. It followed this tutorial and with this post i just want to see how it works =P

#This is my first highlighted code
print("Hello World")

it seems to work fine...