牛叔叔 的笔记

好好学习

2020-12-22 08:51

使用Python设计远程屏幕监控软件(一)

牛叔叔

Python

(1355)

(0)

收藏

使用Python设计一款远程屏幕监控软件,在需要监控的电脑上运行该程序,该程序不断的截屏,并将屏幕数据压缩处理(提高网络传输速度),发送到网络 redis中缓存,监控程序可以从redis服务中读取最新的屏幕截图并展现。


本地全屏截屏代码:

    #本地全屏幕截图
    im = ImageGrab.grab()
    #图像尺寸(宽,高)元组
    size = im.size
    #发本地截图转换为字节串进行发送
    #imageBytes = im.tobytes()
    buf = BytesIO()
    im.save(buf, 'jpeg' ,quality=20)
    buf_str = buf.getvalue()


我们可以将redis操作进行封装,代码如下:

class Cache:
    def __init__(self,host='wanmait的redis服务器',password='万码学堂redis服务密码'):
        pool = redis.ConnectionPool(host=host,password=password)
        self.conn = redis.Redis(connection_pool=pool)
    def set(self,key,value):
        self.conn.set(key,value)
    def get(self,key):
        return self.conn.get(key)
    def insertImage(self,key,frame):
        b = pickle.dumps(frame)
        self.conn.set(key,b)

    def getImage(self,key):
        return pickle.loads(self.conn.get(key))
cache = Cache()


全部代码如下:

import pickle
import redis
import socket
import struct
from PIL import ImageGrab
import traceback
import gzip
import random
from time import sleep
from io import BytesIO

class Cache:
    def __init__(self,host='wanmait的redis服务器',password='万码学堂redis服务密码'):
        pool = redis.ConnectionPool(host=host,password=password)
        self.conn = redis.Redis(connection_pool=pool)
    def set(self,key,value):
        self.conn.set(key,value)
    def get(self,key):
        return self.conn.get(key)
    def insertImage(self,key,frame):
        b = pickle.dumps(frame)
        self.conn.set(key,b)

    def getImage(self,key):
        return pickle.loads(self.conn.get(key))
        
        
cache = Cache()
def putScreen():
    #本地全屏幕截图
    im = ImageGrab.grab()
    #图像尺寸(宽,高)元组
    size = im.size
    #发本地截图转换为字节串进行发送
    #imageBytes = im.tobytes()
    buf = BytesIO()
    im.save(buf, 'jpeg' ,quality=20)
    buf_str = buf.getvalue()

    imageBytes = gzip.compress(buf_str)
    cache.insertImage("wanmait_com_screen",imageBytes)
    cache.set("wanmait_size_w","%d"%size[0])
    cache.set("wanmait_size_h","%d"%size[1])

    print("发送一次数据:%d" % len(imageBytes))

if __name__=='__main__':
    while True:
        try:
            putScreen()

        except Exception as e:
            print('发送数据异常')
            pass
        sleep(3)#每隔3秒发送一次截屏


0条评论

点击登录参与评论