主要功能是在电脑开机时获得屏幕截图和通过摄像头来拍摄照片,并将图片和照片保存在本地然后发送到我的gmail邮箱。
实时监控电脑自开机起的运行状态,谁在使用这台电脑。
完整代码:
#author:liangliang
#email: liangliangyy@gmail.com
#blog: http://www.lylinux.org/
#site: www.jb200.com
import time
from VideoCapture import Device
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import smtplib
from PIL import ImageGrab
import os
#获得当前时间
def get_correcttime() :
open_time = time.strftime('%m%d%H%M',time.localtime(time.time()))
return open_time
#获得屏幕截图并保存
def get_desktopimg(correcttime):
filename = r"F:/learn/watchcomputer/desktop" + correcttime + ".jpg"
pic = ImageGrab.grab()
pic.save(filename)
print "desktop img saved ok!!!!"
return filename
#获得摄像头照片并保存
def get_webcamimg(correcttime):
filename = filename = r"F:/learn/watchcomputer/webcam" + correcttime + ".jpg"
cam = Device()
cam.saveSnapshot(filename,timestamp=3, boldfont=1, quality=75)
print "webcam img saved ok!!!!!!"
return filename
#发送屏幕截图和摄像头照片到我的gmail邮箱!
def send_img(desktop,webcam):
try:
from_mail = "liangliangyy@gmail.com"
to_mail = "liangliangyy@gmail.com"
msg = MIMEMultipart()
msg['From'] = from_mail
msg['To'] = to_mail
msg['Subject'] = 'my computer'
body = 'test img send'
html_code = '<b><i>the guy who use my computer and the screen shot.</b></i><br> <img alt="desktop" src="cid:image1" /><img alt="webcam" src="cid:image2" />'
print html_code
con = MIMEText(html_code,'html','utf-8')
msg.attach(con)
img1 = MIMEImage(file(desktop,'rb').read())
img2 = MIMEImage(file(webcam,'rb').read())
img1.add_header('Content-ID','<image1>')
img2.add_header('Content-ID','<image2>')
msg.attach(img1)
msg.attach(img2)
server = smtplib.SMTP('smtp.gmail.com')
server.docmd('ehol',from_mail)
server.starttls()
server.login(from_mail,'password')#修改密码为你自己的
server.sendmail(from_mail,to_mail,msg.as_string())
server.quit()
print "mail send ok!!!!!"
return True
except:
return False
#将信息写入日志以供查看
def write_log(issuccess):
log_file_dir = r"F:/learn/watchcomputer/computer.log"
log_flie = file(log_file_dir,'a')
log_flie.write('at '+now_time + ' img saved success! ')
if(issuccess):
log_flie.write('mail send success!!!!!')
else:
log_flie.write('mail send failed.....')
log_flie.write('nn')
log_flie.close()
time.sleep(60)
now_time = get_correcttime()
desktopimg = get_desktopimg(now_time)
webcamimg = get_webcamimg(now_time)
#判断两个图片是否保存成功
if(os.path.isfile(desktopimg) and os.path.isfile(webcamimg)):
MailIsSend = send_img(desktopimg,webcamimg)
write_log(MailIsSend)
else:
exit(1)
print 'haaa running success !!!!'
代码说明:
首先,获得当前时间,然后获得屏幕截图和摄像头截图并保持在本地,然后检查这两张图片是否保存成功,若成功,则发送到gmail邮箱,否则退出程序,然后将当前时间和邮件是否发送成功写入到日志文件中.
将以上代码保存,然后新建一个computer.vbs文件,复制以下代码:
将上面的路径修改为python程序的保存路径,然后将这个vbs文件发送快捷方式到你电脑的启动菜单里面的启动文件夹中,即可在电脑开机时运行了。
以上代码是第一版,第二版请参考:python监控电脑实例教程(2),实现了收取特定邮件,如果检测到的话可以实现关闭电脑功能。