Esempio n. 1
0
 def __init__(self, SETTINGS_FILE):
     """
     Creates an instance of BlackHole
     Arguments:
     SETTINGS_FILE: Path of the settings File
     """
     self.settings = None
     self.data = None
     self.information = None
     try:
         self._loadData(SETTINGS_FILE)
         Loger.write(self)  
         if self.data.user.enable:
             if self.data.user.timeEnabled:
                 now = datetime.now().time().replace(second=0)
                 if not (self.data.user.timeFrom < now < self.data.user.timeTo):
                     raise UserDisabledTime(self.data.user)
             self.data.user.lastLogin = datetime.now()
             self.data.user.save()
         else:
             raise UserDisabled(self.data.user)       
         self.blackHoleBrowser = cursesGui.BlackHoleBrowser(self)
     except OperationalError as e:
         raise MysqlException(e)
     except Exception as e:
         raise e
Esempio n. 2
0
 def __init__(self, SETTINGS_FILE):
     """
     Creates an instance of BlackHole
     Arguments:
     SETTINGS_FILE: Path of the settings File
     """
     self.settings = None
     self.data = None
     self.information = None
     try:
         self._loadData(SETTINGS_FILE)
         Loger.write(self)
         if self.data.user.enable:
             if self.data.user.timeEnabled:
                 now = datetime.now().time().replace(second=0)
                 if not (self.data.user.timeFrom < now <
                         self.data.user.timeTo):
                     raise UserDisabledTime(self.data.user)
             self.data.user.lastLogin = datetime.now()
             self.data.user.save()
         else:
             raise UserDisabled(self.data.user)
         self.blackHoleBrowser = cursesGui.BlackHoleBrowser(self)
     except OperationalError as e:
         raise MysqlException(e)
     except Exception as e:
         raise e
Esempio n. 3
0
 def getPrivateKey(self, user, environment):
     try:
         pk = PrivateKey.objects.get(user=user, environment=environment)
         try:
             if pk.type == 'DSA':
                 key = paramiko.DSSKey.from_private_key(pk)
             else:
                 key = paramiko.RSAKey.from_private_key(pk)   
         except Exception as e:
             Loger.writeError("%s [%s]" % (user, e.message))
             return False             
         return key
     except exceptions.ObjectDoesNotExist as e:
         return False
Esempio n. 4
0
 def getPrivateKey(self, user, environment):
     try:
         pk = PrivateKey.objects.get(user=user, environment=environment)
         try:
             if pk.type == 'DSA':
                 key = paramiko.DSSKey.from_private_key(pk)
             else:
                 key = paramiko.RSAKey.from_private_key(pk)
         except Exception as e:
             Loger.writeError("%s [%s]" % (user, e.message))
             return False
         return key
     except exceptions.ObjectDoesNotExist as e:
         return False
Esempio n. 5
0
 def closeLog(self, signum=None, frame=None):
     if not self.closed:
         self.sessionStopDate = datetime.now()
         sessionDuration = round((self.sessionStopDate - self.sessionStartDate).total_seconds() / 60, 3)
         usage = "%s/%s" % (self.enterCount, sessionDuration)
         Loger.write("[logout] user=%s to=%s as=%s sessionID=%s usage=%s" % (self.blackHole.data.user.userName, self.hostConnection.host.name, self.userConnection, self.blackHole.data.sessionID, usage))
         self.blackHole.writeSessionLog(self.hostConnection.host,
                                        self.hostConnection.userAuthentication,
                                        self.sessionStartDate,
                                        self.sessionStopDate,
                                        sessionDuration,
                                        round(self.enterCount/sessionDuration,3),
                                        self.keyCount,
                                        self.logFile)
         self.closed = True
Esempio n. 6
0
    def closeLog(self, signum=None, frame=None):
        if not self.closed:
            self.sessionStopDate = datetime.now()
            sessionDuration = round(
                (self.sessionStopDate - self.sessionStartDate).total_seconds()
                / 60, 3)

            Loger.write("[logout] user=%s to=%s as=%s sessionID=%s" %
                        (self.blackHole.data.user.userName,
                         self.hostConnection.host.name, self.userConnection,
                         self.blackHole.data.sessionID))
            self.blackHole.writeSessionLog(
                self.hostConnection.host,
                self.hostConnection.userAuthentication, self.sessionStartDate,
                self.sessionStopDate, sessionDuration, self.logFile)
            self.closed = True
Esempio n. 7
0
 def __init__(self, data):
     self.token = os.urandom(4).encode('hex')
     self._palette = [
         ('message', 'black', 'dark cyan'),
         ('alert', 'dark red', 'black'),
         ('bg', 'black', 'black'),
     ]
     self.message = urwid.Text(_(u"Enter the Token for the sessionID: %s") %
                               data.sessionID,
                               align='center')
     self.response = urwid.Edit(u"", align='center')
     self.alert = urwid.Text(u"", align='center')
     try:
         EmailSender(data.user, self.token, data.sessionID)
     except Exception as e:
         Loger.writeError("Error sending eMail Token SMS to %s [%s" %
                          (data.user.email, e))
         self.alert.set_text(u"%s" % e)
Esempio n. 8
0
 def writeSessionLog(self, host, userIdentity, loginDate, logoutDate, sessionDuration, usage, keyCount, logFile):
     try:
         blackholeServer = socket.gethostname()
         sessionLog = SessionLog(user=self.data.user,
                                    host=host,
                                    userIdentity=userIdentity,
                                    sourceIP=self.data.sourceIP,
                                    loginDate=loginDate,
                                    logoutDate=logoutDate,
                                    sessionID=self.data.sessionID,
                                    sessionDuration=sessionDuration,
                                    usage = usage,
                                    keyCount = keyCount,
                                    blackholeServer = blackholeServer,
                                    logFile = logFile)
         sessionLog.save()
     except Exception as e:
         Loger.writeError("!!%s [%s]" % (self.data.user.userName,e))
Esempio n. 9
0
 def writeSessionLog(self, host, userIdentity, loginDate, logoutDate,
                     sessionDuration, usage, keyCount, logFile):
     try:
         blackholeServer = socket.gethostname()
         sessionLog = SessionLog(user=self.data.user,
                                 host=host,
                                 userIdentity=userIdentity,
                                 sourceIP=self.data.sourceIP,
                                 loginDate=loginDate,
                                 logoutDate=logoutDate,
                                 sessionID=self.data.sessionID,
                                 sessionDuration=sessionDuration,
                                 usage=usage,
                                 keyCount=keyCount,
                                 blackholeServer=blackholeServer,
                                 logFile=logFile)
         sessionLog.save()
     except Exception as e:
         Loger.writeError("!!%s [%s]" % (self.data.user.userName, e))
    def __init__(self):
        self.user_list = {}
        self.loger = Loger('Server is starting...')
        self.running = False
        # self.name = ''
        # self.ip
        # self.port = 0
        # self.max_users = 0
        # self.server
        signal.signal(signal.SIGINT, self.signal_handle)

        # 处理参数
        self.parse_argvs()

        # 绑定IP和端口,并开启监听
        # 进入循环处理消息状态
        if self.bing_listen() and self.loop():
            pass
        else:
            self.loger.log('error while initting server')
            clean_server()
Esempio n. 11
0
 def __init__(self, data):
     '''
     Constructor
     '''
     self.token = os.urandom(4).encode('hex')
     self._palette = [('message','black','dark cyan'),
                      ('alert','dark red','black'),
                      ('bg', 'black', 'black'),]
     self.message = urwid.Text(_(u"Enter the Token for the sessionID: %s") % data.sessionID, align='center')
     self.response = urwid.Edit(u"",align='center')
     self.alert = urwid.Text(u"",align='center')
     try:
         if self.sendEmail: email = EmailSender(data.user,self.token,data.sessionID)
     except Exception as e:
         Loger.writeError("Error sending eMail Token SMS to %s [%s" % (data.user.email,e))
         self.alert.set_text(u"%s" % e)
     try:
         
         if self.sendEmail: SMSSender(data.user,self.token,data.sessionID)
     except Exception as e:
         Loger.writeError("Error sending SMS Token SMS to %s [%s]" % (data.user.getFullName(),e))
         self.alert.set_text(u"%s" % e)
 def __init__(self):
   self.user_list = {}
   self.loger = Loger('Server is starting...')
   self.running = False
   # self.name = ''
   # self.ip 
   # self.port = 0
   # self.max_users = 0
   # self.server 
   signal.signal(signal.SIGINT, self.signal_handle)
   
   # 处理参数
   self.parse_argvs()
   
   # 绑定IP和端口,并开启监听
   # 进入循环处理消息状态
   if self.bing_listen() and self.loop():
     pass
   else:
     self.loger.log('error while initting server')
     clean_server()
class Chatting_server:
    '''A server for chat online service'''
    User_Info_Dict_Template = {'IP': '', 'PORT': 0, 'NICK': ''}

    def __init__(self):
        self.user_list = {}
        self.loger = Loger('Server is starting...')
        self.running = False
        # self.name = ''
        # self.ip
        # self.port = 0
        # self.max_users = 0
        # self.server
        signal.signal(signal.SIGINT, self.signal_handle)

        # 处理参数
        self.parse_argvs()

        # 绑定IP和端口,并开启监听
        # 进入循环处理消息状态
        if self.bing_listen() and self.loop():
            pass
        else:
            self.loger.log('error while initting server')
            clean_server()

    def loop(self):
        inputs = [self.server]

        # 新建线程接收来自键盘的消息
        thread = threading.Thread(target=self.listen_keyboard)
        thread.setDaemon(True)
        thread.start()

        self.running = True
        # 等待接收键盘消息的套接字的连接
        try:
            socket_key, t = self.server.accept()
            inputs.append(socket_key)
        except socket.error, e:
            self.loger.log('error while accept key socket')
            self.running = False

        # 循环等待消息
        while self.running:
            #self.loger.log('user_list -->> ')
            #for i in self.user_list.keys():
            #  self.loger.log('%d ' % i.fileno() + str(self.user_list[i]))
            #self.loger.log('log before select')
            t = '[' + str(len(self.user_list)) + '] '
            for i in self.user_list.keys():
                t += str(i.fileno()) + '(' + self.user_list[i]['NICK'] + ') '
            self.loger.log(t)

            try:
                rl, wl, el = select.select(inputs, [], [])
            except select.error, e:
                self.loger.log('error while selectting : %s' % e)
            #self.loger.log('log after select')

            #self.loger.log( 'rs = %d; ws = %d; es = %d' % (len(rl), len(wl), len(el)))

            # 有事件发生, 可读/可写/异常
            for sock in rl:

                # 有新的连接请求
                if sock == self.server:
                    try:
                        client_no, client_info = self.server.accept()
                    except socket.error, e:
                        self.loger.log(
                            'error while acceptting new connection : %s' % e)
                        self.running = False
                        continue
                    client_info_dict = {
                        'IP': client_info[0],
                        'PORT': client_info[1]
                    }
                    if self.insert_user(client_no, client_info_dict):
                        self.loger.log('add new connection %d OK' %
                                       client_no.fileno())
                    else:
                        self.loger.log('add new connection %d failed' %
                                       client_no.fileno())
                        continue
                    inputs.append(client_no)

                # 有新数据到达
                else:
                    try:
                        recv_data = sock.recv(2048)
                        self.loger.log('recveive data from %d [%s]' %
                                       (sock.fileno(), recv_data.rstrip()))
                    except socket.error, e:
                        self.loger.log('error while receiving data from %d' %
                                       sock.fileno())
                        self.loger.log('%d will be closed' % sock.fileno())
                        inputs.remove(sock)
                        self.remove_user(sock)
                    # 来自键盘的消息
                    if sock == inputs[1]:
                        if 'EXIT' == recv_data:
                            self.running = False
                            continue
                    elif len(recv_data):
                        if recv_data.startswith('$$'):
                            self.command_handle(sock, recv_data[2:], inputs)
                        else:
                            self.check_broadcast(sock, recv_data)
                    else:
                        if self.server == sock:
                            self.running = False
                        self.loger.log('%d has closed the socket' %
                                       sock.fileno())
                        inputs.remove(sock)
                        self.remove_user(sock)
Esempio n. 14
0
 def __init__(self, user):
     messageString = _("The user %(username)s is only enabled from %(from)s to %(to)s")
     self.message = messageString % {'username':user.getFullName(),
                                         'from':user.timeFrom,
                                         'to':user.timeTo}
     Loger.writeError(self.message)         
Esempio n. 15
0
 def __init__(self, _message=""):
     self.message = _("DataBase Error: %s ") % _message   
     Loger.writeError(self.message)
Esempio n. 16
0
 def interactiveShell(self, chan):
     signal.signal(signal.SIGHUP, self.closeLog)
     oldtty = termios.tcgetattr(sys.stdin)
     log = self.blackHole.data.user.logEnable
     if log:
         try:
             if os.path.isdir(
                     os.path.join(self.blackHole.settings.log_path,
                                  self.blackHole.data.user.profile.name)):
                 logFile = "%s/%s/%s-%s-%s-%i_%s.log" % (
                     self.blackHole.settings.log_path,
                     self.blackHole.data.user.profile.name,
                     self.blackHole.data.user.userName, self.userConnection,
                     self.hostConnection.host.name,
                     self.blackHole.data.sessionID,
                     self.sessionStartDate.strftime("%Y%m%d_%H%M%S"))
             else:
                 Loger.writeError(
                     "[ERROR] Log Path don't Exists: %s" %
                     os.path.join(self.blackHole.settings.log_path,
                                  self.blackHole.data.user.profile.name))
                 logFile = "%s/%s-%s-%s-%i_%s.log" % (
                     self.blackHole.settings.log_path,
                     self.blackHole.data.user.userName, self.userConnection,
                     self.hostConnection.host.name,
                     self.blackHole.data.sessionID,
                     self.sessionStartDate.strftime("%Y%m%d_%H%M%S"))
             self.logFile = logFile
             file = open(logFile, 'w')
             os.chmod(
                 file.name, stat.S_IRUSR | stat.S_IRGRP | stat.S_IWRITE
                 | stat.S_IWGRP | stat.S_IROTH)
         except Exception as e:
             raise Exception("Creating log File [%s]" % e)
     try:
         tty.setraw(sys.stdin.fileno())
         tty.setcbreak(sys.stdin.fileno())
         chan.settimeout(0.0)
         if log:
             file.write("-------------- TIME STAMP: %s --------------\n" %
                        self.sessionStartDate.strftime("%Y-%m-%d %H:%M"))
         while True:
             r, w, e = select.select([chan, sys.stdin], [], [])
             if chan in r:
                 try:
                     x = chan.recv(1024)
                     if len(x) == 0:
                         break
                     if log:
                         try:
                             file.write(str(x).decode().replace('\r', ''))
                             file.flush()
                             os.fsync(file.fileno())
                         except:
                             file.write(str(x))
                             file.flush()
                             os.fsync(file.fileno())
                     sys.stdout.write(x)
                     sys.stdout.flush()
                 except socket.timeout:
                     break
                     #raise Exception(e)
             if sys.stdin in r:
                 x = os.read(sys.stdin.fileno(), 1)
                 if len(x) == 0:
                     break
                 chan.send(x)
     except:
         pass
     finally:
         termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
         if log:
             file.close()
Esempio n. 17
0
 def __init__(self, blackHole, widget, size):
     """
     * blackHole: blackHole object
     * widget: HostTree object
     * size: size of the terminal
     """
     self.blackHole = blackHole
     self.hostConnection = widget.hostConnectionObject
     self.widget = widget
     self.size = size
     self.userConnection = self.hostConnection.getConnectionUser(self.blackHole.data.user)
     self.enterCount = 0
     self.keyCount = 0
     self.sessionStartDate = datetime.now()
     self.sessionStopDate = None
     self.closed = False
     self.logFile = None
     
     try:
         paramiko_log_file = "/tmp/blackhole_%s.debug.log" % self.blackHole.data.user.userName
         if not os.path.exists(paramiko_log_file):
             open(paramiko_log_file, 'w').close()
         paramiko.util.log_to_file(paramiko_log_file)
         try:
         #Create the Socket
             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
             sock.settimeout(3)
             sock.connect((self.hostConnection.host.ip, self.hostConnection.host.port))
         except Exception as e:
             exceptionMsg = "*** Connect failed: [%s] to %s" % (str(e), self.hostConnection.host.name)
             Loger.writeError(exceptionMsg)
             raise Exception(exceptionMsg)
         try:
             # Create the Transport
             t = paramiko.Transport(sock)
             try:
                 #Connect to the ssh server
                 t.start_client()
                 try:
                     t.auth_publickey(self.userConnection, self.widget.pk)
                     Loger.write("[login] user=%s to=%s as=%s sessionID=%s" % (self.blackHole.data.user.userName, self.hostConnection.host.name, self.userConnection, self.blackHole.data.sessionID))
                 except paramiko.SSHException as e:
                     t.close()
                     sock.close()
                     Loger.writeError("%s [%s] %s " % (self.blackHole.data.user.userName, self.hostConnection.host.name, e.message))
                     raise Exception(e)  
                 chan = t.open_session()
                 cols, rows = size
                 chan.get_pty('xterm', cols, rows)
                 chan.invoke_shell()
                 self.interactiveShell(chan)
                 chan.close()
                 t.close()
                 sock.close()    
                 self.closeLog()
             except paramiko.SSHException as e:
                 exceptionMsg = '*** SSH negotiation failed to %s.' % self.hostConnection.host.name
                 Loger.writeError(exceptionMsg)
                 t.close()
                 sock.close()
                 raise Exception(exceptionMsg)
             except Exception as e:
                 raise(e)
         except Exception as e:
             raise Exception(e)
     except Exception as e:
         raise Exception(e)
Esempio n. 18
0
 def __init__(self, logPath):
     self.loger = Loger(logPath)
     self.loger.clear()
Esempio n. 19
0
class HopcroftAlghorithm:

    def __init__(self,logPath):
        self.loger = Loger(logPath)
        self.loger.clear()



    def minimize(self, automata):
        L = []
        P = [automata.finalStates]
        entries = automata.prepereEntriesTable()

        # initialize P and L
        regularStates = []
        for i, state in enumerate(automata.transitionTable):
            if i not in automata.finalStates:
                regularStates.append(i)
        P.append(regularStates)

        # put smaller list on L
        toPutOnListL = []
        if len(P[0]) < len(P[1]):
            toPutOnListL = statesSplitChar.join(str(x) for x in P[0])
        else:
            toPutOnListL = statesSplitChar.join(str(x) for x in P[1])

        for i,d in enumerate(automata.transitionTable[0]):
            L.append('{}{}{}'.format(toPutOnListL,symbolSplitChar,i))

        # as long as there are elements in L
        loopCounter = 1;

        # If there is only one state
        if len(P[0]) < 1 or len(P[1]) < 1:
            return None

        while L:
            self.loger.log('\n======== {}. loop ========\n'.format(loopCounter))
            self.loger.log('P: {}'.format(P))
            self.loger.log('L: {}'.format(L))
            itemFromL = L.pop(0)
            splited = itemFromL.split(symbolSplitChar)
            states = splited[0].split(statesSplitChar)
            symbol = splited[1]
            whatEnteres = []
            for state in states:
                potentialEntry = automata.entriesTable[int(state)][int(symbol)]
                if not potentialEntry:
                    continue
                else:
                    whatEnteres += potentialEntry

            # łamanie
            if not whatEnteres:
                self.loger.log('Nothing enters {} via symbol: {}'.format(states,symbol))
                loopCounter+=1
                continue
            self.loger.log('States: {} are entering {} via symbol: {}'.format(whatEnteres,states,symbol))
            tmpP = copy.deepcopy(P)
            self.loger.log('\nLooking for subset \'B\' of P to break apart')
            for i, B in enumerate(P):
                splited = splitOff(B, whatEnteres)
                if len(splited) > 1:
                    self.loger.log('\n{}. B: {} broken by: {} to: {}'.format(i+1,B,whatEnteres,splited))
                    tmpP.remove(B)
                    for split in splited:
                        tmpP.append(split)
                    self.loger.log('P after breaking up: {}'.format(tmpP))
                    # Uzupełnienie list L
                    flattenB = ''.join(str(x) for x in B)
                    wasFoundInL = False
                    self.loger.log('L before filling: {}'.format(L))
                    for g, element in enumerate(L):
                        split = element.split(symbolSplitChar)
                        states = split[0].split(statesSplitChar)
                        symbol = split[1]
                        joinedStates = "".join(states)

                        if flattenB in joinedStates:
                            replaced = L.pop(g)
                            for split in splited:
                                joinedSplit = statesSplitChar.join(str(x) for x in split)
                                self.loger.log('Replaced {} with {} in L'.format(replaced,joinedSplit+symbol))
                                L.insert(g,joinedSplit+symbolSplitChar+symbol)
                            wasFoundInL = True

                    if not wasFoundInL:
                        if len(splited[0]) != len(splited[1]):
                            splited = sorted(splited,key=len)
                            smallerBreak = splited[0]
                        else:
                            smallerBreak = splited[1]

                        smallerBreak = '-'.join(str(x) for x in smallerBreak)
                        for i, transition in enumerate(automata.transitionTable[0]):
                            L.append(smallerBreak+symbolSplitChar+str(i))
                            self.loger.log('Added {} to L'.format(smallerBreak+str(i)))
                    self.loger.log('L after filling: {}'.format(L))
                else:
                    self.loger.log('\n{}. B: {} cannot be broken by {}'.format(i+1,B,whatEnteres))
            P = tmpP
            loopCounter+=1
            self.loger.log("\n")
            self.loger.log('Final P: {}'.format(P))
            automataPrint = getAutomataPrintOut(P,automata)
            self.loger.log("\nMinimized automata transition table:\n")
            self.loger.log(automataPrint)

        return automataPrint;
Esempio n. 20
0
 def run(self):
     """Handle user input and display updating."""
     try:
         self.ui.tty_signal_keys('undefined', 'undefined', 'undefined', 'undefined', 'undefined')
         self.ui.set_mouse_tracking()
         self.size = self.ui.get_cols_rows()
         while 1:          
             focus, _ign = self.listbox.body.get_focus()
             self.header_text = [
         ('footer_msg', "BlackHole (v%s)" % black_hole.get_version()) , " ",
         ('footer_msg', _("User:"******" ",
         ('key', "%s" % self.user.getFullName()), " ",
         ('footer_msg', _("- Selected:")) , " ",
         ('key', "%s" % focus.description),
         ]
             self.header.set_text(self.header_text)
             canvas = self.view.render(self.size, focus=1)
             self.ui.draw_screen(self.size, canvas)
             keys = None
             while not keys:
                 keys = self.ui.get_input()
             for k in keys:
                 if urwid.is_mouse_event(k):
                     event, button, col, row = k
                     self.view.mouse_event(self.size, event, button, col, row, focus=True)
                     _widget, _tupla = self.listbox.get_focus()
                     if isinstance(_widget, HostTree):
                         if _widget.lastWasDoubleClick() and event == 'mouse press':
                             self.validate(_widget)
                 else:
                     if k == 'window resize':
                         self.size = self.ui.get_cols_rows()
                     elif k in ('q', 'Q'):
                         self.quit = True
                         self.stopUI()
                         return
                     elif k in ('c', 'C'):
                         if self.blackHole.settings.chat_enabled:
                             self.stopUI()
                             self.startChat()
                             self.startUI()
                         Loger.write(_("Chat not Enabled"))
                     elif k == 'right':
                         # right can behave like +
                         k = "+"
                     k = self.view.keypress(self.size, k)
                     if k == "enter":
                         _widget, _tupla = self.listbox.get_focus()
                         if isinstance(_widget, HostTree):
                             self.validate(_widget)
                         else:
                             continue
                     elif k == 'left':
                         self.move_focus_to_parent(self.size)
                     elif k == '-':
                         self.collapse_focus_parent(self.size)
                     elif k == 'home':
                         self.focus_home(self.size)
                     elif k == 'end':
                         self.focus_end(self.size)
     except Exception as e:
             raise Exception(e.message)
Esempio n. 21
0
    def __init__(self, widget, size):
        """
        * blackHole: blackHole object
        * widget: HostTree object
        * size: size of the terminal
        """
        self.blackHole = blackHole.BlackHole.instance
        self.hostConnection = widget.hostConnectionObject
        self.widget = widget
        self.size = size
        self.userConnection = self.hostConnection.getConnectionUser(
            self.blackHole.data.user)
        self.sessionStartDate = datetime.now()
        self.sessionStopDate = None
        self.closed = False
        self.logFile = None

        try:
            paramiko.util.logging.getLogger().setLevel(30)
            try:
                #Create the Socket
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.settimeout(3)
                sock.connect((self.hostConnection.host.ip,
                              self.hostConnection.host.port))
            except Exception as e:
                exceptionMsg = "*** Connect failed: [%s] to %s" % (
                    str(e), self.hostConnection.host.name)
                Loger.writeError(exceptionMsg)
                raise Exception(exceptionMsg)
            try:
                # Create the Transport
                t = paramiko.Transport(sock)
                try:
                    #Connect to the ssh server
                    t.start_client()
                    try:
                        t.auth_publickey(self.userConnection, self.widget.pk)
                        Loger.write(
                            "[login] user=%s to=%s as=%s sessionID=%s" %
                            (self.blackHole.data.user.userName,
                             self.hostConnection.host.name,
                             self.userConnection,
                             self.blackHole.data.sessionID))
                    except paramiko.SSHException as e:
                        t.close()
                        sock.close()
                        Loger.writeError(
                            "%s [%s] %s " %
                            (self.blackHole.data.user.userName,
                             self.hostConnection.host.name, e.message))
                        raise Exception(e)
                    chan = t.open_session()
                    cols, rows = size
                    chan.get_pty('xterm', cols, rows)
                    chan.invoke_shell()
                    self.interactiveShell(chan)
                    chan.close()
                    t.close()
                    sock.close()
                    self.closeLog()
                except paramiko.SSHException as e:
                    exceptionMsg = '*** SSH negotiation failed to %s.' % self.hostConnection.host.name
                    Loger.writeError(exceptionMsg)
                    t.close()
                    sock.close()
                    raise Exception(exceptionMsg)
                except Exception as e:
                    raise e
            except Exception as e:
                raise Exception(e)
        except Exception as e:
            raise Exception(e)
class Chatting_server:
  '''A server for chat online service'''
  User_Info_Dict_Template = {'IP':'', 'PORT':0, 'NICK':''}
  
  def __init__(self):
    self.user_list = {}
    self.loger = Loger('Server is starting...')
    self.running = False
    # self.name = ''
    # self.ip 
    # self.port = 0
    # self.max_users = 0
    # self.server 
    signal.signal(signal.SIGINT, self.signal_handle)
    
    # 处理参数
    self.parse_argvs()
    
    # 绑定IP和端口,并开启监听
    # 进入循环处理消息状态
    if self.bing_listen() and self.loop():
      pass
    else:
      self.loger.log('error while initting server')
      clean_server()
    
  def loop(self):
    inputs = [self.server]
    
    # 新建线程接收来自键盘的消息
    thread = threading.Thread(target=self.listen_keyboard)
    thread.setDaemon(True)
    thread.start()
    
    self.running = True
    # 等待接收键盘消息的套接字的连接
    try:
      socket_key, t = self.server.accept()
      inputs.append(socket_key)
    except socket.error, e:
      self.loger.log('error while accept key socket')
      self.running = False
    
    # 循环等待消息
    while self.running:
      #self.loger.log('user_list -->> ')
      #for i in self.user_list.keys():
      #  self.loger.log('%d ' % i.fileno() + str(self.user_list[i]))
      #self.loger.log('log before select')
      t = '[' + str(len(self.user_list)) + '] '
      for i in self.user_list.keys():
        t += str(i.fileno()) + '(' + self.user_list[i]['NICK']+ ') '
      self.loger.log(t)
      
      try:
        rl, wl, el = select.select(inputs, [], [])
      except select.error, e:
        self.loger.log('error while selectting : %s' % e)
      #self.loger.log('log after select')
      
      #self.loger.log( 'rs = %d; ws = %d; es = %d' % (len(rl), len(wl), len(el)))
      
      # 有事件发生, 可读/可写/异常
      for sock in rl:
        
        # 有新的连接请求
        if sock == self.server:
          try:
            client_no, client_info = self.server.accept()
          except socket.error, e:
            self.loger.log('error while acceptting new connection : %s' % e)
            self.running = False
            continue
          client_info_dict = {'IP':client_info[0], 'PORT':client_info[1]}
          if self.insert_user(client_no, client_info_dict):
            self.loger.log('add new connection %d OK' % client_no.fileno())
          else:
            self.loger.log('add new connection %d failed' % client_no.fileno())
            continue
          inputs.append(client_no)
        
        # 有新数据到达
        else:
          try:
            recv_data = sock.recv(2048)
            self.loger.log('recveive data from %d [%s]' % (sock.fileno(), recv_data.rstrip()))
          except socket.error, e:
            self.loger.log('error while receiving data from %d' % sock.fileno())
            self.loger.log('%d will be closed' % sock.fileno())
            inputs.remove(sock)
            self.remove_user(sock)
          # 来自键盘的消息
          if sock == inputs[1]:
            if 'EXIT' == recv_data:
              self.running = False
              continue
          elif len(recv_data):
            if recv_data.startswith('$$'):
              self.command_handle(sock, recv_data[2:], inputs)
            else:
              self.check_broadcast(sock, recv_data)
          else:
            if self.server == sock:
              self.running = False
            self.loger.log('%d has closed the socket' % sock.fileno())
            inputs.remove(sock)
            self.remove_user(sock)
Esempio n. 23
0
class MooreAlghorithm:
    markers = []

    def __init__(self, logPath):
        self.loger = Loger(logPath)
        self.loger.clear()

    def getMarkersPrint(self):
        printOut = ''
        for i, row in enumerate(self.markers):
            whitespace = '   ' * i
            printOut += '{}{}\n'.format(whitespace, row[i:])
        return printOut

    def glueStates(self):
        P = []
        whatWasGlued = []
        allStates = []
        for i, row in enumerate(self.markers):
            cutRow = row[i:]
            allStates.append(i)
            glued = []
            for k, column in enumerate(cutRow):
                if k == 0: continue
                truePos = k + i
                if column == 0 and truePos not in whatWasGlued:
                    glued.append(truePos)
                    whatWasGlued.append(truePos)
            if glued:
                P.append(glued + [i])
                whatWasGlued.append(i)

        # add states that were not glued
        diff = splitOff(allStates, whatWasGlued)[0]
        P += [[x] for x in diff]
        return P

    def minimize(self, automata):
        automata.prepereEntriesTable()
        L = []
        N = len(automata.transitionTable)
        self.markers = res = [[0 for i in range(N)] for j in range(N)]

        for i, transition in enumerate(automata.transitionTable):
            for finalState in automata.finalStates:
                if i not in automata.finalStates:
                    L.append([finalState, i])
                    self.markers[finalState][i] = 1
                    self.markers[i][finalState] = 1

        index = 1
        turnLength = len(L)
        rawIndex = 1
        self.loger.log('Tura 1')

        while L:
            pair = L.pop(0)

            if turnLength + 1 == rawIndex:
                index += 1
                rawIndex = 1
                turnLength = len(L)
                self.loger.log('\nTura {}'.format(index))

            for symbol, d in enumerate(automata.transitionTable[0]):
                entries1 = automata.entriesTable[pair[0]][symbol]
                entries2 = automata.entriesTable[pair[1]][symbol]
                self.loger.log('---------')
                self.loger.log('Pair: [{},{}] symbol: {}'.format(
                    pair[0], pair[1], symbol))
                if entries1 is None or entries2 is None:
                    continue
                self.loger.log('{} is entered by: '.format(pair[0]) +
                               ' '.join(str(x) for x in entries1))
                self.loger.log('{} is entered by: '.format(pair[1]) +
                               ' '.join(str(x) for x in entries2))
                for entry in entries1:
                    for entry2 in entries2:
                        if self.markers[entry][entry2] == 0 and self.markers[
                                entry2][entry] == 0:
                            self.loger.log('Can be added: {} {}'.format(
                                entry, entry2))
                            L.append([entry, entry2])
                            self.markers[entry][entry2] = index + 1
                            self.markers[entry2][entry] = index + 1
            rawIndex += 1
        self.loger.log('\n')
        printOut = self.getMarkersPrint()
        P = self.glueStates()
        automataPrintOut = getAutomataPrintOut(P, automata)
        self.loger.log(printOut)
        self.loger.log('Glued states: {}'.format(str(P)))
        self.loger.log(automataPrintOut)
        return automataPrintOut
Esempio n. 24
0
 def __init__(self, user):
     self.message = _("The user %s is not enabled.") % user.getFullName()
     Loger.writeError(self.message)
Esempio n. 25
0
 def interactiveShell(self, chan):
     signal.signal(signal.SIGHUP, self.closeLog)
     oldtty = termios.tcgetattr(sys.stdin)
     log = self.blackHole.data.user.logEnable
     if log:
         try:
             if os.path.isdir(os.path.join(self.blackHole.settings.log_path, self.blackHole.data.user.profile.name)):
                 logFile = "%s/%s/%s-%s-%s-%i_%s.log" % (self.blackHole.settings.log_path,
                                                         self.blackHole.data.user.profile.name,
                                                         self.blackHole.data.user.userName,
                                                         self.userConnection, 
                                                         self.hostConnection.host.name,
                                                         self.blackHole.data.sessionID,
                                                         self.sessionStartDate.strftime("%Y%m%d_%H%M%S"))
             else:
                 Loger.writeError("[ERROR] Log Path don't Exists: %s" % os.path.join(self.blackHole.settings.log_path, self.blackHole.data.user.profile.name))
                 logFile = "%s/%s-%s-%s-%i_%s.log" % (self.blackHole.settings.log_path,
                                                      self.blackHole.data.user.userName,
                                                      self.userConnection,
                                                      self.hostConnection.host.name,
                                                      self.blackHole.data.sessionID,
                                                      self.sessionStartDate.strftime("%Y%m%d_%H%M%S"))
             self.logFile = logFile
             file = open(logFile, 'w')
             os.chmod(file.name, stat.S_IRUSR | stat.S_IRGRP | stat.S_IWRITE | stat.S_IWGRP | stat.S_IROTH)
         except Exception as e:
             raise Exception("Creating log File [%s]" % e)
     try:
         tty.setraw(sys.stdin.fileno())
         tty.setcbreak(sys.stdin.fileno())
         chan.settimeout(0.0)
         if log: 
             file.write("-------------- TIME STAMP: %s --------------\n" % self.sessionStartDate.strftime("%Y-%m-%d %H:%M"))
         while True:
             r, w, e = select.select([chan, sys.stdin], [], [])
             if chan in r:
                 try:
                     x = chan.recv(1024)
                     if len(x) == 0:
                         break
                     if log:
                         try:
                             file.write(str(x).decode().replace('\r', ''))
                             file.flush()
                             os.fsync(file.fileno())
                         except:
                             file.write(str(x))
                             file.flush()
                             os.fsync(file.fileno())
                     sys.stdout.write(x)
                     sys.stdout.flush()                      
                 except socket.timeout:
                     break
                         #raise Exception(e)
             if sys.stdin in r:
                 x = os.read(sys.stdin.fileno(), 1)
                 if len(x) == 0:
                     break
                 chan.send(x)
                 if log:
                     if chr(13) in x:
                         file.write("\n[TIME STAMP: %s ]\n" % datetime.now().strftime("%Y-%m-%d %H:%M"))
                         file.flush()
                         os.fsync(file.fileno())
                         self.enterCount += 1
                     else:
                         self.keyCount += 1
     except:
         pass
     finally:
         termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
         if log:
             file.close()
Esempio n. 26
0
 def __init__(self, user):
     messageString = _("The user %(username)s is only enabled from %(from)s to %(to)s")
     self.message = messageString % {'username': user.getFullName(),
                                     'from': user.timeFrom,
                                     'to': user.timeTo}
     Loger.writeError(self.message)         
Esempio n. 27
0
 def __init__(self, _message):
     self.message = _("Error Loading Settings: %s") % _message   
     Loger.writeError(self.message)
Esempio n. 28
0
 def run(self):
     """Handle user input and display updating."""
     try:
         self.ui.tty_signal_keys('undefined', 'undefined', 'undefined',
                                 'undefined', 'undefined')
         self.ui.set_mouse_tracking()
         self.size = self.ui.get_cols_rows()
         while 1:
             focus, _ign = self.listbox.body.get_focus()
             self.header_text = [
                 ('footer_msg',
                  "BlackHole (v%s)" % black_hole.get_version()),
                 " ",
                 ('footer_msg', _("User:"******" ",
                 ('key', "%s" % self.user.getFullName()),
                 " ",
                 ('footer_msg', _("- Selected:")),
                 " ",
                 ('key', "%s" % focus.description),
             ]
             self.header.set_text(self.header_text)
             canvas = self.view.render(self.size, focus=1)
             self.ui.draw_screen(self.size, canvas)
             keys = None
             while not keys:
                 keys = self.ui.get_input()
             for k in keys:
                 if urwid.is_mouse_event(k):
                     event, button, col, row = k
                     self.view.mouse_event(self.size,
                                           event,
                                           button,
                                           col,
                                           row,
                                           focus=True)
                     _widget, _tupla = self.listbox.get_focus()
                     if isinstance(_widget, HostTree):
                         if _widget.lastWasDoubleClick(
                         ) and event == 'mouse press':
                             self.validate(_widget)
                 else:
                     if k == 'window resize':
                         self.size = self.ui.get_cols_rows()
                     elif k in ('q', 'Q'):
                         self.quit = True
                         self.stopUI()
                         return
                     elif k in ('c', 'C'):
                         if self.blackHole.settings.chat_enabled:
                             self.stopUI()
                             self.startChat()
                             self.startUI()
                         Loger.write(_("Chat not Enabled"))
                     elif k == 'right':
                         # right can behave like +
                         k = "+"
                     k = self.view.keypress(self.size, k)
                     if k == "enter":
                         _widget, _tupla = self.listbox.get_focus()
                         if isinstance(_widget, HostTree):
                             self.validate(_widget)
                         else:
                             continue
                     elif k == 'left':
                         self.move_focus_to_parent(self.size)
                     elif k == '-':
                         self.collapse_focus_parent(self.size)
                     elif k == 'home':
                         self.focus_home(self.size)
                     elif k == 'end':
                         self.focus_end(self.size)
     except Exception as e:
         raise Exception(e.message)
Esempio n. 29
0
 def __init__(self, fileName):
     self.fileName = fileName
     self.message = _("File %s is Missing") % self.fileName
     Loger.writeError(self.message)
Esempio n. 30
0
 def __init__(self, fileName):
     self.fileName = fileName
     self.message = _("File %s is Missing") % self.fileName
     Loger.writeError(self.message)
Esempio n. 31
0
 def __init__(self, userName):
     self.message = _("Unknown User [%s]") % userName
     Loger.writeError(self.message)
Esempio n. 32
0
 def __init__(self, _message):
     self.message = _("Error Loading Settings: %s") % _message   
     Loger.writeError(self.message)
Esempio n. 33
0
 def __init__(self, _message=""):
     self.message = _("DataBase Error: %s ") % _message   
     Loger.writeError(self.message)
Esempio n. 34
0
 def __init__(self, userName):
     self.message = _("Unknown User [%s]") % userName
     Loger.writeError(self.message)
Esempio n. 35
0
 def __init__(self):
     self.message = _("Missing BlackHole Instance")
     Loger.writeError(self.message)
Esempio n. 36
0
 def __init__(self, user):
     self.message = _("The user %s is not enabled.") % user.getFullName()
     Loger.writeError(self.message)