<file_sep>ps -ef | grep postgresql | grep -v grep
[ $?  -eq "0" ] && echo "PostgreSQL check!" || echo "process is not running"
<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-

# @Author       Wonseok
# @Designer     Wonseok
# @Start at     Aprl. 17
# @Last at      Aprl. 18
# @Music        The tear of PPIERO - Outsider(Moo-oong) ( feat Bae-Chi-Gi )
# @Information  This class is child class of BackupEngine.
# @details
#               DBE(Database Backup Engine) is only for doing backup service. 
#           You have to connect master and slave server, and connect local database in parent initalizer.
#           This is a previous work for using this class. After this work, you have to connect local database.
#           Obviously this work is held in this class. It is easy but may take some time to do this work.
import os, sys
sys.path.insert(0, os.getcwd())
from BackupEngine import BackupEngine 
from ObjectInfo import Server
from ObjectInfo import AdministratorClass
from ObjectInfo import DatabaseClass
from System import Logger
class DatabaseBackupEngine ( BackupEngine ) :
    def __init__(self, Master=None, Slave=None, Admin=None) :
        BackupEngine.__init__(self, Master, Slave, Admin)




#
#      Test if DBE status is good
#
if __name__ == "__main__" :
    # Test Configuration :
    # Master server is server id (1)
    # Slave server is server id (4)
    # Admin is me
    #
    # Test algorithm
    # 1. Server connection test
    #   - Master server connect [ Parent class done ]
    #   - Slave server connect  [ Parent class done ]
    # 
    # 2. Get master's local db_key from local database.
    #   - Using master server's owner_key to get DB_key     -> will be written in DatabaseClass
    #   - Using master server's db_key, get the db_data from local db.
    #      
    # 3. Database connection test 
    #   The database which is gotton from task number 2, connect test it.
    #
    # 4. Send the command which back-up database.
    #   Make the command ( Using scheduler is good way. )
    #   Send the command to server.

    '''
    * Initializing for test
    '''
    # Server & Database Setting
    MasterServer = Server.Server(1, 22, 'ssh', '192.168.3.11', '3@mHze=5K{1wj){}', 'root', 'Wonseok.J', 970403, 'ubuntu', 'wonseokbuntu', None, '2018-03-02', None, None)
    SlaveServer = Server.Server(4, 22, 'ssh', '192.168.3.11', 'P]9p{PWKRu=+o7y]', 'root', 'Wonseok.J', 970403, 'ubuntu', 'WonseokTestCent', None, '2018-03-02', None, None)
    MasterServer.db = DatabaseClass.DB("psql", "'localhost'", "'5432'", "'testdb'", "'1234'", "'test'")
    SlaveServer.db = DatabaseClass.DB("psql", "'localhost'", "'5432'", "'testdb'", "'1234'", "'test'")
    # Connect local db
    MasterServer.db.Connect_DB()
    SlaveServer.db.Connect_DB()
    # DB = db for grammar error
    MasterServer.DB = MasterServer.db
    SlaveServer.DB = SlaveServer.db
    # Initalize Admin
    MasterServer.Admin = AdministratorClass.Administrator('Wonseok', '/root/바탕화면/ServerPlayer/Report/', 'root', 'Admin', 'root')
    SlaveServer.Admin = AdministratorClass.Administrator('Wonseok', '/root/바탕화면/ServerPlayer/Report/', 'root', 'Admin', 'root')
    # Push the admin
    MasterServer.local_admin = MasterServer.GetServerOwner()
    SlaveServer.local_admin = SlaveServer.GetServerOwner()
    
    '''
    * Real test of DBE
    '''
    # Connection test (1-1, 1-2)
    DBE = DatabaseBackupEngine(MasterServer, SlaveServer, MasterServer.Admin)
<file_sep>''' 
 If you want to share this system to others or another people,
you have to execute this file to remove your own data. 
unless, your data will be get fire by someone.
So please erase your local data from here. I believe you may understand.
'''
import os, sys

def ConfigureFire() :
    Configure = open('Configure.txt', 'w')
    Configure.write('Execute=no')
    Configure.close()
    
def UserConfigFire() :
    os.system('rm ./UserConfig/*.txt')    

def ReportFire() :
    os.system('rm ./Report/*.txt')

def srcFire() :
    os.system('rm -r src')

def FireForGit() :
    ConfigureFire()
    UserConfigFire()
    ReportFire()
    srcFire()
    MakeRequirements()

def MakeRequirements() :
    os.system('pipreqs . --force')

# If you want to share your project to git, 
# just execute it!
if __name__ == '__main__' :
    FireForGit()
<file_sep># SOUL  the server manager.


* System requirements
 - Python 2.7 needs.
 - Your OS must be Linux (Ubuntu will be best choice)
 
* pre - requirements 
pip install -r requirements.txt
apt get install sshpass

* How to execute?
cd -/ServerManager-for-Buzzz
python ./System/Engine.py

* Before share < Caution! >
cd -/ServerManager-for-Buzzz
python ./BeforeShare.py
<file_sep># @Author       Wonseok
# @Designer     Wonseok
# @Start at     Aprl. 13
# @Last at      Aprl. 13
# @Music        Parallax, U-Won-Jae
# @Information


import os, sys
from SystemLoader import SystemLoader
from Connector import Connector
from Configurator import Configurator
sys.path.insert( 0, os.getcwd() )
from ObjectInfo import DatabaseClass
from ObjectInfo import Server
# if you want to use server class in server, you have to write Server.Server( ...  ) - interesting issue

class Kernel(object) :
    # SystemLoader which kernel has provide information to connector,
    # and check if connection is successful. If not, kernel will load logger
    # to save logs for programmer.

    def serverToServer(self, server) :
        # the server is just element in list.
        # Server is a element which is class named 'server'
        # print(server)
        _Server = Server.Server( server[0], server[1], server[2], server[3], server[4], server[5], server[6], server[7], server[8], server[9], server[10] )
        _Server.db = self.Conn.db
        _Server.admin = self.Conn.admin
        return _Server


    # def __init__(self):
    #     print('Log : Kernel Initilizer is loaded!')
    #     self.Conn = Connector()


    def __init__(self, object = None) :
        # Initializer check
        if( object == None ) :
            print('Kernel error. You must define kerenel with System Loader!')
            return

        self.SystemLoader = object
        #self.SystemLoader.printInfo()
        self.GoodServerList = []
        self.BadServerList = []

        self.Conn = Connector(self.SystemLoader) # Conn has logger DB
        self.GoodServerList = self.Conn.GoodServerList
        self.BadServerList = self.Conn.BadServerList

        Configurators_Badguys = []
        print("  Re-checking bad servers connection starts")
        for i in self.BadServerList :
            serv = self.serverToServer(i)
            Conf = Configurator(serv, self.Conn.admin)
            Conf.ConnectSSH()
            Configurators_Badguys.append(Conf)

        print('Kernel is successfully loaded!')



    def __str__ (self):
        return "KERNEL"
<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-

import os, sys
# @Author       Wonseok
# @Designer     Wonseok
# @Start at     May 2
# @Last at      May 2
# @Music        CRAYON - G.DRAGON
# @Information  This class is only for User Interface.
#               You don't need to be worried by designing UI.

from anytree import Node, RenderTree
sys.path.insert( 0, os.getcwd() )
from System import FileToServer
from ObjectInfo import Server
from ObjectInfo import DatabaseClass
from System import Kernel
class UserInterface(object) :


    def clear(self) :
        # you just call this function to clean the screen.
        os.system(self.cls)

    def __init__(self, objects ) :
        # I want to make this class in GUI mode, but I don't have enough time and work force.
        self.SCPManager = FileToServer.SCPManager()
        self.MODE = 'CUI'
        self.Engine = objects
        if( objects.OS_SORT == 1 ) : # 1 is Linux
            self.cls = 'clear'
        elif( objects.OS_SORT == 2 ) :   # Windows
            self.cls = 'cls' 


        # level = 0, you have to exit menu.
        self.root = Node("Null")

        # level = UI
        self.nodUI = Node("UserInterface", parent=self.root)

        # level = 2, PSM, DM, CM, SM, PO
        self.ServerMenu = Node("PrintServerManageMenu", parent=self.nodUI)
        self.DBMenu = Node("DatabaseManage", parent=self.nodUI)
        self.ConfigMenu = Node("Configuration Mode", parent=self.nodUI)
        self.SecurityMode = Node("Security Mode", parent=self.nodUI)
        self.PowerOff =  Node("Power Off", parent=self.nodUI)

        # level = 3, TM, ID, GBC, FM
        self.TargetManage = Node("Target Manage", parent=self.ServerMenu)
        self.InstallDatabase = Node("Install database", parent=self.ServerMenu)
        self.GoBackupCons = Node("Go Backup Console", parent=self.ServerMenu)
        self.FirewallManag = Node("Firewall manage", parent=self.ServerMenu)
            
        # level = 4, TMM
        self.TMM = Node("Target Manage Menu", parent=self.TargetManage)
            
        # level = 5, AM, DM, SystemUpdate, ThrowMessage
        self.AM = Node("AddtargetMenu", parent=self.TMM)
        self.DM = Node("DeltargetMenu", parent=self.TMM)
        self.SystemUpdate = Node("System Update", parent = self.TMM)
        self.ThrowCommandMenu = Node("Throw command menu", parent=self.TMM)
        
        # level = 6, OSUpgrade, Cron update
        self.OSUpgrade = Node("Operating System Upgrade", parent=self.SystemUpdate)
        self.UpdateUpgrade = Node("Update & Upgrade", parent=self.SystemUpdate)
        self.CronUpdate = Node("Cron update", parent=self.SystemUpdate)
        self.ThrowFile = Node("Throw File", parent=self.ThrowCommandMenu)
        self.ThrowMsg = Node("Throw Command", parent=self.ThrowCommandMenu)
        
        # level = 7
        self.SetCommandForFile = Node("Set the command for file", parent = self.ThrowFile)
        self.SendCommand = Node("Send command", parent= self.ThrowFile)

    def SystemUpdateMenu(self,target, nod) :
        self.PrintTargetMenu(target)

        print('')
        print( '1 - 1. Operating System Upgrade')
        print( '1 - 2. Update & Upgrade')
        print( '1 - 3. update at cron ')
        print(' 1 - 0. return to menu ')

        usr_input = self.InputByUsr( 'Which one do you want to go?', 3 )
        if( usr_input == 1 ) :
            nod[0] = self.OSUpgrade
        elif( usr_input == 2 ) :
            nod[0] = self.UpdateUpgrade
        elif( usr_input == 3 ) :
            nod[0] = self.CronUpdate
        elif( usr_input == 0 ) :
            nod[0] = nod[0].parent

        raw_input('')

    def OperatingSystemUpgrade(self, target=[[]], nod=None ) :
        self.PrintTargetMenu(target)
        ''' 
            You can add more OS in here 
        '''
        OSList = {}
        OSList['ubuntu'] = []
        OSList['cent'] = []
        OSList['debian'] = []
        for i in target :
            if( i == [] ) :
                print("You must regist target in befre menu.")
                raw_input('')
            else :
                if( str(i[8]).find('Ubuntu') != -1 ) :
                    OSList['ubuntu'].append(i)
                elif( str(i[8]).find('Cent') != -1 ) :
                    OSList['cent'].append(i)
        print(OSList)
        raw_input()

        return OSList


    def InputByUsr(self, msg='', numMax=None) :
        
        if numMax == None :
            return raw_input(msg)

        while( True ) :
            usr_input = int( input('What do you want to do? : '))
            if( usr_input < 0 or usr_input > numMax ) :
            # Zero always be 'power off'
                print('Input Error, try again!')
                flag = raw_input(msg)
            else :
                return usr_input


    def PrintMainMenu(self, badnum, goodnum, nod) :
        self.clear()
        print('                  *         *         *                 ')
        print('              *      SOUL      *             *          ')
        print('  *              * *     *       *                 *    ')
        print('                                                 ver 0.5')
        print('')
        print('    1. Server manage.                                ')
        print('    2. Database manage.                              ')
        print('    3. Configuration mode.                           ')
        print('    4. Security mode.                                ')
        print('    0. Power off.                                    ')
        print('')
        print('')
        print(' Num( bad servers  ) : ' + str(badnum))
        print(' Num( good servers ) : ' + str(goodnum))
        print('')
        usr_input = self.InputByUsr( 'Which one do you want to go?', 4 )                                    # if you add functions, you have to add '1' in parameter.
        
        if usr_input == 1  :
            nod[0] = self.ServerMenu
            raw_input()
        elif usr_input == 2  :
            nod[0] = self.DBMenu
        elif usr_input == 3 :
            nod[0] = self.ConfigMenu
        elif usr_input == 4 :
            nod[0] = self.SecurityMode
        # add additional function at this line.
        else : 
            nod[0] = self.root 

    def PrintTargetMenu(self, target=[]) :
        # Target list is chosen targets which user picked.

        print('                                              ')
        print(' Target Console ----------------------------------------------- ')
        for i in target  :
            print( '  [*]. ' + str(i) )
        print(' --------------------------------------------------- target end.')


    def PrintServerManageMenu(self, target=[[]], nod=None) :
        # Target list is chosen targets which user picked.
        self.PrintTargetMenu(target)

        print('')
        print( '1 - 1. Target manage')
        print( '1 - 2. Install database ')
        print( '1 - 3. Go backup console ')
        print(' 1 - 4. Firewall manage ')

        print(' 1 - 0. Return')
        key =  self.InputByUsr('Which one do you want to go?', 4)
        if( key == 1 ) :
            nod[0] = self.TargetManage
        elif key == 2 :
            nod[0] = self.InstallDatabase
        elif key == 3 :
            nod[0] = self.GoBackupCons
        elif key == 4 :
            nod[0] = self.FirewallManag
        else :
            print('input error!')
        raw_input('')

    def TargetManageMenu(self, target=[], nod=None) :
        self.PrintTargetMenu(target)

        print( '1-1 - 1. Add target.')
        print( '1-1 - 2. Del target.')
        print( '1-1 - 3. System Update Menu')
        print(' 1-1 - 4. Throw Command Menu')
        print( '1-1 - 0. Return.')
        key =  self.InputByUsr('Which one do you want to go?', 4)
        if( key == 1 ) :
            nod[0] = self.AM
        elif key == 2 :
            nod[0] = self.DM
        elif key == 3 :
            nod[0] = self.SystemUpdate
        elif key == 4 :
            nod[0] = self.ThrowCommandMenu
        elif key == 0 :
            nod[0] = self.ServerMenu
        else :
            print('Input error!')
            raw_input()
    
    #[[2, 22, u'ssh', u'123', u'123', u'123', u'123', 123, u'test', u'test', u'YES', u'2018-05-07 21:52:48.022944', None, None], [4, 22, u'ssh', u'172.16.58.3', u'P]9p{PWKRu=+o7y]', u'root', u'Wonseok.J', 970403, u'CentOS 7 x64', u'WonseokTest2Cent', u'', u'2018-05-07 21:52:58.786149', None, None], [6, 23, u'ssh', u'172.16.58.3', u'Wonseok786!', u'swc', u'Wonseok.J', 1065, u'Ubuntu14', u'WonseokTest3', u'YES', u'2018-05-07 21:53:49.822362', None, None]]
    def PrintAllTargetsDetails(self, targets=[[]], badTargets=[[]], goodTargets=[[]] ,nod=None):
        # Target list is chosen list user picked, and allTargets list is a list of all servers.
        # [ID], [PORT], [SORT], [IP], [PASSWORD]. [USRNAME], [OWNR NAME], [ OWNR_ID ], [SERVER OS], [SERVER NAME], [IS ERROR], [LAST_LOGIN], [dbkey], [obj key]
        print("CONNECTION STATUS : BAD ")
        print("[ADDED]\t\t[ER]\t[ID]\t\t[SERVER NAME]\t\t\t\t[IP]\t\t\t\t[SSH ID]\t\t[SSH PW]\t\t\t[LAST LOGIN]")
        for badtarget in badTargets :
            if badtarget == [] : break
            print("{}\t\t{}\t{}\t\t{}\t\t\t\t{}\t\t\t\t{}\t\t{}\t\t\t{}".format(str(badtarget in targets), str(badtarget[10]), str(badtarget[0]), str(badtarget[9]), str(badtarget[3]), str(badtarget[7]),str(badtarget[4]), str(badtarget[11])))
        print("")
        print("[ADDED]  CONNECTION STATUS : GOOD")
        for badtarget in goodTargets :    # Yes I know. badtarget must be good target. but... I'm lazy... so.. I won't change it. badtarget is good target.. you know...        
            if badtarget == [] : break
            print("{}\t\t{}\t{}\t\t{}\t\t\t\t{}\t\t\t\t{}\t\t{}\t\t\t{}".format(str(badtarget in targets), str(badtarget[10]), str(badtarget[0]), str(badtarget[9]), str(badtarget[3]), str(badtarget[7]),str(badtarget[4]), str(badtarget[11])))

        print("\n\n")
        print("Already Targets : ")
        print("[ID]     [SERVERNAME]        [IP]        [SORT]")
        for target in targets :
            if target == [] : break
            print("{}       {}                  {}          {}".format(str(target[0]), str(target[9]), str(target[3]), str(target[2])))

        nod[0] = self.TMM
        raw_input('')

    def ChkValue(self, id, target, bad, good) :
        '''
        @return     1 - is in target,       MSG = None <type>
                    2 - is in bad           MSG = list[ that node ]
                    3 - is in good          MSG = list[ that node ]
                    4 - not found           MSG = That is not in both bad and good lists.
        '''
        # target, bad, good = [ [] ] is list in list.
        # check is in target.
        for i in target :
            if i == [] : break
            #print(id,type(id), i[0], type(i[0]))
            if( str(id) == str(i[0]) ) :
                return 1, i
        
        # check is in bad
        for i in bad :
            #print(id,type(id), i[0], type(i[0]))
            if i == [] : break
            if( str(id) == str(i[0]) ) :
                return 2, i
        
        # check is in good
        for i in good :
            #print(id,type(id), i[0], type(i[0]))
            if i == [] : break
            if( str(id) == str(i[0]) ) :
                return 3, i
        
        return 4, 'That is not in both bad and good lists.'



    def AddtargetMenu(self, target=[[]], badTargets = [[]], goodTargets = [[]], nod=None) :
        self.PrintAllTargetsDetails(target, badTargets, goodTargets,nod)
        print("\n")
        want_id = self.InputByUsr('Which one do you want to add? input [ID] value : ', None)
        num, msg = self.ChkValue(want_id, target, badTargets, goodTargets)
        if( num == 2 or num == 3 ) :
            if( target.count([]) != 0 ) : target.remove([])
            target.append( msg )
            nod[0] = nod[0].parent
        else :
            print("Caution! Error occured!")
            print("Error code : " + str(num))
            print("Error msg : " + str(msg))
            print("\nReturn before menu!")

        

        
    def DeltargetMenu(self, target=[[]], badTargets = [[]], goodTargets = [[]], nod=None) :
        self.PrintAllTargetsDetails(target, badTargets, goodTargets,nod)
        print("\n")
        want_id = self.InputByUsr('Which one do you want to delete? input [ID] value : ', None)
        num, msg = self.ChkValue(want_id, target, badTargets, goodTargets)
        if( num == 1 ) :
            target.remove( msg )
            nod[0] = nod[0].parent
        else :
            print("Caution! Error occured!")
            print("Error code : " + str(num))
            print("Error msg : " + str(msg))
            print("\nReturn before menu!")
            raw_input()

    def func_ThrowCommandMenu(self,  nod=None) :
        self.clear()
        print( '1-1-4 - 1. Throw file')
        print( '1-1-4 - 2. Throw Command')
        key =  self.InputByUsr('Which one do you want to go?', 2)
        if( key == 1 ) :
            nod[0] = self.ThrowFile
        elif key == 2 :
            nod[0] = self.SendCommand
        else :
            nod[0] = nod[0].parent
            print('Input error!')
            raw_input()

    def getServerFromTarget(self, target=[], nod=None) :
        return self.Engine.KernelObj.serverToServer(target)

    # Return Server class by server's ID.
    def getServerFromTargetsById(self, id, target=[[]]):
        # Target list is chosen list user picked, and allTargets list is a list of all servers.
        # [ID], [PORT], [SORT], [IP], [PASSWORD]. [USRNAME], [OWNR NAME], [ OWNR_ID ], [SERVER OS], [SERVER NAME], [IS ERROR], [LAST_LOGIN], [dbkey], [obj key]
        for Serv in target :
            if Serv[0] == id :
                return self.Engine.KernelObj.serverToServer(Serv)
        return None
        
    def func_ThrowFilescp(self, nod=None) :
        self.clear()
        print('1..- 1. Set the command for file')
        print('2..- 2. Send command')
        key =  self.InputByUsr('Which one do you want to go?', 2)
        if( key == 1 ) :
            nod[0] = self.SetCommandForFile
        elif key == 2 :
            nod[0] = self.SendCommand
        else :
            print("Input error!")
            raw_input()

    # This function is linked with 'FILE TO SERVER.py'
    def func_SetCommandForFile(self,  target=[[]],nod=None ) :
        self.clear()
        print('   ! Caution! ' )
        print('     - your command is will be sent for your targets. ')
        print('     - even if you want to back, system can not be back. ')
        
        # Sync target with SCPManager.Target
        for i in target :
            self.SCPManager.TryAddSlave(self.getServerFromTarget(i))

        Flag = str(raw_input(' Do you want to have specific target? (y/n) '))
        if( Flag == 'n' or Flag == 'N') :
            self.SCPManager.TargetSetById( 'all' )
        else :
            print('If you want to end or exit, input -1')
            tmpServIds = []
            while( True ) :
                tmpServIds.append(int( input('ID -> ')))
                if( tmpServIds[ int(len(tmpServIds)) - 1] == -1) : # The last of tmpServIds
                    tmpServIds.pop()
                    break;
            for i in tmpServIds :
                tmpServer = self.getServerFromTargetsById(i)
                if( tmpServer == None ) :
                    print("Error occurs at 'UIManager.py[func_setCommandForFile]'")
                self.SCPManager.TargetSetById( tmpServer )
    
    def func_SendCommand(self, nod=None) :
        '''
        [ID]    [COMMAND]
        1       asf
        2       12
        3       ads
        4       asd

        Are you sure? or Delete? ( sure = 1, delete = 2)
        '''
        print('[ID]     [COMMAND]')
        self.SCPManager.PrintTargetCommands()
        print('')
        flag = int(input('Are you sure? or Delete? ( sure = 1, delete = 2 )'))
        if( flag == 1 ) :
            self.SCPManager.SendToAllTargets()
        else : 
            print('Input ids you want to delete.')
            print('If you want to end or exit, input -1')
            tmpServIds = []
            while( True ) :
                tmpServIds.append(int( input('ID -> ')))
                if( tmpServIds[ int(len(tmpServIds)) - 1] == -1) : # The last of tmpServIds
                    tmpServIds.pop()
                    break
            for i in tmpServIds :
                tmpServ= self.getServerFromTargetsById(i)
                if( tmpServ == None ):
                    print("UImanager.py[func_sendcommand] has some issue")
                    continue
                self.SCPManager.DeleteServerInTargets( tmpServ )<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-

import os, sys
sys.path.insert(0, os.getcwd() )
from ObjectInfo import DatabaseClass
from ObjectInfo import AdministratorClass
from ObjectInfo import Server
import time, datetime
from System import Logger

# @Author       Wonseok
# @Designer     Wonseok
# @Start at     Aprl. 18
# @Last at      Aprl. 18
# @Music        
# @Information  This class is made for checking the system. You can check the system to use this class.
#           But if you want to make server checker, server checker must has server class,
#           And define some modules.
#            Database checker may need Database class. That's all.

class CheckerEngine (object) :
    def __init__(self, LocalServer=None, LocalDatabase=None, LocalAdmin=None) :
        # Checker must has local settings.
        self.LocalServer = LocalServer
        self.LocalDatabase = LocalDatabase
        self.db = self.LocalDatabase # for Logger
        self.LocalAdmin = LocalAdmin
        self.Logger = Logger.Logger(self)
        self.EngineName = "CHECKERENGINE"
        

    def CheckerConditionCheck(self) :
        # Server check.
        isOkay, Msg = self.LocalServer.isTryConnect()
        if( isOkay != True ) :
            self.SendLog_ServerConnectionBad(self.Logger, Msg)
            return False, "Program can not make a link with local server. Check the log."
            # Send Log
        isOkay, Msg = self.LocalDatabase.isTryConnect()
        if( isOkay != True ) :
            return False, "Program can not link with local database. check the log."
            self.SendLog_DatabaseConnectionBad(self.Logger, Msg)
            # Send Log
        if( str(self.LocalAdmin) != "ADMINISTRATORCLASS" ) :
            return False, "Program can not make a link with local administrator. Check the admin."
            # 여기 하면 됨
        return True, "Good"
            # Send Log

    def SendLog_ServerConnectionBad (self, Logger, ExceptionMsg) :
        # Log structure :
        ##   [ADMIN.ID] tried to connect [ServerID] by [ServerRole]@[Host] at [Date.time]
        ##   Server was [Server.isOkay]. And program tried to connect, but server connection is BAD.
        ##   specific report which pssh says is here : [Exception E]
        strLogMsg = str(self.LocalAdmin.ID) + " tried to connect " + str(self.LocalServer.ID) + " by " + str(self.LocalServer.CONNECTION_USERNAME)+"@" + str(self.LocalServer.CONNECTION_IPADDRESS)  + " at " + str(datetime.datetime.now()) + "\n" + \
                    "Server was " + self.LocalServer.IS_ERROR + ". And program tried to connect, but server connection is BAD." + "\n" + \
                    "specific report which pssh says is here : " + str(ExceptionMsg)
        Logger.SetOrigin('KNOWN_LOG')
        RK = Logger.MakeReport( 'SERVICE_STATUS_CHECK', self.LocalAdmin.PATH, self.LocalAdmin.NAME, strLogMsg)
        Logger.push_log( self.EngineName, self.LocalServer.ID, RK, 'KNOWN_LOG', 'BAD', 'CheckerEngine.SendLog_ConnectionBad', 'SERVER')

    
    def SendLog_DatabaseConnectionBad (self, Logger, ExceptionMsg) :
        # Log structure :
        ##   [ADMIN.ID] tried to connect Database ID : [DB_ID]
        ##   Database Setting is : 
        ##   SORTS, HOSTS, NAME, PW, USER, DB_KEY, IS_CONNECTED, OBJECT, SERVER_KEY :
        ##   Values;
        strLogMsg = str(self.LocalAdmin.ID) + " tried to connect Database ID : " + str(self.LocalDatabase.DB_KEY) + "\n" + \
                    "Database setting is : " + "\n" + \
                    "SORTS, HOSTS, NAME, PW, USER, DB_KEY, IS_CONNECTED, OBJECT, SERVER_KEY : " + "\n" + \
                    self.LocalDatabase.getInfo() + "\n" + \
                    "Exception Msg : " + ExceptionMsg + "\n"
        Logger.SetOrigin('KNOWN_LOG')
        RK = Logger.MakeReport( 'SERVICE_STATUS_CHECK', self.LocalAdmin.PATH, self.LocalAdmin.NAME, strLogMsg)
        Logger.push_log( self.EngineName, self.LocalAdmin.SERVER_KEY, RK, 'KNOWN_LOG', 'BAD', 'CheckerEngine.SendLog_ConnectionBad', 'SERVER')

    def __str__(self) :
        return "CHECKERENGINE"<file_sep>service postgresql start
python /usr/local/lib/python2.7/dist-packages/pgadmin4/pgAdmin4.py
<file_sep>psycopg2==2.7.4
SQLAlchemy==1.2.5
anytree==2.4.3
pandas==0.22.0
Fabric==1.14.0
pexpect==4.5.0
<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-

import os, sys
sys.path.insert(0, os.getcwd() )
from ObjectInfo import DatabaseClass
from ObjectInfo import AdministratorClass
from ObjectInfo import Server
from CheckerEngine import CheckerEngine
import time, datetime
from System import Logger

# @Author       Wonseok
# @Designer     Wonseok
# @Start at     Aprl. 18
# @Last at      Aprl. 18
# @Music        Sing a song at TV program - Shin Yong Jae.
# @Information  This class is made for checking the database system. This system is a child class of Checker Engine.
#           You must add some functions and values in this functions. that's all.

class DatabaseChecker( CheckerEngine) :
    def __init__(self, LocalServer=None, LocalDatabase=None, LocalAdmin=None ) :
        CheckerEngine.__init__(self, LocalServer, LocalDatabase, LocalAdmin)
        self.Logger = Logger.Logger(self)
        self.EngineName = "DATABASECHECKER"

    def CheckerConditionCheck(self) :
        isOkay, msg = self.CheckerConditionCheck()
        if( isOkay ) : 
            return True, "Good"
        else :
            return False, msg
        
    <file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-

import os, sys
sys.path.insert(0, os.getcwd() )
from ObjectInfo import DatabaseClass
from ObjectInfo import AdministratorClass
from ObjectInfo import Server
from CheckerEngine import CheckerEngine
import time, datetime
from System import Logger

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.header import Header
from email import encoders



from pexpect import pxssh
import getpass


# @Author       Wonseok
# @Designer     Wonseok
# @Start at     Aprl. 20
# @Last at      Aprl. 20
# @Music        Time paradox
# @Information  This class will send the report from Serverchecker or DatabaseChecker to you.
#           This class will supports user to check server conditions by watching mail from this class
#           That's why this class name is mail checker.
# 
class MailChecker( CheckerEngine ) :
    '''
    @Written by wonseok.
    @Date at 2018. 04. 20

     Dear my source code watchers! Thank you for watching my sources. If you have some issues, please mail me
    <EMAIL>! I'm glad to see all your issues and reports!
     Why I write letters in here is, this class contains my company boss' mail ID and password.
    Please do not use that and log-in. If you do that I will fell really sad and have to lock my git-hub.
    So, I hope that I won't locak any source codes and make my source open.
     +) That mail is for using test. not contain any heavy infromation, and I got the agree from him.
     But I don't want other guys use that account.
     Thanks!
     '''
     # Nothing special with ServerChecker.
    def __init__(self, LocalServer=None, LocalDatabase= None, LocalAdmin=None ) :
        # For sending mail, you need host, port, mimebase.
        # If you want to use 'Microsoft mail server', you have to change 
        #    --> MailChecker.host = 'smtp.live.com' (maybe)
        # And mimebase is for mixed mail (text+image+content ... etc)
        
        '''
            About Plain.

            The mail plain is for mail getter. Think about it, don't you think if you
            get mail just a log, it is not kind? So, I made a basis of 'mailplain'.
            The name is MailPlanText at '/LocalAdmin.PATH/MailBase/, name is 'MailPlainText'
            The content of 'mailplaintext' will be at front of mail. 
        '''
        CheckerEngine.__init__(self, LocalServer, LocalDatabase, LocalAdmin )
        self.Logger = Logger.Logger(self)
        self.EngineName = "MAILCHECKER"
        self.host = 'smtp.gmail.com'    # This is a host of smtp - googel-Gmail service.
        self.port = '587'               # This is a port of smtp at google-Gmail service..
        self.MIMEBASE = ['multipart', 'mixed'] 
        # Mail base setting starts
        self.MailBaseFile = open(self.LocalAdmin.PATH+"MailBase/MailPlainText.txt", 'r') # check the log !
        self.Content = ""               # define
        while True :                    # Here is the line for setting plain text.
            line = self.MailBaseFile.readline()
            if not line : break
            else : self.Content += (line + "\n")
        # Mail base setting ends


    # Find the report by using name which you put at parameter.
    def AddReportInContent_byName(self, Name) :
        BaseFile = open(self.LocalAdmin.PATH+str(Name), "r")
        while True :
            line = BaseFile.readline()
            if not line : break
            else : self.Content += (line+"\n")

    # This function is only for smtplib
    def MailServer_Login(self, senderAddress, senderPassword ) :
        # If you want to make your own mail server, call the smtplib.SMTP!
        # like this!
        self.mailServer = smtplib.SMTP(self.host, self.port)    # you need host and port number.
        self.mailServer.set_debuglevel(1)                       # This will print issues from google server.
        self.mailServer.ehlo()                          # This is the protocol regulation of SMTP
        self.mailServer.starttls()                      # TLS Service starts. if you don't want it, don't call this function.
        self.mailServer.ehlo()                          # After call the tls service, check the server if I can call mail functions

        self.senderAddress = senderAddress
        self.senderPassword = <PASSWORD>

        self.mailServer.login(senderAddress, senderPassword)

    def MaillServer_CreateMail(self, recipient, Subject, Content) :
        self.MailMsg = MIMEMultipart('alternative')
        self.MailMsg['From'] = self.senderAddress
        self.MailMsg['To'] = recipient
        self.MailMsg['Subject'] = Header(Subject, 'utf-8')
        self.MailMsg.attach(MIMEText(self.Content + Content, 'plain', 'utf-8'))
        self.recipient = recipient

    def MailServer_SendMail(self) :
        try :
            if( self.MailMsg['From'] != None and self.MailMsg['To'] != None and self.MailMsg['Subject'] != None ) :
                self.mailServer.sendmail(self.senderAddress, self.recipient, self.MailMsg.as_string())
                self.mailServer.close()
            else :
                print('Error!')
        except Exception as e :
            print(e)


if __name__ == "__main__" :
    S = Server.Server(1, 22, 'ssh', '192.168.127.12', '3@mHze=5K{1wj){}', 'root', 'Wonseok.J', 970403, 'ubuntu', 'wonseokbuntu', None, '2018-03-02', None, None)
    S.DB = DatabaseClass.DB("psql", "'localhost'", "'5432'", "'testdb'", "'1234'", "'test'")
    S.DB.Connect_DB()
    S.db = S.DB
    S.Admin = AdministratorClass.Administrator('Wonseok', '/root/바탕화면/ServerPlayer/Report/', 'root', 'Admin', 'root')
    
    MailChecker = MailChecker(S, S.DB, S.Admin)
    MailChecker.MailServer_Login('<EMAIL>', '<PASSWORD>!')
    MailChecker.AddReportInContent_byName('1.wonseokbuntu.LastCommand.txt')
    msg = '\n\nTEST at, 2018-04-2001:37:35:378081 and the server host name is "wonseokbuntu" ' + '\n\n ATTENTION! THIS IS FOR TEST \n\n'
    MailChecker.MaillServer_CreateMail('<EMAIL>', 'Last log from server test [test]', msg)
    MailChecker.MailServer_SendMail()

<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-

# @Author       Wonseok
# @Designer     Wonseok
# @Start at     Aprl. 10
# @Last at      Aprl. 15
# @Music        Pianoman - MAMAMOO
# @Information  This class makes report, make and throw log to local DB.
#               You have to make sure to connect your local DB with program.
import os, sys
import psycopg2
import time, datetime

sys.path.insert(0, os.getcwd() )

from ObjectInfo import DatabaseClass
def Generate_PrivateCode():
    # Return structure is :
    # YEAR-MONTH-DAYHOUR:MIN:SEC.MICROSEC
    # ex) 2017-04-03:08:40:00.010101
    return str(datetime.datetime.now()).replace(" ","")


def Generate_Filename(className, ownerName) :
    # Return structure is :
    # (ClassName).(OwnerName).log
    if( ownerName == "" ) :
        ownerName = "Logger"
    else :
        return className+"."+ ownerName +".log"


def Generate_ReportKey(FileName) :
    # Return structure is :
    # (ClassName).(OwnerName).log.(Time)
    # ex) Kernel.log.2018-04-03-08:40:00.01010...
    # https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
    # for this rule (windows file name rule) ':' is changed for '-' --> ex) Kernel.log.2018-01-01-01-01-01.01010...
    return FileName + str(datetime.datetime.now()).replace(" ","")

def Exit(code) :
    # code 100 : OS Error. Your os is not supported in this system.
    print("WARNNING : You can't execute program. \n Error code : " + str(code))
    SetExecuteLog('Engine initialize is failed', code)
    exit()

BeforeTime = datetime.datetime.now()
def SetExecuteLog(code, ErrorCode) :
    global BeforeTime
    now = datetime.datetime.now()
    LogFile = open(os.getcwd() + '/UserConfig/LoggerLog.txt', "a")
    LogFile.write('Code : ' + str(code) + '\n')
    if( ErrorCode ) :
        LogFile.write('ErCode : ' + str(ErrorCode) + '\n')
    LogFile.write('Written time : ' + str(now) + ' [' + str(now - BeforeTime) + ']'+ '\n')
    BeforeTime = now

class Logger(object) :
    
    # If you want just define logger,
    def MakeReport(self, ReportType, Path, Name, Content) :
        # push_log( self, request_key, server_key, ReportKey, origin_key, status_key, return_val, program_key )
        FileName = Generate_Filename(self.className, Name) # it is as same as file name
        ReportKey = Generate_ReportKey(FileName)

        isInServer, ErrorMsg = self.track_exists('report', 'report_type', ReportType)
        if( isInServer ) :
            # Make file for report
            ReportFile = open(Path+FileName+".txt", "a")
            ReportFile.write('\n'+Content)
            ReportFile.close()

            # Push log for you made a report
            vars = "'" + ReportKey + "', '" + ReportType + "', '" + str(datetime.datetime.now()).replace(" ","") + "', '" + Path +"', '" + FileName +"'"
            # Aprl 13. Name -> FileName by wonseok

            self.SQL_Insert_Into_values('report', vars)
            # Push log for return report key
            return ReportKey
        else :
            UnknownMsg = "\nAnd unknown error occured in Logger.MakeReport. You have to check it.\n"
            ReportFile = open(Path+FileName+".txt", "a")
            ReportFile.write('\n'+Content + UnknownMsg)
            ReportFile.close()
            return ReportKey
            # RK = self.MakeReport( 'WARNING_SERVICE_REPORT', Path, 'Logger', 'Report type : ' + ReportType + ' is not in DB! Please check service owner... before content : ' + Content + ' by ' + Name)
           #  vars = "'" + ReportKey + "', 'ERROR_SERVICE_REPORT', '" + str(datetime.datetime.now()).replace(" ","") + "', '" + Path + "', '" + FileName + "'"
            # self.SQL_Insert_Into_values('report', vars)
            # self.push_log( 'DB_REQUEST', 'localhost', RK, 'PROGRAM_OWNER', 'BAD', 'None', 'LOGGER')


    def SQL_Select_From_Where_In(self, column_names, table_name, column_name2, values) :
        cur = self.conn.cursor()
        cur.execute("SELECT " + column_names + " FROM " + table_name + " WHERE " + column_name2 + " IN " + values)


    def SQL_Insert_Into_values(self, table_name, values) :
        cur = self.conn.cursor()
        cur.execute("INSERT INTO " + table_name + " VALUES ( " + values + " )" )
        self.conn.commit()


    def track_exists(self, table_name, column_name2, values):
        # If there is no value in table #table_name, return None.
        # Not if, return True.
        # It is differnt at SQL_Select_From_Where_In.... But it can be same.. so plz check the code.
        # If you can think better idea at code, modify it and report me please. :)
        try :
            cur = self.conn.cursor()
            cur.execute("SELECT * FROM " + table_name + " WHERE " + column_name2 + " =  '" + values + "' ")
        except psycopg2.Error as e :
            print(e.message)
            print('error occur!')
            return False, e
        
        except Exception as e :
            print(e)
            return False, e

        return True, None

    def SQL_Update_Set_Where(self, table_name, column_name, value, whereCondition, whereValue ) :
        self.conn.cursor.execute("UPDATE " + table_name + " SET " + column_name + " = " + value + " WHERE " + whereCondition + " = " + whereValue )


    def SetOrigin(self, origin_k) :
        if( self.track_exists(  'origin', 'origin_key', origin_k  ) == False ) :
            # No origin_k is in there [ Before test ]
            # 6646464
            SetExecuteLog(str(origin_k) + ' is not in db! program exit!', 'LOGER.SETORIGIN')
            print( 'Please check the Logger.log' )
            Exit('Logger.setorigin')
        else :
            SetExecuteLog(str(origin_k) + ' is in DB', None)


    def Connect_LogDB(self) :
        try :
            self.conn = psycopg2.connect(self.conn_string)
        except psycopg2.Error as e :
            # Throw error log < DB Connection failed >
            print(e.message)
            return False
        return True


    # If you define logger as something special
    def __init__(self, object=None) :
        if( object == None ) :
           print('Logger is made by nothing')
           self.className = ""
           self.Connect_LogDB()
        else:
            # print('Logger making start!')
            # print( object )
            self.className = str(object)
            self.object = object
            self.conn_string ="host="+object.db.HOST+" dbname=logdb "+ "user="+object.db.USER+" password="+<PASSWORD>
            self.DB_Connection = self.Connect_LogDB()

    def PushLog_UnknownError(self, Admin, location, ExceptionMsg=None) :
        # if( self.DB_Connection == False ) :
        #     print('DB CONNECTION FAIL CHECK THE LOGGER LOG')
        #     return
        # LogStructure :
        ## [ADMIN.ID] makes unknown error in [object], location is in [location] at [Date]
        ## Exception massage is [ExceptionMsg]. 
        ## --------------- Object info ---------------
        ## [Object.INFO]
        ## --------------- Admin  info ---------------
        ## [Admin.INFO]
        ## Log END.
        print('Unknown error occur!')
        strLogMsg = str(Admin.ID) + " makes unknown error in " + str(object) + ", location is in " + str(location) + " at " + str(datetime.datetime.now()) + "\n" + \
                    "Exception massage is " + str(ExceptionMsg) + ".\n" + \
                    "--------------- Object info ---------------\n" + \
                    str(self.object.getInfo()) + "\n" + \
                    "--------------- Admin  info ---------------\n" + \
                    str(Admin.getInfo()) + "\n" + \
                    "Log End."
        self.SetOrigin('UNKNOWN_LOG')
        RK = self.MakeReport('UNKNOWN', Admin.PATH, Admin.NAME, strLogMsg)
        self.push_log('DONT_KNOW', '404', RK, 'UNKNOWN_LOG', 'UNKNOWN', 'Logger.UnknownError', 'LOGGER')
        
    def push_log(self, request_key, server_key, Report_Key, origin_key, status_key, return_val, program_key, extraKey=None):
        # You have to check if those keys are in DB
        # push_log( self, request_key, server_key, Report_Key, origin_key, status_key, return_val, program_key )
        # 1) execution_id = yyyy-mm-ddhh:mm:ss.ms < Generate_PrivateCode >
        # request_key  = request_key
        # server_key = server_key
        # report_key = Report_key
        # origin_key = origin_key
        # status_key =  status_key
        # return_val = return_val
        # program_key = program_key
        # occur_timedetect
        # occur_timeends, return_value

        # track_exists(self, table_name, column_name2, values)
        if( self.track_exists('request_types', 'request_key', request_key) == None or  \
            self.track_exists('report',        'report_key',  Report_Key) == None or \
            self.track_exists('origin', 'origin_key', origin_key) == None or
            self.track_exists('status', 'status_key', status_key) == None or
            self.track_exists('program', 'program_key', program_key) == None) :
            # MakeReport(self, ReportType, Path, Name, Content)
            self.MakeReport('WARNING_SERVICE_REPORT', '/root/바탕화면/ServerPlayer/Report/', 'Logger', 'Please key check! : ' + \
            str(request_key, Report_Key, origin_key, status_key, program_key) )
            print('Line 129 is completed!')


        execution_id = Generate_PrivateCode() # Generate by time

        program_key = self.className
        occur_timedetect = str( datetime.datetime.now() )
        if( status_key == "IGNORE" or status_key == "DONE" ) :
            # "UPDATE " + table_name + " SET " + column_name + " = " + value + " WHERE " + whereCondition + " = " + whereValue
            try :
                self.SQL_Update_Set_Where('"execution_logs"', '"occur_timeends"', occur_timedetect , '"execution_id"', extraKey)
            # 여기 exception에서 infinite loop이 발생함.
            # sql try catch 오류 부분 해결할 것. 또한 아래 exception에서 psycopg exception이면 push log 하지 않아야함.
            # 재귀호출 ㄴㄴ
            except psycopg2.Error as e :
                print(e.message)
                print('Sorry. push log failed because of database connection')

            except Exception as e:
                RepContent = " This error is occured at Logger.py, You have to check if exceution_log is deleted! "
                #self.push_log('"CONNECT"', '"LOCALHOST"', '"PROGRAM_OWNER"', True, RepContent, '"DANGER"', None)
                print('line 144 is completed')

        else :
            # SQL_Insert_Into_values(self, table_name, values)
            # request_key, server_key, Report_Key, origin_key, status_key, return_val, program_key
            values = "'" + str(execution_id) + "', '" + request_key + "', '" + str(server_key) + "', '" + str(Report_Key) + "', '" + origin_key +"', '" + status_key + "', '" +  str(datetime.datetime.now()) + "', '" + ""+ "', '" + return_val + "', '" + program_key + "'"
            try :
                self.SQL_Insert_Into_values( 'execution_logs', values)
            except Exception as e :
                print(e.message)
                print('Sorry. push log failed because of database connection')

##                                      FOR TEST                              */
##                             Listening Roller coaster : Aprl 12.            */
##                                  <NAME>                         */
# You don't need to check under this line.
# Test is completed at Aprl 17.

def ParseDataList_FromPath(FilePath) :
    # returns file contents in 'FilePath'
    # You can check your dir by using'print(os.getcwd())'
    File = open(str(FilePath), "r")
    return File.readlines()


def ParseSortCont_FromString(List_forParse):
    # It only returns two data which are Sort and Content of string in listself.
    # EX) NAME:Wonseok
    # Sort = Name, Content = Wonseok
    ParsedStr = List_forParse.split('=')
    Sort = str(ParsedStr[0])
    Content = str(ParsedStr[1]).strip()
    return Sort, Content


class testClass(object):

    def __init__ (self) :
        # logger SETTINGS
        print("DB class is made")
        self.db = DatabaseClass.DB()
        self.LoadDBFiles()


    def __str__(self) :
        return "CONNECTOR"


    def LoadDBFiles(self):
        # ParseDataFromPath returns list in file contents
        # This function returns nothing
        print("load is complete")
        DatabaseData = ParseDataList_FromPath("./ProgramSettings/DataBaseSettings.txt")
        for i in range(0, len(DatabaseData)) :
            Sort, Content = ParseSortCont_FromString( DatabaseData[i] )
            if Sort == 'SORTS' :
                self.db.SORTS = Content
            elif Sort == 'USER' :
                self.db.USER = Content
            elif Sort == 'HOST' :
                self.db.HOST = Content
            elif Sort == 'PORT' :
                self.db.PORT = Content
            elif Sort == 'NAME' :
                self.db.NAME = Content
            elif Sort == 'PW' :
                self.db.PW = Content
            else : # For catch the error
                print (' INPUT ERROR AT DB SETTINGS.TXT ' )
                print (' (Input) Sort : ', Sort, ' Content : ', Content)
        # # END LOOP & for check
        # self.DB.printInfo()N


if __name__ == "__main__" :
    print("Logger tests ......... ")
    TestClass = testClass()
    print(Generate_PrivateCode())
    L = Logger(TestClass)
    L.SetOrigin('KNOWN_LOG')
    # self, ReportType, Path, Name, Content
    RK = L.MakeReport( 'ALERT_SERVICE_REPORT', '/root/바탕화면/ServerPlayer/Report/', 'Wonseok', 'LogCheck!' )
    # self, request_key, server_key, Report_Key, origin_key, status_key, return_val, program_key
    L.push_log( 'DONT_KNOW', 'localhost', RK, 'KNOWN_LOG', 'BAD', 'None', 'CONNECTOR')
<file_sep>from SystemLoader import SystemLoader
from Logger import Logger
import psycopg2
import pandas.io.sql as pdsql
import pandas
import sqlalchemy
from pexpect import pxssh
import time, datetime
import os

BeforeTime = datetime.datetime.now()
def SetExecuteLog(code, ErrorCode) :
    global BeforeTime
    now = datetime.datetime.now()
    LogFile = open(os.getcwd() + '/UserConfig/ConnectorLog.txt', "a")
    LogFile.write('Code : ' + str(code) + '\n')
    if( ErrorCode ) :
        LogFile.write('ErCode : ' + str(ErrorCode) + '\n')
    LogFile.write('Written time : ' + str(now) + ' [' + str(now - BeforeTime) + ']'+ '\n')
    BeforeTime = now

def SendLog_ConnectionBad (Logger, Admin, ID, Role, Host, ExceptionE) :
    # Log structure :
    ##   [ADMIN.ID] named [ADMIN.NAME] tried to connect [ServerID] by [ServerRole]@[Host] at [Date.time]
    ##   Server was [Server.isOkay]. And program tried to connect, but server connection is BAD.
    ##   specific report which pssh says is here : [Exception E]
    strLogMsg = str(Admin.ID) + " named " + str(Admin.NAME) + " tried to connect " + str(ID) + " by " + str(Role)+"@" + str(Host)  + " at " + str(datetime.datetime.now()) + "\n" + \
                "Program tried to connect, but server connection is BAD." + "\n" + \
                "specific report which pssh says is here : " + str(ExceptionE)
    Logger.SetOrigin('KNOWN_LOG')
    RK = Logger.MakeReport( 'SERVICE_STATUS_CHECK', Admin.PATH, Admin.NAME, strLogMsg)
    Logger.push_log( 'CONNECT', Host, RK, 'KNOWN_LOG', 'BAD', 'Connector.SendLog_ConnectionBad', 'CONNECTOR')

def SendLog_ConnectionGood (Logger, Admin, ID, Role, Host) :
    # Log structure :
    ##   [ADMIN.ID] tried to connect [ServerID] by [ServerRole]@[Host] at [Date.time]
    ##   Server was [Server.isOkay]. And program tried to connect, and server connection is GOOD
    strLogMsg = str(Admin.ID) + " named " + str(Admin.NAME) + " tried to connect " + str(ID) + " by " + str(Role)+"@" + str(Host)  + " at " + str(datetime.datetime.now()) + "\n" + \
                ".Program tried to connect, and it was successful.\n" 
    Logger.SetOrigin('KNOWN_LOG')
    RK = Logger.MakeReport( 'SERVICE_STATUS_CHECK', Admin.PATH, Admin.NAME, strLogMsg)
    Logger.push_log( 'CONNECT', Host, RK, 'KNOWN_LOG', 'BAD', 'Connector.SendLog_ConnectionBad', 'CONNECTOR')


def Shell_login(Shell, Hostname, Username, Password):
    Shell.login( Hostname, Username, Password)
    Shell.sendline('uname -a')
    Shell.prompt()
    SetExecuteLog(str(Hostname) + " Msg : " + Shell.before, None)

def Update_Success(cursor, conn, Id, isSuccess) :
    if isSuccess == True :
        cursor.execute("UPDATE servers SET \"LAST_LOGIN\"=\'"+str(datetime.datetime.now())+"\' WHERE \"ID\"="+str(Id))
        cursor.execute("UPDATE servers SET \"IS_ERROR\"=\'"+str("")+"\' WHERE \"ID\"="+str(Id))
        conn.commit()
        # Push Log in here
        # self.logger.push_log()

    else :
        cursor.execute("UPDATE servers SET \"LAST_LOGIN\"=\'"+str(datetime.datetime.now())+"\' WHERE \"ID\"="+str(Id))
        cursor.execute("UPDATE servers SET \"IS_ERROR\"=\'"+str("YES")+"\' WHERE \"ID\"="+str(Id))

        conn.commit()

    conn.commit()
    cursor.close()

def MakeListToMsg( listUsrInput ) :
    Msg = ""
    for i in listUsrInput :
        Msg += str(i) + '\n'
    return Msg

class Connector(object) :
    # def __init__(self) :
    #     self.SystemLoader = SystemLoader()


    def __init__(self, objects = None):
        # you must input 'SystemLoader in here'
        self.SystemLoader = objects
        # o yes
        self.db = self.SystemLoader.DB
        self.admin = self.SystemLoader.Admin
        self.ServerList = [[]]
        self.conn_string = ""
        self.logger = Logger(self)
        self.GoodServerList= []
        self.BadServerList = []

        self.Connecting()


    def Connecting(self) :
        # First, you have to connect DataBase in your local computer.
        # PostgreSQL will be the best choice. But if you want to use other version,
        # please check program version.
        self.Connect_DB()

        # Second, program will get server data from your local database.
        self.Connect_getServerDB()

        # Third, program check the servers okay to connectt
        self.Connect_Servers()

    def Connect_Servers(self) :
        # In this function, program check servers which owner has in local DB.
        # If there are errors in this logic, program will send log in DB.
        # You can check your error log in this program, and in other module.

        # i is each server list of serverlists
        for i in self.ServerList :
            # The rule of env.host = 'user@host:port'
            str_tmp = str(i[5])+"@"+str(i[3])+":"+str(i[1])

            try :
                # shell and host setting
                s = pxssh.pxssh()
                hostname = str(i[3])
                username = str(i[5])
                password = str(i[4])

                # Login to shell, if it has error, it may goes under 'except' lines.
                Shell_login(s, hostname, username, password)

                # If you want check what if server respond in pxssh, execute under lines.
                #######  s.sendline('whoami')
                #######  s.prompt()
                #######  print( "before:\n"+ s.before )

                s.logout()

                cursor = self.conn.cursor()
                Update_Success(cursor, self.conn, i[0], True)
                # Logger, Admin, ID, Role, Host, ExceptionE
                SendLog_ConnectionGood(self.logger, self.admin, i[0], username, hostname)

                # Added Aprl 12
                self.GoodServerList.append(i)

            except pxssh.ExceptionPxssh as e :
                cursor = self.conn.cursor()
                Update_Success(cursor, self.conn, i[0],  False)
                SendLog_ConnectionBad(self.logger, self.admin, i[0], username, hostname, e)
                SetExecuteLog( str(hostname) + " pxssh failed on login.", str(e))

                # Added Aprl 12
                self.BadServerList.append(i)


    def Connect_getServerDB(self) :
        SetExecuteLog('(getServerDB) ' + self.conn_string, None)
        self.conn = psycopg2.connect(self.conn_string)
        the_frame = pdsql.read_sql_table("servers", self.engine)

        self.ServerList = the_frame.values.tolist()
        ListMsg = MakeListToMsg(self.ServerList)
        SetExecuteLog('Server List : ' + ListMsg, None)

    # remain log
    def Connect_DB(self):
        # print('connect db')          # for log
        if self.db.SORTS == 'psql' :
            self.conn_string = "host="+self.db.HOST+" dbname="+self.db.NAME+" user="+self.db.USER+" password="+self.db.PW
            #print( self.conn_string )   # for log
            # dialect+driver://username:password@host:port/database
            self.engine = sqlalchemy.create_engine("postgresql+psycopg2://" + self.db.USER.replace("'","") + ":" + self.db.PW.replace("'","")+"@" + self.db.HOST.replace("'","") + ":" + self.db.PORT.replace("'","")+ "/" + self.db.NAME.replace("'",""))
            self.conn = psycopg2.connect(self.conn_string)
            self.db.IS_CONNECTED = True


        else :
            print ( "Sorry, " + self.db.SORTS + " isn't supported yet.....")

    def __str__(self) :
        return "CONNECTOR"

# 
#       Develop Log ( Aprl 15 )
#

# Aprl 15
#  <NAME>
#
#   Some lines are deleted and added some '\n' characters.
#   Becuase I changed IDE from atom to VS Code.<file_sep># @Author       Wonseok
# @Designer     Wonseok
# @Start at     June, 4
# @Last at      June, 4
# @Music        
# @Information

import os, sys
sys.path.insert( 0, os.getcwd() )
from ObjectInfo import DatabaseClass
from ObjectInfo import Server
from pexpect import pxssh
import psycopg2

class SCPCommand(object) :
    def __init__(self, _fromDir="", _connectId="", _iP="", _toDir="") :
        self.FromDir = _fromDir
        self.connectId = _connectId
        self.IP = _iP
        self.ToDir = _toDir

    def Set(self, _fromDir, _connectId, _ip, _toDir) :
        self.FromDir = _fromDir
        self.connectId = _connectId
        self.IP = _ip
        self._toDir = _toDir

    def MakeCommand(self) :
        if( self.FromDir == None or \
                self.connectId == None or \
                self.IP == None or \
                self.ToDir == None  ) :
            return False
        else :
            tmpStr = " scp -o StrictHostKeyChecking=no " + str(self.FromDir) + " " + self.connectId + "@" + \
                        str(self.IP) + ":" + str(self.ToDir)
            return tmpStr

    def __str__(self) :
        return self.MakeCommand()

class SCPManager(object) :
    def __init__(self) :
        self.Slaves = {}

    def PrintTargetCommands(self) : 
        for i in (self.Slaves.keys()) :
            print("{}\t\t{}".format(str(i.ID), str(self.Slaves[i].MakeCommand())))

    def TryAddSlave(self,SlaveServer) :
        if( SlaveServer.IS_ERROR == "YES" ) :
            return False
        _SCPCommand = SCPCommand("", "", "", "")
        self.Slaves[SlaveServer] = _SCPCommand
        return True

    def TargetSetById(self, id) :
        SlaveList = self.Slaves.keys()
        for Serv in SlaveList :
            print(type(Serv), Serv.getInfo())
            if( id == 'all') :
                _fromDir = str(raw_input("From Dir (+FileName) : "))
                _TryConID = Serv.CONNECTION_USERNAME
                _IP = Serv.CONNECTION_IPADDRESS
                _toDir = str(raw_input("Where to go? (+FileName) : "))
                Command = SCPCommand(_fromDir, _TryConID, _IP, _toDir)
                self.Slaves[Serv] = Command

            if( Serv.ID == id ) :
                _fromDir = str(raw_input("From Dir (+FileName) : "))
                _TryConID = Serv.CONNECTION_USERNAME
                _IP = Serv.CONNECTION_IPADDRESS
                _toDir = str(raw_input("Where to go? (+FileName) : "))
                Command = SCPCommand(_fromDir, _TryConID, _IP, _toDir)
                self.Slaves[Serv] = Command

    def SetCommandForAllTargets(self, Comm) :
        for Serv in self.Slaves :
            self.Slaves[Serv] = Comm

    def SendToAllTargets(self) :
        for Serv in self.Slaves :
            Comm = self.Slaves[Serv].MakeCommand()
            if( Comm == False ) : continue
            print(Serv.CONNECTION_PASSWORD)
            os.system( "sshpass -p" + Serv.CONNECTION_PASSWORD  + self.Slaves[Serv].MakeCommand() )
            print('done!')
            raw_input()

    def DeleteServerInTargets(self, ServerKey) :
        self.Slaves.pop(ServerKey)<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-

# @Author       Wonseok
# @Designer     Wonseok
# @Start at     Aprl. 17
# @Last at      Aprl. 17
# @Music        ANTI - ZICO( feat.. )
# @Information  This class is parent class for backup system. This will need some class.
# @details
#           First, This class need server class. For example, if you want to back-up your
#        postgreSQL data to server, you have to regist master server and slave server.
#        (master = server which is backed up. slave = server which back up.)
#         -> slave will take data from master to save in itself.
#           (If you want to make database backup system) Second, you need DataBase.
#         If you want to make copy-database, just copy it and put it in your database.

import os, sys
sys.path.insert(0, os.getcwd())

from ObjectInfo import Server
from ObjectInfo import AdministratorClass
from ObjectInfo import DatabaseClass
from System import Logger
import time, datetime
class BackupEngine(object) :

    def __init__(self, Master, Slave, Admin) :
        self.IS_INITIALIZE = False

        if( (str(Master) is not "SERVER") or
            (str(Slave) is not "SERVER") or
            (str(Admin) is not "ADMINISTRATORCLASS")) :
            print(str(Master), str(Slave), str(Admin))
            print('Backup initialize fail!')
            return

        # Engine will back up from master to slave.
        self.Master = Master
        self.Slave = Slave
        self.Admin = Admin

        # Server connection test.
        if( self.ConnectionTest_toServer() ) :
            print('Test accepted!')
        else :
            print('BackupEngine tried to connect master & server. But it failed.')

    # Connection test needs to be accepted. If not, Backup Engine failed to initialize.
    def ConnectionTest_toServer(self) :
        IS_OKAY_MASTER, Msg_MASTER = self.Master.isTryConnect()
        IS_OKAY_SLAVE, Msg_SLAVE = self.Slave.isTryConnect()

        if( (IS_OKAY_MASTER and IS_OKAY_SLAVE ) == False ) :
            self.SendLog_ConnectionWrong(IS_OKAY_MASTER, IS_OKAY_SLAVE, Msg_MASTER, Msg_SLAVE)
            self.Master = None
            self.Slave = None
            return False

        return True

    def SendLog_ConnectionWrong(self, ConnMaster, ConnSlave, Msg_MASTER, Msg_SLAVE ) :
        # LogStructure :
        ##  [Admin.ID] tried to connect these at [Date.time] : 
        ##  Master : [Master.ID], [Master.Role]@[MAST.Host] / Slave : [Slave.ID], [Slave.Role]@[Slav.Host]
        ##  But server Connection is BAD. 
        ##  Master connection status : [ConnMaster], Slave connection status : [ConnSlave]
        ##  Here is the Msg from master : [Msg_Master]
        ##  Here is the Msg from slave  : [Msg_Slave]

        StrLogMsg = str(self.Admin.ID) + " tried to connect these at " + str(datetime.datetime.now()) + " : \n" + \
                    "Master : " + str(self.Master.ID) + ", " + str(self.Master.ROLE) + "@" + str(self.Master.HOST) + \
                     " / Slve : " + str(self.Slave.ID) + ", " + str(self.Slave.ROLE) + "@" + str(self.Slave.HOST) + "\n" + \
                     "But server Connection is BAD." + \
                     "Master connection status : " + str(ConnMaster) + ", Slave connection status : " + str(ConnSlave) + "\n" + \
                     "Here is the Msg from master : " + str(Msg_MASTER) + "\n" + \
                     "Here is the Msg from slave  : " + str(Msg_SLAVE) + "\n"
        BackupLogger = Logger.Logger(self)
        BackupLogger.SetOrigin('KNOWN_LOG')
        RK = BackupLogger.MakeReport('SERVICE_STATUS_CHECK', self.Admin.PATH, self.Admin.NAME, StrLogMsg)

        if( ConnMaster ) :
            ConnMaster = "BAD"
        else :
            ConnMaster = "GOOD"
        if( ConnSlave ) :
            ConnSlave = "BAD"
        else :
            ConnSlave = "GOOD"

        # Push master log and slave log.
        BackupLogger.push_log('CONNECT', self.Master.ID, RK, 'KNOWN_LOG', ConnMaster, 'BackupEngine.SendLog_ConnectionBad', 'BACKUPENGINE')
        BackupLogger.push_log('CONNECT', self.Slave.ID, RK, 'KNOWN_LOG', ConnMaster, 'BackupEngine.SendLog_ConnectionBad', 'BACKUPENGINE')
        


#
#       Test if BackupEngine's status is good.
#

if __name__ == "__main__" :
    S = Server.Server(1, 22, 'ssh', '172.16.31.10', '3@mHze=5K{1wj){}', 'root', 'Wonseok.J', 970403, 'ubuntu', 'wonseokbuntu', None, '2018-03-02', None, None)
    S.db = DatabaseClass.DB("psql", "'localhost'", "'5432'", "'testdb'", "'12345'", "'test'")
    S.db.Connect_DB()
    S.DB=S.db
    S.Admin = AdministratorClass.Administrator('Wonseok', '/root/바탕화면/ServerPlayer/Report/', 'root', 'Admin', 'root')
    S.local_admin = S.GetServerOwner()

    BE = BackupEngine(S, S, S.Admin)<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-

import os, sys
sys.path.insert(0, os.getcwd() )
from ObjectInfo import DatabaseClass
from ObjectInfo import AdministratorClass
from ObjectInfo import Server
from CheckerEngine import CheckerEngine
import time, datetime
from System import Logger

from pexpect import pxssh
import getpass

# @Author       Wonseok
# @Designer     Wonseok
# @Start at     Aprl. 18
# @Last at      Aprl. 20
# @Music        Sing a song at TV program - Shin Yong Jae.
# @Information  This class is made for checking the database system. This system is a child class of Checker Engine.
#           You must add some functions and values in this functions. that's all.

class ServerChecker( CheckerEngine) :

    '''
    @ Written by wonseok.
    @ Date at 2018.04.20

     You don't need to define ConditionChecker function or sending log function 
    which sends 'server connection bad' or 'database connection bad' status.
     Server checker just needs to define some functions which can control servers,
    check attacks from bad hackers.
     And also, ServerChecker needs to make a report which can be seen easily.

     Day 18 :
        Define class and functions < Checker engine which are parent class of this class >
     Day 19 :
        Define this class and some functions which are initailizer, condition checker,
        shell commands, SSH commanding functions, some functions for security check.
     Day 20 :
        I will make some functions about making report, and for sending this mail,
        I will make a mail class named, 'mailchecker'.
    '''

    # Nothing special.
    # But you have to notice that this class uses parent class's initializer.
    def __init__(self, LocalServer=None, LocalDatabase=None, LocalAdmin=None ) :
        CheckerEngine.__init__(self, LocalServer, LocalDatabase, LocalAdmin)
        self.Logger = Logger.Logger(self)
        self.EngineName = "SERVERCHECKER"

    # This program will check condition of local Database and etc.
    # If checking status is bad, parent class will remains log.
    def ServerChecker_ConditionCheck(self) :
        isOkay, msg = self.CheckerConditionCheck()
        if( isOkay ) : 
            return True, "Good"
        else :
            return False, msg

    # Pexpect defines wonderful functions for using shell script in remote server.
    # It's really good to use, and don't need hard codes.
    def MakeShell(self) :
        # For using shell script at remote server, you have to define shell.
        self.Shell = pxssh.pxssh()
        
    def LoginShell(self) :
        # After execute makeshell function, you have to login in server.
        host = self.LocalServer.CONNECTION_IPADDRESS    # local server is
        user = self.LocalServer.CONNECTION_USERNAME     # master server.
        pw = self.LocalServer.CONNECTION_PASSWORD
        self.Shell.login(host, user, pw)                # This is the most important line

    # You just execute this function and putting msg in this function's parameter,
    # you can send message to remote server.
    def ThrowMsg_Shell(self, msg) :
        self.Shell.sendline(msg)    # run a command
        self.Shell.prompt()         # match the prompt  - pexpect github.
    
    def LogoutShell(self) :
        self.Shell.logout()

    '''
     From this line, program will check some security checks at remote server.
    You don't need to execute these commands in every servers.
    This commands will execute for you automatically.
    What you just need to check is, execute this function, check the report. That's all!
    '''
    def LastCommand(self) :
        # Last command tells you who visited and succeed to login in your server.
        # It's a very basic command of checking security.

        self.MakeShell()
        self.LoginShell()
        self.ThrowMsg_Shell("last")
        data = self.Shell.before
        self.LogoutShell()

        return data


    def SSHAttemptsCommand_Debian(self, num) :
        # This commands will tell you who wanted to log in your remote server.
        # This function is for debian( ubuntu is based at debian ) OS.
        self.MakeShell()
        self.LoginShell()
        self.ThrowMsg_Shell("tail -n "+str(num)+" /var/log/auth.log | grep sshd")
        data = self.Shell.before
        self.LogoutShell()

        return data

    def SSHAttemptsCommand_CentRedHat(self, num) :
        # CentOS and RedHat have to execute this function.
        self.MakeShell()
        self.LoginShell()
        self.ThrowMsg_Shell("tail -n "+str(num)+" /var/log/secure | grep 'sshd'")
        data = self.Shell.before
        self.LogoutShell()

        return data

    def BashHistory(self, num) :
        # This function tells you what hackers did in your server.
        # But you have to know that, history includes commands that you did.
        self.MakeShell()
        self.LoginShell()
        self.ThrowMsg_Shell("tail -n "+str(num)+" ~/.bash_history")
        data = str(self.Shell.before)
        print(self.Shell.before)
        self.LogoutShell()

        return data

    '''
     From this line, program will make the result from command to report.
    You can check the reports by using below functions.
    '''

    #@param     content is the msg from server. You have to make report this value.
    #           caller is the command which you used in server.
    #              - if you use 'last' command at server, caller will be 'last'
    def MakeReport(self, content, caller) :
        # LogStructure :
        #
        # File name : (ServerID).(ServerName).(Command).(Date) - new file
        #          +  (ServerID).(ServerName).(Command) - based file.

        FileName_new = str(self.LocalServer.ID)+"."+str(self.LocalServer.SERVER_NAME)+"."+str(caller)+"."+ (str(datetime.datetime.now()).replace(" ",""))
        FileName_base = str(self.LocalServer.ID)+"."+str(self.LocalServer.SERVER_NAME)+"."+str(caller)

        newFile = open(self.LocalAdmin.PATH + FileName_new + ".txt", "w")
        baseFile = open(self.LocalAdmin.PATH + FileName_base + ".txt", "a")
        
        newFile.write(content+'\n\n')
        baseFile.write(content+'\n\n')

        newFile.close()
        baseFile.close()


    def __str__(self) :
        return "SERVERCHECKER"

if __name__ == "__main__" :
    S = Server.Server(1, 22, 'ssh', '192.168.127.12', '3@mHze=5K{1wj){}', 'root', 'Wonseok.J', 970403, 'ubuntu', 'wonseokbuntu', None, '2018-03-02', None, None)
    S.DB = DatabaseClass.DB("psql", "'localhost'", "'5432'", "'testdb'", "'1234'", "'test'")
    S.DB.Connect_DB()
    S.db = S.DB
    S.Admin = AdministratorClass.Administrator('Wonseok', '/root/바탕화면/ServerPlayer/Report/', 'root', 'Admin', 'root')
    
    ServerChecker = ServerChecker(S, S.DB, S.Admin)
    #S.ThrowCommand('last')
    print( ServerChecker.ServerChecker_ConditionCheck() )
    #ServerChecker.LastCommand()
    #ServerChecker.SSHAttemptsCommand_Debian()
    #ServerChecker.dont()
    data = ServerChecker.BashHistory(500)
    ServerChecker.MakeReport( data , 'BashHistory')
    data = ServerChecker.LastCommand()
    ServerChecker.MakeReport( data, 'LastCommand' )<file_sep>
# This class will have information between this program with program log & configure DB
# After load onnection, connector has to have connection with servers.
import psycopg2
from AdministratorClass import Administrator
import sqlalchemy
class DB(object) :
    def __init__(self, Sorts=None, Host=None, Port=None, Name=None, Pw=None, User=None, DB_KEY=None, SERV_KEY=None):
        print('Log : Database initializer is loaded! ')
        # If you use sort 'PostgreSQL', input 'psql', 'MS-SQL', input 'mssql',
        # 'MySQL', input 'mysql', 'ORACLE', input 'orac', 'SQLITE', 'sqlite'
        self.SORTS = Sorts                     # Database management name
        self.HOST = Host                      # Database host ip xxx.xxx.xxx.xxx
        self.PORT = Port                      # Database port (1000 ~ 9999)
        self.NAME = Name                      # Database Name
        self.PW   = Pw                      # Database password
        self.USER = User                      # Database user
        self.DB_KEY = DB_KEY

        self.IS_CONNECTED = False
        self.OBJECT = None
        self.SERVER_KEY = SERV_KEY

    def AdminToDatabaseConnect(self, Admin) :
        # This class using admin's key to get Database information, and connect it.
        if( self.IS_CONNECTED == False ) :
            print("You should try connect Database first!")
            return
        else :
            cur = self.conn.cursor()
            cur.execute("SELECT * FROM db_profile WHERE owner_id = '" + str(Admin.ID) + "'")
            owner_info = cur.fetchall()
            owner_info = owner_info[0]
            DB_KEY = owner_info[0]
            HOST = owner_info[1]
            PW = owner_info[2]
            PORT = owner_info[4]
            SORTS = owner_info[5]

            cur.execute("SELECT * FROM database WHERE db_key = '" + str(DB_KEY) + "'")
            db_info = cur.fetchall()
            db_info = db_info[0]
            USER = db_info[5]
            NAME = db_info[4]
            
            TmpDB = DB(SORTS, HOST, PORT, NAME, PW, USER, DB_KEY, Admin.ID)
            TmpDB.Connect_DB()
            TmpDB.SERVER_KEY = Admin.ID


    def getInfo(self) :
        return ( str(self.SORTS) + " " + str(self.HOST) + " " + str(self.PORT) + " " + str(self.NAME) + \
        str(self.PW) + " " + str(self.USER) + " " + str(self.DB_KEY) + " " + str(self.IS_CONNECTED) + " " + \
        str(self.OBJECT) + " " + str(self.SERVER_KEY) + "\n" )

    def printInfo(self) :
        # STRUCTURE :
        # NAME : \nHOST : \n ...
        print('Database Information ~')
        print('Name  : ' + self.NAME)
        print('SORTS : ' + self.SORTS)
        print('PORT  : ' + self.PORT)
        print('HOST  : ' + self.HOST)
        print('USER  : ' + self.USER)
        print('PW    : ' + "Check the file (for security)")
        print('')


    # This function is from Connector.py
    # This function connect DB with elements which are initialized
    # remain log
    def Connect_DB(self) :
        print('connect db')
        if self.SORTS == 'psql' :
            try :
                self.conn_string = "host="+self.HOST+" dbname="+self.NAME+" user="+self.USER+" password="+self.PW
                print( self.conn_string )
                self.conn = psycopg2.connect(self.conn_string)
            except psycopg2.Error as e :
                # remain log
                print(e)
                self.IS_CONNECTED = False
            self.IS_CONNECTED = True
        
        else :
            print("Sorry, " + self.SORTS + " isn't supported yet.")
            return False

    def isTryConnect(self) :
        print('connect db')
        if self.SORTS == 'psql' :
            try :
                self.conn_string = "host="+self.HOST+" dbname="+self.NAME+" user="+self.USER+" password="+self.PW
                print( self.conn_string )
                self.conn = psycopg2.connect(self.conn_string)
            except psycopg2.Error as e :
                # remain log
                return False, e
            except Exception as e :
                return False, e
            return True, "GOOD"
        
        else :
            return False, "That DB is not supported."

    def __str__(self) :
        return "DATABASECLASS"
<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-

# @Author       Wonseok
# @Designer     Wonseok
# @Start at     Aprl. 5
# @Last at      Aprl. 15
# @Music        Castle of magic by MC Sniper
# @Information  This class is only for server each of being managed.
#               Unfortunately, now, if your DB is not 'postgreSQl', you can't control it.


from pexpect import pxssh       # Added at Aprl 15
import psycopg2
from DatabaseClass import DB
from AdministratorClass import Administrator
import time, datetime

import os, sys
sys.path.insert(0, os.getcwd())
from System import Logger
class Server (object) :

    def __init__(self, i=None, p=None, s=None, ip=None, pa=None, u=None, n=None, id=None, os=None, Na=None, IE=None, LST_DATE=None, db_key=None, obj_key=None) :
        self.ID = i                     # Primary Key for Serv
        self.CONNECTION_PORT = p        # Connection port ( ssh = 22 )
        self.CONNECTION_SORT = s        # ssh or ftp ...
        self.CONNECTION_IPADDRESS = ip  # 192.168.10.1 ..
        self.CONNECTION_PASSWORD = pa   # Wonseok...
        self.CONNECTION_USERNAME = u    # root
        self.OWNER_NAME = n             # Wonseok
        self.OWNER_ID = id              # key of wonseok. Primary key of Administrator will be a good point for understanding.
        self.SERVER_OS = os             # Ubuntu 16.04 ..
        self.SERVER_NAME = Na           # WonseokServer..
        self.IS_ERROR = IE              # True? False? or something
        self.CONNECTION_LASTDATE = LST_DATE
        self.DB_KEY = db_key
        self.OBJECT_KEY = obj_key

        self.DB= None
        self.Admin= None

        # Local is server's owner.
        self.local_db = None
        self.local_admin = None

    # Try connecting if server is okay
    # okay -> self.iserror= true, No -> self.iserror= false
    def isTryConnect(self) :
        try :
            shell = pxssh.pxssh()
            shell.login( self.CONNECTION_IPADDRESS, self.CONNECTION_USERNAME, self.CONNECTION_PASSWORD)
            shell.sendline('ls -al')
            shell.prompt()
            print( "before\n" + shell.before)

            shell.logout()
        
        except pxssh.ExceptionPxssh as e :
            self.IS_ERROR = "YES"   # Error occur
            return False, e

        self.IS_ERROR = None        # No error
        return True, 'GOOD'


    # Using this function makes you easier to throw command.
    def ThrowCommand(self, comd) :
        try : 
            shell = pxssh.pxssh()
            shell.login( self.CONNECTION_IPADDRESS, self.CONNECTION_USERNAME, self.CONNECTION_PASSWORD)
            shell.sendline(comd)
            shell.prompt()
            print("command : " + shell.before)

            shell.logout()

        except pxssh.ExceptionPxssh as e :
            ServerLogger = Logger.Logger(Server)                # Because, Logger is in other directory.
            self.SendLog_ThrowMsgError(ServerLogger, comd, e)
            return False, e
        
        return True, 'GOOD'


    # Using this function, you can get server's owner easy
    def GetServerOwner(self) :
        # @Return   True -> get admin information successfully, False -> No
        # @Befroe   You have to make sure that this server class has 'local_db'
        # Algo : Connect DB -> Using Foreinn key -> Get Admin's information -> put it in admin class
        if self.DB.IS_CONNECTED == False :
            print("This server doesn't have local database!\n \
                   You hae to execute db.Connect_DB first!")
            return False, "Not connected local_db"
        else :
            try :
                cur = self.DB.conn.cursor()
                cur.execute("SELECT * FROM administrator WHERE admin_key=" + str(self.OWNER_ID) )
                owner_info = cur.fetchall()     # administrator call succeed
            
            except psycopg2.Error as e :
                # send log
                print(e)
                return False, e
            
            except Exception as e :
                print('error:', e)
                ServerLogger = Logger.Logger(self)
                ServerLogger.PushLog_UnknownError(self.Admin, 'Server.GetServerOwner', e)
                return False, e
            
            # Make admin class
            if len(owner_info) != 1 :
                # Because of primary key, it won't happen.
                print('Owner is wrong! The system must have just one owner!')
            owner_info = owner_info[0]
            tmpAdmin = Administrator(owner_info[0], owner_info[1], owner_info[2], owner_info[3], owner_info[4])
            tmpAdmin.printInfo()

            # Initialize
            self.local_admin = tmpAdmin

            # Return success
            return True, "Success"

    #       Created at Aprl 17. with Say you love me please - red cheek puberty
    #       Below functions are loger.
    #       Written by <NAME>

    # This function is copied from Scheduler.SendLog_ThrowMsgError
    def SendLog_ThrowMsgError (self, Logger, command, ExceptionMsg) :
        # Log structure :
        ##   [ADMIN.ID] tried to throw [command] to [ServerID] by [ServerRole]@[Host] at [Date.time]
        ##   Server was [Server.isOkay]. And program tried to connect, but server connection is BAD.
        ##   specific report which pssh says is here : [Exception E]
        strLogMsg = str(self.Admin.ID) + " tried to throw " + str(command) + " to " + str(self.ID) + " by " + str(self.CONNECTION_USERNAME)+"@" + str(self.CONNECTION_IPADDRESS)  + " at " + str(datetime.datetime.now()) + "\n" + \
                    "Server was " + self.IS_ERROR + ". And program tried to connect, but server connection is BAD." + "\n" + \
                    "specific report which pssh says is here : " + str(ExceptionMsg)
        Logger.SetOrigin('KNOWN_LOG')
        RK = Logger.MakeReport( 'SERVICE_STATUS_CHECK', self.Admin.PATH, self.Admin.NAME, strLogMsg)
        Logger.push_log('REQ_COMMAND', self.ID, RK, 'KNOWN_LOG', 'BAD', 'Server.SendLog_ThrowMsgError', 'SERVER')

    def SendLog_ConnectionBad (self, Logger, ExceptionMsg) :
        # Log structure :
        ##   [ADMIN.ID] tried to connect [ServerID] by [ServerRole]@[Host] at [Date.time]
        ##   Server was [Server.isOkay]. And program tried to connect, but server connection is BAD.
        ##   specific report which pssh says is here : [Exception E]
        strLogMsg = str(self.Admin.ID) + " tried to connect " + str(self.ID) + " by " + str(self.CONNECTION_USERNAME)+"@" + str(self.CONNECTION_IPADDRESS)  + " at " + str(datetime.datetime.now()) + "\n" + \
                    "Server was " + self.IS_ERROR + ". And program tried to connect, but server connection is BAD." + "\n" + \
                    "specific report which pssh says is here : " + str(ExceptionMsg)
        Logger.SetOrigin('KNOWN_LOG')
        RK = Logger.MakeReport( 'SERVICE_STATUS_CHECK', self.Admin.PATH, self.Admin.NAME, strLogMsg)
        Logger.push_log( 'CONNECT', self.ID, RK, 'KNOWN_LOG', 'BAD', 'Server.SendLog_ConnectionBad', 'SERVER')


    def __str__ (self) :
        # upper only
        return "SERVER"

    def getInfo(self) :
        # CAUTION : DO NOT RETURN OTHER CLASS.
        # IF YOU DO THAT, THIS FUNCTION WILL MAKE FULL STACK RECURSIVE FUNCTION, AND MAKE 
        # STACK OVERFLOW ERROR. 
        strMsg = "ID = " + str(self.ID) + \
                "\nConnection_port = " + str(self.CONNECTION_PORT) + \
                "\nCONNECTION_SORT = " + str(self.CONNECTION_SORT) + \
                "\nCONNECTION_IPADDRESS = " + str(self.CONNECTION_IPADDRESS) + \
                "\nCONNECTION_PASSWORD = " + str(self.CONNECTION_PASSWORD) + \
                "\nCONNECTION_USERNAME = " + str(self.CONNECTION_USERNAME) + \
                "\nOWNER_NAME = " + str(self.OWNER_NAME) + \
                "\nOWNER_ID = " + str(self.OWNER_ID) + \
                "\nSERVER_OS = " + str(self.SERVER_OS) + \
                "\nSERVER_NAME = " + str(self.SERVER_NAME) + \
                "\nIS_ERROR = " + str(self.IS_ERROR) + \
                "\nCONNECTION_LASTDATE = " + str(self.CONNECTION_LASTDATE) + \
                "\nDB_KEY = " + str(self.DB_KEY) + \
                "\nOBJECT_KEY = " + str(self.OBJECT_KEY)
        return strMsg

#
#       Test if server can have Administrator and Database
#

if __name__ == "__main__" :
    S = Server(1, 22, 'ssh', '172.16.58.3', 'makeitpopwebuzzz!1', 'root', 'Wonseok.J', 1230, 'ubuntu', 'wonseokbuntu', None, '2018-03-02', None, None)
    S.DB = DB("psql", "'localhost'", "'5432'", "'testdb'", "'1234'", "'test'")
    S.DB.Connect_DB()
    S.Admin = Administrator('Wonseok', '/root/바탕화면/ServerPlayer/Report/', 'root', 'Admin', 'root')
    S.GetServerOwner()
    S.local_db = S.DB.AdminToDatabaseConnect( S.local_admin )


#
#   Develop Log ( Aprl 15 )
#

# Aprl 15
#   <NAME>
#
#  I think server has to have connector's function named 'Connect_Servers)
#  So I copied that function to Server.py
#
# Aprl 17
#   Designer Wonseok.J
#
#  I added some functions named GetServerOwner in this class. Just using this class, 
# You can get server's owner. And once you call this function, automatically server makes admin
# class. It will initialize that with server.
#  <file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-

# @Author       Wonseok
# @Designer     Wonseok
# @Start at     Aprl. 13
# @Last at      Aprl. 15
# @Music        Angel - Drunken Tiger with Yoon - mire, bizzy
# @Information  This class supports you that you can do cron service easy.
#               If you want to execute program at regular time, you can regist it easily.
#               And also, cron service remains logs in log DB.
import os, sys
sys.path.insert(0, os.getcwd() )
from Logger import Logger
from ObjectInfo import Server
import time, datetime

# Scheduler class make schedule using crontab command for user in easy way.
# It will check if the server is okay to connect, and if that is okay then it will send command to server.
# You don't worry to make command and send it to server.
class Scheduler(object) :

    def __init__(self, object) :
        # This argument is important. Korean usually say this produce,
        # Year -> Month -> Day -> Hour -> Minute -> Second
        # But Crontab command's produce is
        # Minute -> Hour -> Day -> Month -> DATE
        # So this dict will change American's dict to Korean's

        if( str(object) != "SERVER" ) : # program key is SERVER
            # remain the log if you have more time.
            print( str(object) + "'can't register any cron service! ")
        else :
            self.Server = object

        self.KeyOfList = {
            0 : 3,
            1 : 4,
            2 : 2,
            3 : 1,
            4 : 0
        }
        self.db = object.db
        self.InputList = [None, None, None, None, None]     # This list is raw list
        self.OutputList = [None, None, None, None, None]    # This list is changed for crontab command
        self.CommandAtLst = ""                          # This command is final string when you write in crontab command


    # This function makes command for sending server.
    # This command will be exectued in user's server.
    def MakeCommand(self) :
        strTmp = ""
        for i in range(0, 5) :
            strTmp += str(self.OutputList[i]) + " "
        strTmp += self.CommandAtLst

        return ('cat <(crontab -l) <(echo "' + strTmp + '") | crontab -')

    # MIN HOUR DAY MONTH DATE
    # producedure : Month -> Date -> Day -> Hour -> Min
    def PrintAndInput(self) :
        for i in range(0, 5) :
            self.PrintValues(i)
            self.InputValue(i)

        self.PrintValues(5)

    def InputCommand(self) :
        print('Please input command you want to execute : ')
        self.CommandAtLst = raw_input()



    # This function is just for input some variables.
    # You have to check algorithm and __init__ comment before you see this lines.
    def InputValue(self, num) :
        if( num == 0 ) :
            # Month
            print('What month are you going to do it? : ')
        elif( num == 1 ) :
            # Date
            print('What date are you going to do it? \n')
            print('SUN      MON      TUE     WED     THU     FRI     SAT \n')
            print('0        1        2       3       4       5       6\n')
            print('-> ')
        elif( num == 2 ) :
            # Day
            print('What day are you going to do it? : ')
        elif( num == 3 ) :
            # Hour
            print('What hour are you going to do it? : ')
        elif( num == 4 ) :
            # Minute
            print('What minute are you going to do it? : ')


        # Korean usually say : month-> date -> day -> hour-> Minute .
        # This function change to crontab producedure.
        self.InputList[num] =  raw_input()
        self.OutputList[(self.KeyOfList[num])] = self.InputList[num]


    # This function is just for print values to help user to make command.
    # After this function, you have to execute input function to input some values.
    def PrintValues(self, num) :  # recursive function
        strTable = "MIN     HOUR    Day     MONTH   DATE"
        strTmp = ""
        for i in range(0, 5) :
            if( self.OutputList[i] == None ) :
                strTmp += '.\t'
            else :
                strTmp += str(self.OutputList[i])+'\t'

        os.system('clear')
        print('Now (Every = *) : ' + '\n' + strTable)
        print(strTmp + '\n\n')


    # This function is main function in this class
    # Whenever user wants to make schedule, this function will make special schedule.
    def MakeSchedule(self) :
        while( True ) :
            self.PrintAndInput()
            self.InputCommand()
            strTmp = self.MakeCommand()
            flag = raw_input(strTmp + '\nCommand will be excuted! is it right? (y/n) ')
            if( flag == 'y' or flag == 'Y' ) :
                print('Sending...')
                break
            else  :
                print('Do you want to exit? (y/n) ')
                falg = raw_input()
                if( flag == 'y' or flag == 'Y') :
                    return

                print('Retry it!')
                self.InputList = [None, None, None, None, None]
                self.OutputList = [None, None, None, None, None]
                flag = raw_input()
        
        # from break command
        return strTmp


    # This function is for send command server. 
    # Main alogorithm is, check the server if service is online, send the command, remain the log.
    # Lst updated at Aprl 15 with I'm not laughing ( Leesang )
    def MakeAndSendCommand(self):
        # Is server okay to connect ?
        # Make Logger for if you have some issue to connect server, make report and send log to DB.
        SchedulerLogger = Logger(self)              # This is for before line.
        
        if( self.Server.IS_ERROR == 'YES' ) :
            # The server has some error. Try connect?
            print('The report says server is not online. Do you want to test the server? (y/n)')
            isOkay = raw_input()
            if( (isOkay is not 'y') and (isOkay is not 'Y')) : 
                # Server status is BAD < report >
                # No I don't want to connect.
                print('return to before menu!')
                flag = raw_input()
                return

            isOkayServer, ServerMsg = self.Server.isTryConnect()
            if( isOkayServer == False ) :
                # Server status is BAD < report >
                # Yes I wanted to connect. But server is still BAD.
                print('Sorry, the server connection is so bad.')
                self.SendLog_ConnectionBad(SchedulerLogger, ServerMsg)
                # Send log < Not connect >
                return
                
        print('Server connection is successful!')
        print('Press any key to continue!')
        flag = raw_input()  # just UI

        # Server is good or was not good but now good.
        # You have to connect the server and send message to DB ! below here
        Usr_Comd = self.MakeSchedule()                          # Get Command.
        isSuccess, ExMsg = self.Server.ThrowCommand(Usr_Comd)     # This function returns if success, and message from try ~ catch
        if( isSuccess == True ) :
            self.Server.ThrowCommand('crontab -l')
            print('I sent message successfully!')
        else :
            print("I coudln't send message to server!")
            self.SendLog_ThrowMsgError(SchedulerLogger, Usr_Comd, ExMsg)


    #       Created at Aprl 17. with Parchelbel: Canon In D Major) In Jazz
    #       Below functions are for logger.
    #       Written by <NAME>
    def SendLog_ThrowMsgError (self, Logger, command, ExceptionMsg) :
        # Log structure :
        ##   [ADMIN.ID] tried to throw [command] to [ServerID] by [ServerRole]@[Host] at [Date.time]
        ##   Server was [Server.isOkay]. And program tried to connect, but server connection is BAD.
        ##   specific report which pssh says is here : [Exception E]
        strLogMsg = str(self.Server.admin.ID) + " tried to throw " + str(command) + " to " + str(self.Server.ID) + " by " + str(self.Server.CONNECTION_USERNAME)+"@" + str(self.Server.CONNECTION_IPADDRESS)  + " at " + str(datetime.datetime.now()) + "\n" + \
                    "Server was " + self.Server.IS_ERROR + ". And program tried to connect, but server connection is BAD." + "\n" + \
                    "specific report which pssh says is here : " + str(ExceptionMsg)
        Logger.SetOrigin('KNOWN_LOG')
        RK = Logger.MakeReport( 'SERVICE_STATUS_CHECK', self.Server.admin.PATH, self.Server.admin.NAME, strLogMsg)
        Logger.push_log('REQ_COMMAND', self.Server.ID, RK, 'KNOWN_LOG', 'BAD', 'Scheduler.SendLog_ThrowMsgError', 'SCHEDULER')


    def SendLog_ConnectionBad (self, Logger, ExceptionMsg) :
        # Log structure :
        ##   [ADMIN.ID] tried to connect [ServerID] by [ServerRole]@[Host] at [Date.time]
        ##   Server was [Server.isOkay]. And program tried to connect, but server connection is BAD.
        ##   specific report which pssh says is here : [Exception E]
        strLogMsg = str(self.Server.admin.ID) + " tried to connect " + str(self.Server.ID) + " by " + str(self.Server.CONNECTION_USERNAME)+"@" + str(self.Server.CONNECTION_IPADDRESS)  + " at " + str(datetime.datetime.now()) + "\n" + \
                    "Server was " + self.Server.IS_ERROR + ". And program tried to connect, but server connection is BAD." + "\n" + \
                    "specific report which pssh says is here : " + str(ExceptionMsg)
        Logger.SetOrigin('KNOWN_LOG')
        RK = Logger.MakeReport( 'SERVICE_STATUS_CHECK', self.Server.admin.PATH, 'Wonseok', strLogMsg)
        Logger.push_log( 'CONNECT', self.Server.ID, RK, 'KNOWN_LOG', 'BAD', 'Scheduler.SendLog_ConnectionBad', 'SCHEDULER')


    def __str__(self) :
        return "SCHEDULER" 



        


# note :
# lst update aprl 14 with 'Stronger than you - Sans and ... trio'
# Test : <None>
if (__name__ == "__main__") :
    '''
    # You need server
    testServer = Server.Server()

    # You have to make scheduler
    Scheduler = Scheduler(testServer)

    # You have to execute function named 'MakeSchedule'
    Scheduler.MakeSchedule()

    # Test completed. it was successful. ( ~ Aprl 15 )
    '''
    testServer = Server.Server(1, 22, 'ssh', '172.16.17.32', '3@mHze=5K{1wj){}', 'root', 'Wonseok', 970403, 'ubuntu', 'WonseokTestbuntu',None,'2018-01010101')
    Scheduler = Scheduler(testServer)

    Scheduler.MakeAndSendCommand()
<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-

# @Author       Wonseok
# @Designer     Wonseok
# @Start at     Aprl. 4
# @Last at      Aprl. 20
# @Music        Parallax, U-Won-Jae
# @Information  Engine class is place in System UI.
#               In UI, user has to set the some settings.
#               If not, user may have some issues to execute program.


from SystemLoader import SystemLoader
from Kernel import Kernel
from Logger import Logger
import os, sys
sys.path.insert(0, os.getcwd())
from ObjectInfo import AdministratorClass
from Scheduler import Scheduler
from UserInterface import UIManager
import fabric
import datetime
from anytree import Node, RenderTree

def Exit(code) :
    # code 100 : OS Error. Your os is not supported in this system.
    print("WARNNING : You can't execute program. \n Error code : " + str(code))
    SetExecuteLog('Engine initialize is failed', code)
    exit()

def clearScreen(sort) :
    if( sort == 1 ) :
        os.system('clear')
    elif( sort == 2 ) :
        os.system('cls')
    else :
        Exit(100)

BeforeTime = datetime.datetime.now()
def SetExecuteLog(code, ErrorCode) :
    global BeforeTime
    now = datetime.datetime.now()
    LogFile = open(os.getcwd() + '/UserConfig/EngineLog.txt', "a")
    LogFile.write('Code : ' + str(code) + '\n')
    if( ErrorCode ) :
        LogFile.write('ErCode : ' + str(ErrorCode) + '\n')
    LogFile.write('Written time : ' + str(now) + ' [' + str(now - BeforeTime) + ']'+ '\n')
    BeforeTime = now

def ParseSortCont_FromString(List_forParse):
    # It only returns two data which are Sort and Content of string in listself.
    # EX) NAME:Wonseok
    # Sort = Name, Content = Wonseok
    ParsedStr = List_forParse.split('=')
    Sort = str(ParsedStr[0])
    Content = str(ParsedStr[1]).strip()
    return Sort, Content

def InstallRequirements() :
    os.system('pip install -r requirements.txt')


class Engine(object) :
    # engine.py check the bash if system has enough settings.
    # one of the most important check component is these

    # check if user install postgresql.
    # check if user is using python 2.7 or upper version ( just in 2 version )
    def __init__(self) :

        SetExecuteLog('Engine initialize is started', 0)
        
        self.CheckOS() # OS check!!
        self.DBCheck() # DB Check!!
        self.PythonCheck() # Python version check!!
        self.isLaunchFirst()
        SetExecuteLog('OS, DB, Python check is completed', 0)
        flag = raw_input('System check complete!')
    

    def CheckOS(self) :
        # Error code 100 = OS error.
        self.OS_SORT = int(raw_input('What is your OS? ( Linux = 1, Windows = 2, Others = 3 ) : '))
        clearScreen(self.OS_SORT)
        print('OS check ... [OK] ')

    def DBCheck(self) :


        # Error code 101 = DB error.
        if( self.isPostgreInstall()  == False ) :
            print('System needs postgreSQL!')
            Exit(101)
        else :
            os.system('./UserConfig/ex.sh')
            print('Database check ... [OK] ')

    def PythonCheck(self) :
        # Error code 102 = Python version error
        if( self.isPythonVer2() == False ) :
            print('Your python version must be 2 !')
            Exit(102)
        else :
            print('Python check ... [OK] ')
    
    def isPythonVer2(self) :
        print('CHECK IF SYSTEM IS RUNNING PYTHON VERSION 2 .......... ')
        if( sys.version_info[0] == 2 ) :
            return True
        else : 
            return False

    def isPostgreInstall(self) :
        print('CHECK IF SYSTEM HAS POSTGRES VERSION ................. ')
        # This directory is must be needed.
        if( os.path.exists("/var/lib/postgresql/") ) :
            return True
        else :
            return False

    def launch(self) :
        '''
        ! - ATTENTION ALL PROGRAMMERS - #!

        This is the main loop function in this program.
        As you know, this is the main function as 'void main' in C/C++ function.
        If you want to check some logis or things, just edit here.
        '''
        clearScreen(self.OS_SORT)
        print('System will be loaded. Please wait!')
        self.load_SystemLoader()

        print('Kernel will be loaded. Please wait!')
        self.load_Kernel()
        L = raw_input('Press any key to continue....')

        # if you want to check logic of UI, check below function.
        self.UIManage()

    def load_SystemLoader(self) :
        self.SystemLoaderObject = SystemLoader()
        SetExecuteLog('System Loader initializer is successfully loaded',None)
        
        self.SystemLoaderObject.LoadDBFiles()
        SetExecuteLog('Database is successfully loaded.',None)
        
        self.SystemLoaderObject.LoadUserFiles()
        SetExecuteLog('User Files are successfully loaded.',None)

        SetExecuteLog('System Loadeer is loaded.',None)

    def load_Kernel(self) :
        self.KernelObj = Kernel( self.SystemLoaderObject )
        SetExecuteLog('Kernel is loaded.', None)

    def isLaunchFirst(self) :
        userConfigure = open('Configure.txt')
        ConfigureLines = userConfigure.readlines()
        for i in ConfigureLines :
            Sort, Content = ParseSortCont_FromString( i )
            if Sort == 'Execute' :
                if Content == 'no' :
                    InstallRequirements()
        
        userConfigure.close()

        userConfigure = open('Configure.txt', 'w')
        userConfigure.write('Execute=yes')

    def UpgradeOS(self, OSList) :
        # Now, only supports ubuntu and cent
        UbuntuServers = []
        CentServers = []
        for i in OSList['ubuntu'] :
            UbuntuServers.append( self.KernelObj.serverToServer(i) )

        for i in OSList['cent'] :
            CentServers.append( self.KernelObj.serverToServer(i) )

        # Ubuntu server upgrade
        for i in UbuntuServers :
            print(i, type(i))
            i.ThrowCommand('apt-get -y install update-manager-core')
            i.ThrowCommand('do-release-upgrade')

        # CentOS server upgrade
        for i in CentServers :
            i.ThrowCommand("su -c 'yum update")

        tmp = raw_input('Upgrade Done!')

    def UIManage(self) :
        # After this line, User interface starts!
        # Tree must be needed.   < AnyTree >
        '''
    @ Recent 2018 05 07  23:51   Wonseok
    [Null]
    |----[UserInterface] o
         |------[PrintServerManageMenu] o
         |      |------[Target Manage] o
         |      |      |-------[Target Manage Menu] o
         |      |              |--------[AddtargetMenu] o
         |      |              |--------[DeltargetMenu] o
         |      |              |--------[System UpdateMenu]
         |      |              |        |----------------[Operating System Upgrade ]
         |      |              |        |----------------[Update & Upgrade ]
         |      |              |        |----------------[ update at cron ]
         |      |              |--------[Throw command Menu] o
         |      |                       |----------------[Throw File (scp)] o
         |      |                       |                |------------------[ Set the command for file ] o
         |      |                       |                |------------------[ Send command ] o
         |      |                       |----------------[Throw Command]
         |      |------[Install database]
         |      |------[Go Backup Console]
         |      |------[Firewall manage]
         |
         |------[DatabaseManage]
         |------[Configuration Mode]
         |------[Security Mode]
         |------[Power Off]

         '''
     
        self.UI = UIManager.UserInterface(self)
        currentNode=[]
        currentNode.append(self.UI.nodUI)
        targets = [[]]
        while True :
            print( currentNode[0]) 
            if currentNode[0].name == "Null" :
                break
            else :
                if currentNode[0].name == "UserInterface" :
                    self.UI.PrintMainMenu(len(self.KernelObj.BadServerList), len(self.KernelObj.GoodServerList), currentNode)
                    continue

                elif currentNode[0].name == "PrintServerManageMenu" :
                    self.UI.PrintServerManageMenu(targets, currentNode)
                    continue

                elif currentNode[0].name == "DatabaseManage":
                    # Not developed yet
                    pass
                elif currentNode[0].name == "Configuration Mode":
                    # Not developed yet
                    pass
                elif currentNode[0].name == "Security Mode":
                    # not developed yet
                    pass
                elif currentNode[0].name == "Power Off" :
                    print("Good bye my kkammi ................ ")
                    
                elif currentNode[0].name == "Target Manage" :
                    self.UI.PrintAllTargetsDetails(targets, self.KernelObj.BadServerList, self.KernelObj.GoodServerList, currentNode)
                    continue

                elif currentNode[0].name == "Install database" :
                    # not developed yet
                    pass

                elif currentNode[0].name == "Go Backusp Console" :
                    # not developed yet
                    pass

                elif currentNode[0].name == "Firewall manage" :
                    # not developed yet
                    pass

                elif currentNode[0].name == "Target Manage Menu" :
                    self.UI.TargetManageMenu(targets, currentNode)
                    continue
                    
                elif currentNode[0].name == "AddtargetMenu" :
                    self.UI.AddtargetMenu(targets, self.KernelObj.BadServerList, self.KernelObj.GoodServerList, currentNode)
                    continue

                elif currentNode[0].name == "DeltargetMenu" :
                    self.UI.DeltargetMenu(targets, self.KernelObj.BadServerList, self.KernelObj.GoodServerList, currentNode)
                    continue

                elif currentNode[0].name == "System Update" :
                    self.UI.SystemUpdateMenu(targets, currentNode)
                    continue
                
                elif currentNode[0].name == "Operating System Upgrade" :
                    OSList = self.UI.OperatingSystemUpgrade(targets, currentNode)
                    self.UpgradeOS(OSList)
                
                elif currentNode[0].name == "Throw command menu" :
                    self.UI.func_ThrowCommandMenu(currentNode)
                    continue
                
                elif currentNode[0].name == "Throw File" :
                    self.UI.func_ThrowFilescp(currentNode)
                    continue
                
                elif currentNode[0].name == "Set the command for file" :
                    self.UI.func_SetCommandForFile(targets, currentNode)
                
                elif currentNode[0].name == "Send command" :
                    self.UI.func_SendCommand(currentNode)

            currentNode[0] = currentNode[0].parent
        # self.UI = UIManager.UserInterface(self)
        # target  = [[]]
        # level = 0
        # while(True) :
        #     # ? -> PrintMainMenu ( level = 0 )
        #     key = 0

        #     if( level == 0 ) :
        #         # level = 1 and key = 1
        #         key = self.UI.PrintMainMenu(len(self.KernelObj.BadServerList), len(self.KernelObj.GoodServerList))
        #         level += 1

        #     elif( key == 1 and level > 0) :
        #         # PrintMainMenu -> ServerManage
        #         clearScreen(self.OS_SORT)
        #         num = self.UI.PrintServerManageMenu(target)

        #         if( num == 1 ) :
        #             # PrintMainMenu -> ServerManage )-> TargetManage
        #             clearScreen(self.OS_SORT)
        #             num = self.UI.TargetManageMenu(target)

        #             if( num == 1 ) :
        #                 # PrintMainMenu -> ServerManage -> TargetManage) -> Add target
        #                 self.UI.AddtargetMenu(target, self.KernelObj.BadServerList, self.KernelObj.GoodServerList)
        #             elif( num == 2 ) : 
        #                 self.UI.DeltargetMenu(target, self.KernelObj.BadServerList, self.KernelObj.GoodServerList)


        #         elif( num == 2 ) :

        #         elif( num == 3 ) :
                
        #         elif( num == 4 ) :

        #     elif( key == 2 or level > 0 ) :
        #         # PrintMainMenu -> Database manage
        #         clearScreen(self.OS_SORT)
        #     elif( key == 3 or level ) :
        #         # PrintMainMenu -> Configuration mode
        #         clearScreen(self.OS_SORT)
        #     elif( key == 4 ) :
        #         # PrintMainMenu -> Seuciry mode
        #         clearScreen(self.OS_SORT)
        #     elif ( key == 0 ) :
        #         # PrintMainMenu -> Power off
        #         clearScreen(self.OS_SORT)
        #         print("Good bye kkami ...")

'''
    Below line is for test.
    You don't need to think of it.
'''
# Aprl 15
# May 2 added UI, and some class will be added.
if __name__ == "__main__" :
    E = Engine()
    E.launch()


<file_sep># @Author       Wonseok
# @Designer     Wonseok
# @Start at     Aprl. 13
# @Last at      Aprl. 13
# @Music        Paranoid - U Won Jae
# @Information  Ths class is for 'Human'. If you have more time, You can design it using 'Heritance'


class Administrator(object) :
    def __init__(self, Name=None, Path=None, Pw=None, Mode=None, Id=None):
        print('Log : Administrator initializer is loaded! ')
        self.NAME = Name
        self.PATH = Path
        self.PW = Pw
        self.MODE = Mode
        self.ID = Id

    def printInfo(self) :
        # STRUCTURE :
        # NAME : \nHOST : \n ...
        print('Administrator Information ~')
        print('Name  : ' + str(self.NAME))
        print('PATH  : ' + self.PATH)
        print('ID    : ' + str(self.ID))
        print('MODE  : ' + self.MODE)
        print('PW    : ' + "Check the file (for security)")
        print('')
    
    def getInfo(self) :
        strMsg = "NAME = " + str(self.NAME) + \
            "PATH = " + str(self.PATH) + \
            "PW = " + str(self.PW) + \
            "MODE = " + str(self.MODE) + \
            "ID = " + str(self.ID)
        return strMsg

    def __str__(self) :
        return "ADMINISTRATORCLASS"
<file_sep>import os
import sys
sys.path.insert(0, os.getcwd() )
# {value for value in variable}ys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
#
from ObjectInfo import AdministratorClass
from ObjectInfo import DatabaseClass

def ParseDataList_FromPath(FilePath) :
    # returns file contents in 'FilePath'
    # You can check your dir by using'print(os.getcwd())'
    File = open(str(FilePath), "r")
    return File.readlines()

def ParseSortCont_FromString(List_forParse):
    # It only returns two data which are Sort and Content of string in listself.
    # EX) NAME:Wonseok
    # Sort = Name, Content = Wonseok
    ParsedStr = List_forParse.split('=')
    Sort = str(ParsedStr[0])
    Content = str(ParsedStr[1]).strip()
    return Sort, Content

class SystemLoader(object) :

    def __init__ (self):
        # self.Admin = Administrator()
        self.Admin = AdministratorClass.Administrator()
        self.DB = DatabaseClass.DB()
        print('System Loader is Loaded! ... [OK] ')

    def EndProgram(self, Code):
        #print('System End.')
        pass

    def LoadDBFiles(self):
        # ParseDataFromPath returns list in file contents
        # This function returns nothing
        DatabaseData = ParseDataList_FromPath("./ProgramSettings/DataBaseSettings.txt")
        for i in range(0, len(DatabaseData)) :
            Sort, Content = ParseSortCont_FromString( DatabaseData[i] )
            if Sort == 'SORTS' :
                self.DB.SORTS = Content
            elif Sort == 'USER' :
                self.DB.USER = Content
            elif Sort == 'HOST' :
                self.DB.HOST = Content
            elif Sort == 'PORT' :
                self.DB.PORT = Content
            elif Sort == 'NAME' :
                self.DB.NAME = Content
            elif Sort == 'PW' :
                self.DB.PW = Content
            else : # For catch the error
                print (' INPUT ERROR AT DB SETTINGS.TXT ' )
                print (' (Input) Sort : ', Sort, ' Content : ', Content)
        # # END LOOP & for check
        # self.DB.printInfo()

    def LoadUserFiles(self):
        # This function returns nothing
        UserData = ParseDataList_FromPath("./ProgramSettings/UserSetting.txt")
        for i in range (0, len(UserData)) :
            Sort, Content = ParseSortCont_FromString( UserData[i] )
            if Sort == 'NAME' :
                self.Admin.NAME = Content
            elif Sort == 'PW' :
                self.Admin.PW = Content
            elif Sort == 'ID' :
                self.Admin.ID = Content
            elif Sort == 'MODE' :
                self.Admin.MODE = Content
            elif Sort == 'PATH' :
                self.Admin.PATH = Content
            else :
                print (' INPUT ERROR AT USER SETTINGS.TXT ' )
                print (' (Input) Sort : ', Sort, ' Content : ', Content)
        # # END LOOP & for check
        # self.Admin.printInfo()

    def printInfo(self) :
        self.Admin.printInfo()
        self.DB.printInfo()

    def __str__(self) :
        return "SYSTEMLOADER"
<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-

import os, sys
# @Author       Wonseok
# @Designer     Wonseok
# @Start at     Aprl. 12
# @Last at      Aprl. 13
# @Music        Do you heare the people sing? (Les miserables), To X-Girlfriend (san-E)
# @Information  This class is only for server each of being managed.
#               Unfortunately, now, if your DB is not 'postgreSQl', you can't control it.
from Logger import Logger
from pexpect import pxssh

sys.path.insert(0, os.getcwd() )
from ObjectInfo import DatabaseClass
from ObjectInfo import AdministratorClass
import time, datetime

class Configurator(object) :
    # Configurator supports functions which are about 'connect', 'back-up scheduling' ..
    # You can write some special functions in here to expand your own servers
    def Shell_login(self, Shell, Hostname, Username, Password) :
        # as same as Connector function named 'Shell_login'
        Shell.login( Hostname, Username, Password )
        Shell.prompt()
        print("Log 24 at Configurator" + Shell.before)


    def Shell_logout(self, Shell) :
        Shell.logout()


    def SendLog_NotConnecting(self, ExceptionClass) :
        ServerLogger = Logger( self.Server )
        # ReportType, Path, Name, Content
        s = str(datetime.datetime.now())
        CONTENT = "The server host (" + str(self.Server.ID) +") has some issue to connect. \
                    here is the log from server host." + str(ExceptionClass) + " This log \
                    is written at Configurator-SendLog_Notconnecting. Today date is " + \
                    s + " Log end. "

        RK = ServerLogger.MakeReport( 'WARNING_SERVICE_REPORT', self.Admin.PATH, self.Admin.NAME, CONTENT)
        ServerLogger.push_log('CONNECT', str(self.Server.ID), RK, 'KNOWN_LOG', 'BAD', 'PXSSHEXCEPTION', 'SERVERCLASS')

    def ConnectSSH(self) :
        # as similar as Connector's Connect_Servers
        try :
            sh = pxssh.pxssh()
            hostname = self.Server.CONNECTION_IPADDRESS
            username = self.Server.CONNECTION_USERNAME
            password = self.Server.CONNECTION_PASSWORD

            self.Shell_login(sh, hostname, username, password)

        except pxssh.ExceptionPxssh as e :
            self.SendLog_NotConnecting(e)
            print('  ' + str(hostname) + 'connection is bad! check the log!')


    # def __init__(self) :
    #     self.Logger = Logger( Configurator )


    def __init__(self, object, adminObject) :
        # Configurator must control server only < at Aprl 13 >
        # If configurator becomes bigger and has to support more functions,
        # code it on here.
        if( str(object) == "SERVER" ) :
            self.master = "SERVER"
            self.Server = object
            self.Admin = adminObject


    def __str__(self) :
        return 'Configurator'





def ParseDataList_FromPath(FilePath) :
    # returns file contents in 'FilePath'
    # You can check your dir by using'print(os.getcwd())'
    File = open(str(FilePath), "r")
    return File.readlines()




#
#       The codes below over here are for test.
#       Last updated at Aprl 13. < Tough cookie - Zico (feat. Don.mills) >
#       Test is completed at Aprl 15. < Dejavu ( Remastered ) - BeWhY >

def ParseSortCont_FromString(List_forParse):
    # It only returns two data which are Sort and Content of string in listself.
    # EX) NAME:Wonseok
    # Sort = Name, Content = Wonseok
    ParsedStr = List_forParse.split('=')
    Sort = str(ParsedStr[0])
    Content = str(ParsedStr[1]).strip()
    return Sort, Content


class testClass(object):

    def __init__ (self) :
        # logger SETTINGS
        print("DB class is made")
        self.db = DatabaseClass.DB()
        self.LoadDBFiles()


    def __str__(self) :
        return "Server"


    def LoadDBFiles(self):
        # ParseDataFromPath returns list in file contents
        # This function returns nothing
        print("load is complete")
        DatabaseData = ParseDataList_FromPath("./ProgramSettings/DataBaseSettings.txt")
        for i in range(0, len(DatabaseData)) :
            Sort, Content = ParseSortCont_FromString( DatabaseData[i] )
            if Sort == 'SORTS' :
                self.db.SORTS = Content
            elif Sort == 'USER' :
                self.db.USER = Content
            elif Sort == 'HOST' :
                self.db.HOST = Content
            elif Sort == 'PORT' :
                self.db.PORT = Content
            elif Sort == 'NAME' :
                self.db.NAME = Content
            elif Sort == 'PW' :
                self.db.PW = Content
            else : # For catch the error
                print (' INPUT ERROR AT DB SETTINGS.TXT ' )
                print (' (Input) Sort : ', Sort, ' Content : ', Content)
        # # END LOOP & for check
        # self.DB.printInfo()N

# if __name__ == "__main__" :
#     TestClass = testClass()
#     Conf1 = Configurator(TestClass)
