Recently, I received a network security book presented by the electronic industry press 《python Black hat 》, There are a total of 24 An experiment , Today, I will repeat the 20 An experiment ( screenshots ), My test environment is windows virtual machine +conda development environment +python3.7. This experiment is very interesting , stay windows In the environment , Running the script will automatically capture the screen , When I tested here, I found , The screenshot of the virtual machine is incomplete , It may have something to do with the resolution ~
1、 Students only need to cmd Run in python Script , A screenshot of the desktop can be generated
2、 You can view the screenshot of the screen in the directory where you run the script , It's not all cut here
Reference code :
# -*- coding: utf-8 -*-
# @Time : 2022/6/25 8:17 AM
# @Author : ailx10
# @File : screenshot.py
import base64
import win32api
import win32con
import win32gui
import win32ui
def get_dimensions():
width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)
return (width,height,left,top)
def screenshot(name="screenshot"):
hdesktop = win32gui.GetDesktopWindow()
width,height,left,top = get_dimensions()
desktop_dc = win32gui.GetWindowDC(hdesktop)
img_dc = win32ui.CreateDCFromHandle(desktop_dc)
mem_dc = img_dc.CreateCompatibleDC()
screenshot = win32ui.CreateBitmap()
screenshot.CreateCompatibleBitmap(img_dc,width,height)
mem_dc.SelectObject(screenshot)
mem_dc.BitBlt((0,0),(width,height),img_dc,(left,top),win32con.SRCCOPY)
screenshot.SaveBitmapFile(mem_dc,f"{name}.bmp")
mem_dc.DeleteDC()
win32gui.DeleteObject(screenshot.GetHandle())
def run():
screenshot()
with open("screenshot.bmp") as f:
img = f.read()
return img
if __name__ == "__main__":
screenshot()