#!/usr/bin/python

import getpass
import os
import socket
import config
# try:
# 	import MySQLdb
# except ImportError:
# 	print "Error #191712 Sorry. We are working on this issue. Report to boopathi@live.com about this error"
# 	exit()

"""Intro Message"""
intro_message = "Welcome to PyShell. use help to show the list of available commands "

"""Allowed Commands"""
allowed = ["man", "less", "ssh", "pwd", "ls", "grep", "cat", "touch", "clear"];

"""Strictly Restricted Commands"""
strict = ["su", "sudo", "cd", "mkdir", "locate", "rm", "rmdir"];

""" Init Commands """
os.system("clear");
os.system("TERM=\"linux\"");
username = getpass.getuser();
hostname = socket.gethostname();
ipaddr = socket.gethostbyname(socket.gethostname());

def parseCommand(command):
	args = command.split()
	if len(args) == 1:
		return args[0];
	if isVulnerable(args[1:]):
		return False;
	else:
		return args[0];
	

def isVulnerable(args):

	# Finding the possible area of command
	num = 0;
	for x in args:
		if x == "|" or x == "&&" or x=="&" or x==";":
			if not args[args.index(x)+1] in allowed:
				return True

	""" Prevent from accessing folders other than the home folder """
	for a in args:
		if a.startswith("/"):
			return True;
		elif a.__contains__(".."):
			return True;

	"""Restrict users from accessing denied commands from any part of the command"""
	for a in strict:
		if args.__contains__(a):
			return True;
	return False;

def exitShell(message = "Bye. Thanks for using PyShell."):
	os.system("clear");
	print message;
	exit(0)

def displayHelp():
	message = "The allowed commands are \n";
	print message;
	for tmp in allowed :
		print tmp + "\t";

def displayError(message = "Restricted Access"):
	print message + '\n';

# def enterLog(command):
# 	logFile = open("/usr/pshell/log/" + username + ".log", "a");
# 	logFile.write(command + "\n");
# 	logFile.close();
# 	#Enter log into db for verification
# 	con = MySQLdb.connect(host="10.0.0.163", user="pragyan11", passwd="andromeda", db="pragyan11_treasure")
# 	cur = con.cursor()
# 	cur.execute("insert into `treasure_hunt` (`username`,`command`, `hostname`, `ipaddr`) values('"+username +"','"+command +"','"+hostname+"', '"+ipaddr+"')")
# 	con.commit()
# 	con.close()

print intro_message;
while(True):
	try:
		command = raw_input(username + "@" + hostname + ":: ");
	except KeyboardInterrupt:
		print;
		continue;
	except EOFError:
		print
		exitShell("Bye. You pressed CTRL + D");
	except:
		print
	
	"""Handle Null Argument"""
	if command == "":
		continue;

    #enterLog(command)
	cmd = parseCommand(command)
	
	"""Check for Vulnerability Status"""
	if cmd == False:
		displayError("Vulnerability Issue. Command cannot be executed");
		continue;
	if allowed.__contains__(cmd):
		os.system(command)
	elif command == "help":
		displayHelp();
	elif command == "exit":
		exitShell();
	else:
		print "Restricted Access"


