def get_clipboard_formats(): ''' Return list of all data formats currently in the clipboard ''' formats = [] if LINUX: encoding = getpreferredencoding() com = ["xclip", "-o", "-t", "TARGETS"] try: p = subprocess.Popen(com, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, ) for line in iter(p.stdout.readline, b''): if isinstance(line, binary_type): line = line.decode(encoding) formats.append(line.strip()) except Exception as e: print( "Exception from starting subprocess {0}: " "{1}".format(com, e)) if WIN32: import win32clipboard # pylint: disable=import-error f = win32clipboard.EnumClipboardFormats(0) while f: formats.append(f) f = win32clipboard.EnumClipboardFormats(f) if not formats: print("get_clipboard_formats: formats are {}: Not implemented".format(formats)) else: return formats
def _get_clipboard_data_from_system(self, formats): """once the clipboard is opened, just get the clipboard data meant as internal functions, called from copy_from_system return a dict with format, data pairs """ contents = {} if not formats: formats = [] f = win32clipboard.EnumClipboardFormats(0) while f: formats.append(f) f = win32clipboard.EnumClipboardFormats(f) elif isinstance(formats, int): formats = (formats, ) # Verify that the given formats are valid. if not formats: if self.debug > 1: print 'Clipboard, _get_clipboard_data_from_system, no formats available, empty clipboard...' return contents if formats: for format in formats: # if not format in self.format_names.keys(): # # print 'not getting clipboard for format: %s'% format # continue content = win32clipboard.GetClipboardData(format) contents[format] = content return contents
def __get_clipboard(self): self.logger.info('Getting clipboard contents') list_to_csv = [("COMPUTER_NAME", "TYPE", "DATA")] r = None try: r = Tk() # Using Tk instead because it supports exotic characters data = r.selection_get(selection='CLIPBOARD') r.destroy() list_to_csv.append( (self.computer_name, 'clipboard', unicode(data))) except: if r: # Verify that r exists before calling destroy r.destroy() win32clipboard.OpenClipboard() clip = win32clipboard.EnumClipboardFormats(0) while clip: try: format_name = win32clipboard.GetClipboardFormatName(clip) except win32api.error: format_name = "?" self.logger.info('format ' + unicode(clip) + ' ' + unicode(format_name)) if clip == 15: # 15 seems to be a list of filenames filenames = win32clipboard.GetClipboardData(clip) for filename in filenames: list_to_csv.append( (self.computer_name, 'clipboard', filename)) clip = win32clipboard.EnumClipboardFormats(clip) win32clipboard.CloseClipboard() return list_to_csv
def print_all_formats(): """ Prints all current clipboard formats and their names, for testing purposes only """ # Opens the Clipboard clp.OpenClipboard() # Enumerates Clipboard Formats clp_enum = clp.EnumClipboardFormats(0) # Loops over Format Enumerations while clp_enum: try: # Gets the Format Name format_name = clp.GetClipboardFormatName(clp_enum) except clp.error: format_name = "not defined" try: # Gets the Format format = clp.GetClipboardData(clp_enum) except clp.error: format = "not defined" print format_name print format clp_enum = clp.EnumClipboardFormats(clp_enum) # Closes the Clipboard clp.CloseClipboard()
def csv_clipboard(self): """Exports the clipboard contents""" # TODO : what happens if clipboard contents is a CSV string ? self.logger.info('Getting clipboard contents') with open(self.output_dir + '\\' + self.computer_name + '_clipboard.csv', 'wb') as output: csv_writer = get_csv_writer(output) write_to_csv(["COMPUTER_NAME", "TYPE", "DATA"], csv_writer) r = None #initialize the local variable r try: r = Tk() # Using Tk instead because it supports exotic characters data = r.selection_get(selection='CLIPBOARD') r.destroy() write_to_csv([self.computer_name, 'clipboard', unicode(data)], csv_writer) except: if r != None: # Verify that r exist before calling destroy r.destroy() win32clipboard.OpenClipboard() clip = win32clipboard.EnumClipboardFormats(0) while clip: try: format_name = win32clipboard.GetClipboardFormatName(clip) except win32api.error: format_name = "?" self.logger.info('format ' + unicode(clip) + ' ' + unicode(format_name)) if clip == 15: # 15 seems to be a list of filenames filenames = win32clipboard.GetClipboardData(clip) for filename in filenames: write_to_csv([self.computer_name, 'clipboard', filename], csv_writer) clip = win32clipboard.EnumClipboardFormats(clip) win32clipboard.CloseClipboard() record_sha256_logs(self.output_dir + '\\' + self.computer_name + '_clipboard.csv', self.output_dir + '\\' + self.computer_name + '_sha256.log')
def _get_clipboard_formats_open_clipboard(): """return clipboard formats available, when clipboard is open """ formats = [] f = win32clipboard.EnumClipboardFormats(0) while f: formats.append(f) f = win32clipboard.EnumClipboardFormats(f) return formats
def get_clipboard_formats(): ''' Return list of all data formats currently in the clipboard ''' formats = [] f = win32clipboard.EnumClipboardFormats(0) while f: formats.append(f) f = win32clipboard.EnumClipboardFormats(f) return formats
def read_all_clipboard(self): format_ = None # while True: w.OpenClipboard() if format_ is None: format_ = w.EnumClipboardFormats() else: format_ = w.EnumClipboardFormats(format_) data = w.GetClipboardData(format_) print(format_) print(data) w.CloseClipboard()
def GetAvailableFormats(): """ 返回可以支持的剪贴板格式 """ formats = [] try: win32clipboard.OpenClipboard(0) cf = win32clipboard.EnumClipboardFormats(0) while (cf != 0): formats.append(cf) cf = win32clipboard.EnumClipboardFormats(cf) finally: win32clipboard.CloseClipboard() return(formats)
def get_clipboard_formats(): ''' Return list of all data formats currently in the clipboard ''' formats = [] if sys.platform.startswith('win'): import win32clipboard # pylint: disable=import-error f = win32clipboard.EnumClipboardFormats(0) while f: formats.append(f) f = win32clipboard.EnumClipboardFormats(f) return formats else: printer.out("get_clipboard_formats: Not implemented for OS")
def GetAvailableFormats(self): """ Return a possibly empty list of formats available on the clipboard """ formats = [] try: win32clipboard.OpenClipboard(0) cf = win32clipboard.EnumClipboardFormats(0) while (cf != 0): formats.append(cf) cf = win32clipboard.EnumClipboardFormats(cf) finally: win32clipboard.CloseClipboard() return formats
def getTheClipboardType(): formats = [] clipboard.OpenClipboard() lastFormat = 0 nextFormat = clipboard.EnumClipboardFormats(lastFormat) while True: nextFormat = clipboard.EnumClipboardFormats(lastFormat) if 0 == nextFormat: # all done -- get out of the loop break else: formats.append(nextFormat) lastFormat = nextFormat clipboard.CloseClipboard() return formats
def getTypeList(): '''cb.set('===============') for i in range(1,65536): [[1, b'==============='], [7, b'==============='], [13, '==============='], [16, b'\x04\x08\x00\x00']] other:if d.args==('Specified clipboard format is not available',):continue TypeError('Specified clipboard format is not available') ''' w.OpenClipboard() r = {} i = 0 while True: i = w.EnumClipboardFormats(i) if not i: break try: d = w.GetClipboardData(i) except Exception as e: r[i] = e else: r[i] = d # r.append([i,d]) w.CloseClipboard() # 未close 会导致 clipboard 无法使用 return r
def formats(self): fmt = 0 while True: fmt = win32clipboard.EnumClipboardFormats(fmt) if not fmt: break yield fmt
def replaceSelectedText(iNewText, keepOldData=True): '''Replaces the selected text with the given one in the current window. If no text is selected given text will be inserted in the current location Currently this function uses Ctrl+V hack to set the text from the clipboard. It should work with most of the applications but not for all Also this method overrides the last clipboard state for binary content. It works fine if clipboard contains text data (ascii, unicode) but othercases old content is lost. ''' if keepOldData and 0: clipboard.OpenClipboard() oldFormat = 0 oldFormat = clipboard.EnumClipboardFormats(oldFormat) if oldFormat: oldData = clipboard.GetClipboardData(oldFormat) clipboard.CloseClipboard() else: oldFormat = 0 clipboard.OpenClipboard() clipboard.EmptyClipboard() clipboard.SetClipboardData(win32con.CF_UNICODETEXT, unicode(iNewText)) clipboard.CloseClipboard() sendKeys('^v') if oldFormat: clipboard.OpenClipboard() clipboard.EmptyClipboard() clipboard.SetClipboardData(oldFormat, oldData) clipboard.CloseClipboard()
def getSelectedText(keepOldData=True): '''Returns the selected text from the current window. Currently this function uses Ctrl+C hack to get the selected text to the clipboard and return it. It should work with most of the applications but not for all Also this method overrides the last clipboard state for binary content. It works fine if clipboard contains text data (ascii, unicode) but othercases old content is lost. ''' if keepOldData and 0: print 'trying to keep old data' clipboard.OpenClipboard() oldFormat = 0 oldFormat = clipboard.EnumClipboardFormats(oldFormat) if oldFormat: oldData = clipboard.GetClipboardData(oldFormat) clipboard.CloseClipboard() else: oldFormat = 0 sendKeys('^c') time.sleep(0.05) newData = getClipboardText() if oldFormat: clipboard.OpenClipboard() clipboard.EmptyClipboard() clipboard.SetClipboardData(oldFormat, oldData) clipboard.CloseClipboard() return newData
def get_files_by_clipboard(self): global clipboard_open, keyboard, mouse_left_down_pos, is_mouse_left_down, mouse, hm, screen_bound_ui files = None try: while self.clipboard_open: pass winclip.OpenClipboard() self.clipboard_open = True bak_fmt = winclip.EnumClipboardFormats() bak_data = winclip.GetClipboardData(bak_fmt) # mimic ctrl-c #if winclip.EnumClipboardFormats() == 13: # print "before sleep, copy data:"+winclip.GetClipboardData(winclip.CF_TEXT)+"dataend" #print str(mouse_left_down_pos) self.sy.syMouse.mouse.release( self.sy.syMouse.mouse_left_down_pos[0], self.sy.syMouse.mouse_left_down_pos[1], 1) self.sy.syMouse.is_mouse_left_down = False #print "first sleep over" #winclip.EmptyClipboard() #winclip.SetClipboardData(win32con.CF_TEXT, "setfordetectformatschangelater") winclip.CloseClipboard() self.clipboard_open = False # hide pointer # don't use mouse_pos_hide, since it's used in Hook self.sy.syMouse.mouse.move(self.sy.screen_bound_ui[0], self.sy.screen_bound_ui[1] / 2) # TODO: get mouse position by hook now as mouse_pos_hide # Hook mouse self.sy.hm.MouseMove = self.sy.syMouse.on_mouse_move # should be with hm.KeyUp = ... logically, but put here to give user a quick feed back that entered other screen # while localhost can continue its clipboard operations # TODO: not so graceful hear (time.sleep) time.sleep(0.2) #keyboard.tap_key(40) self.sy.syKeyboard.keyboard.press_key(162) # ctrl self.sy.syKeyboard.keyboard.press_key(67) # c self.sy.syKeyboard.keyboard.release_key(67) # c self.sy.syKeyboard.keyboard.release_key(162) # ctrl time.sleep(0.2) # TODO: how to detect clipboard open ? then i can check whether the ctrl-c had been pressed successfully while self.clipboard_open: pass winclip.OpenClipboard() self.clipboard_open = True #if winclip.EnumClipboardFormats() == 13 or winclip.EnumClipboardFormats() == 1: # print "copy data:"+winclip.GetClipboardData(winclip.CF_TEXT)+"dataend" #print hex(winclip.EnumClipboardFormats()) files = winclip.GetClipboardData(winclip.CF_HDROP) winclip.SetClipboardData(bak_fmt, bak_data) except Exception as e: print e finally: winclip.CloseClipboard() self.clipboard_open = False return files
def copy_from_system(self, formats=None, clear=False): """ Copy the Windows system clipboard contents into this instance. Arguments: - *formats* (iterable, default: None) -- if not None, only the given content formats will be retrieved. If None, all available formats will be retrieved. - *clear* (boolean, default: False) -- if true, the Windows system clipboard will be cleared after its contents have been retrieved. """ win32clipboard.OpenClipboard() # Determine which formats to retrieve. if not formats: format = 0 formats = [] while 1: format = win32clipboard.EnumClipboardFormats(format) if not format: break formats.append(format) elif isinstance(formats, int): formats = (formats, ) # Verify that the given formats are valid. try: for format in formats: if not isinstance(format, int): raise TypeError("Invalid clipboard format: %r" % format) except Exception, e: raise
def _enum_formats(self): self._check_ownership() format = 0 while True: format = win32clipboard.EnumClipboardFormats(format) if format == 0: break yield format
def check_for_file(): """ Checks if copied object was a file and then tries to get it's path """ try: clp.OpenClipboard() clip_enum = clp.EnumClipboardFormats(0) while clip_enum: try: format_name = clp.GetClipboardFormatName(clip_enum) except clp.error: format_name = "?" try: format = clp.GetClipboardData(clip_enum) except clp.error: format = "?" if (format_name == '?'): print format if (len(format) > 0): print "File Source Path: \n", format[0] # Path of the copied file path = format[0] # If path contains .pdf, extract it's metadata if (path[-4:] == '.pdf'): fp = open(path, 'rb') parser = PDFParser(fp) doc = PDFDocument(parser) if 'Title' in doc.info[0]: title = doc.info[0]['Title'] else: title = "No Title found" get_crossref_metadata(title, path) clip_enum = clp.EnumClipboardFormats(clip_enum) clp.CloseClipboard() except: print "error"
def getClipboard(): # 获取剪贴板数据 wc.OpenClipboard() if wc.EnumClipboardFormats(): # 数据格式不为 0,即剪切板是否为空 data = wc.GetClipboardData(wc.CF_UNICODETEXT) else: data = False wc.CloseClipboard() return data
def getClipboardFormats(): '''Returns a list containing the integer codes for the various formats currently in the clipboard Returns: list of formats currently in the clipboard list ''' openClipboard() available = [] nextAvailable = win32clipboard.EnumClipboardFormats(0) while nextAvailable: available.append(nextAvailable) nextAvailable = win32clipboard.EnumClipboardFormats(nextAvailable) win32clipboard.CloseClipboard() return available
def Get_clipboard_formats(cls): """returns a list of format types of current clipboard This is mainly meant for debugging purposes. """ if not OpenClipboardCautious(): print 'get_clipboard_formats, could not open clipboard' return try: # get proper format: formats, format = [], 0 formats = [] f = win32clipboard.EnumClipboardFormats(0) while f: formats.append(f) f = win32clipboard.EnumClipboardFormats(f) return formats finally: win32clipboard.CloseClipboard()
def copy_from_system(self, formats=None, clear=False): with win32_clipboard_ctx(): # Determine which formats to retrieve. caller_specified_formats = bool(formats) if not formats: format = 0 formats = [] while 1: format = win32clipboard.EnumClipboardFormats(format) if not format: break formats.append(format) elif isinstance(formats, integer_types): formats = (formats, ) # Verify that the given formats are valid. for format in formats: if not isinstance(format, integer_types): raise TypeError("Invalid clipboard format: %r" % format) # Update clipboard format names. self._update_format_names(formats) # Retrieve Windows system clipboard content. contents = {} for format in formats: # Allow GetClipboardData() to raise Windows API errors if # the caller specified one or more formats. If the # function raises an error at this point, it is likely the # format is not retrievable and the caller will want to # know, since they explicitly asked for this format. if caller_specified_formats: content = win32clipboard.GetClipboardData(format) contents[format] = content continue # Otherwise, catch and log Windows API errors. We assume # here that the caller is not much interested in # irretrievable formats. try: content = win32clipboard.GetClipboardData(format) contents[format] = content except pywintypes.error as err: format_repr = self.format_names.get(format, format) self._log.warning( "Could not retrieve clipboard data " "for format %r: %s", format_repr, err) self._contents = contents # Clear the system clipboard, if requested, and close it. if clear: win32clipboard.EmptyClipboard()
def getClipboardData(self): cb.OpenClipboard() fmt = cb.EnumClipboardFormats() cb.CloseClipboard() if fmt in [1, 13, 16, 7, 49224, 49327, 49322, 49158, 49459, 49471]: #text, unicode-text, locale, oem text, ShellIDList Array, Preferred DropEffect, Shell Object Offsets, Filename, FileNameW, Ole Private Data cb.OpenClipboard() self.clipboard, self.datatype = cb.GetClipboardData(cb.CF_UNICODETEXT), None cb.CloseClipboard() elif fmt in [2, 8, 17, 5, 49364]: #images self.clipboard, self.datatype = ImageGrab.grabclipboard(), 'img' return self.clipboard, self.datatype
def csv_clipboard(self): ''' Exports the clipboard contents ''' # TODO check if it is the same for older windows self.logger.info('Getting clipboard contents') with open( self.output_dir + '\\' + self.computer_name + '_clipboard.csv', 'wb') as output: csv_writer = get_csv_writer(output) #output.write('"Computer Name"|"Type"|Data"\n') try: r = Tk( ) # Using Tk instead because it supports exotic characters data = r.selection_get(selection='CLIPBOARD') r.destroy() #data = win32clipboard.GetClipboardData().decode('utf_8') write_to_csv([ self.computer_name, 'String data in clipboard', unicode(data) ], csv_writer) except: r.destroy() win32clipboard.OpenClipboard() clip = win32clipboard.EnumClipboardFormats(0) while clip: try: format_name = win32clipboard.GetClipboardFormatName( clip) except win32api.error: format_name = "?" self.logger.info('format ' + unicode(clip) + ' ' + unicode(format_name)) if clip == 15: # 15 seems to be a list of filenames filenames = win32clipboard.GetClipboardData(clip) for filename in filenames: write_to_csv([ self.computer_name, 'List of files in clipboard', filename ], csv_writer) clip = win32clipboard.EnumClipboardFormats(clip) win32clipboard.CloseClipboard()
def __getSelectedText(self): clipboard.OpenClipboard() newData = '' newFormat = 0 newFormat = clipboard.EnumClipboardFormats(newFormat) print newFormat if 1 or newFormat == con.CF_UNICODETEXT or newFormat == con.CF_TEXT: print 'gettting data' newData = clipboard.GetClipboardData(newFormat) clipboard.CloseClipboard() print 'cv: ' print newData return newData
def getTheClipboardTypes(): formats = [] win32clipboard.OpenClipboard() lastFormat = 0 while True: nextFormat = win32clipboard.EnumClipboardFormats(lastFormat) if 0 == nextFormat: break else: formats.append(nextFormat) lastFormat = nextFormat win32clipboard.CloseClipboard() return formats
def _getFormats(cls): # pylint: disable=invalid-name """Get format identifiers for contents currently on clipboard""" formats = [] fmt = 0 while 1: fmt = win32clipboard.EnumClipboardFormats(fmt) if fmt == 0: break formats.append(fmt) return formats
def getClipboardText(): ''' ''' clipboard.OpenClipboard() newData = '' newFormat = 0 newFormat = clipboard.EnumClipboardFormats(newFormat) print newFormat if newFormat == win32con.CF_UNICODETEXT or newFormat == win32con.CF_TEXT: print 'gettting data' newData = clipboard.GetClipboardData(newFormat) clipboard.CloseClipboard() print 'cv: ' print newData return newData