#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: zhibo.wang
# @E-mail: gm.zhibo.wang@gmail.com
# @Date : 2020/9/8 15:54
# @Desc : win pc wechat
"""
"spider_startime" : "17",
"spider_frequency" : "1d",
schtasks /create /sc daily /st 08:00:00 /tn "wechat_login" /tr G:\PythonTest\wechatGzh\crontab_task.bat
schtasks 无法设置起始于参数,也就无法执行bat批处理
schtasks /delete /tn wechat_login /F
"""
import getpass
import hashlib
import os
import socket
import subprocess
import time
import requests
# Command_Command 要执行的文件
# WorkingDirectory_WorkingDirectory 起始于
# URI_URI 任务名称
# StartBoundary_StartBoundary 任务时间 2020-09-09T11:55:00
# Date_Date 创建时间 2020-09-09T09:22:13
# Author_Author 机器名\用户名 DESKTOP-1OCBAP2\an
# UserId_UserId sid S-1-5-21-xxxxxxxx-xxxxxxx-xxxxxxx-1001
task_xml_demo = '''<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Date>Date_Date</Date>
<Author>Author_Author</Author>
<URI>\\URI_URI</URI>
</RegistrationInfo>
<Triggers>
<CalendarTrigger>
<StartBoundary>StartBoundary_StartBoundary</StartBoundary>
<Enabled>true</Enabled>
<ScheduleByDay>
<DaysInterval>1</DaysInterval>
</ScheduleByDay>
</CalendarTrigger>
</Triggers>
<Principals>
<Principal id="Author">
<UserId>UserId_UserId</UserId>
<LogonType>InteractiveToken</LogonType>
<RunLevel>LeastPrivilege</RunLevel>
</Principal>
</Principals>
<Settings>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
<AllowHardTerminate>true</AllowHardTerminate>
<StartWhenAvailable>false</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<IdleSettings>
<StopOnIdleEnd>true</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>false</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>
<Priority>7</Priority>
</Settings>
<Actions Context="Author">
<Exec>
<Command>Command_Command</Command>
<WorkingDirectory>WorkingDirectory_WorkingDirectory</WorkingDirectory>
</Exec>
</Actions>
</Task>'''
import_xml_demo = '''for %%f in (xml_path) do (
call :importfile "%%f"
)
exit /b 0
:importfile
set filename=%1
schtasks /create /tn "tn_tn" /xml %filename%
echo on
'''
class Create(object):
key = "click_pc_wechat_task"
def __init__(self):
self.delete_crontab()
self.cwd = os.getcwd()
self.host_name = socket.gethostname()
self.user_name = getpass.getuser()
self.create_import_xml_file()
self.create_crontab_task_file()
self.create_vbs_task_file()
def get_usersid(self):
UserId = None
cmd = "wmic useraccount where name=\"{}\" get sid".format(self.user_name)
print(cmd)
userid_str = [i.replace(" ", "") for i in subprocess.getoutput(cmd).split("\n") if len(i.replace(" ", "")) > 10]
if len(userid_str) > 0:
UserId = userid_str[0]
return UserId
def run_cmd(self, cmd):
os.system(cmd)
def delete_crontab(self):
print("删除计划任务")
cmd = "schtasks /delete /tn {} /F".format(self.key)
self.run_cmd(cmd)
def create_import_xml_file(self):
print("创建import_xml_file")
xml_path = "{}\click_pc_wechat_task.xml".format(self.cwd)
text = import_xml_demo.replace(
"xml_path", xml_path).replace("tn_tn", self.key)
file_name = "{}\import_xml.bat".format(self.cwd)
self.create_file(file_name, text)
def create_crontab_task_file(self):
print("创建crontab_task_file")
text = "python {}\click_pc_wechat.py".format(self.cwd)
file_name = "{}\crontab_task.bat".format(self.cwd)
self.create_file(file_name, text)
def create_vbs_task_file(self):
"""
隐藏cmd窗口
Set ws = CreateObject("Wscript.Shell")
ws.run "cmd /c G:\PythoProjects\pos-crawler\trunk\DataSpiders\DataSpiders\pc_wechat_gzh\crontab_task.bat",vbhide
"""
print("创建vbs_task_file")
text = 'Set ws = CreateObject("Wscript.Shell") \nws.run "cmd /c {file_name}",vbhide'.format(
file_name="{}\crontab_task.bat".format(self.cwd)
)
file_name = "{}\crontab_task.vbs".format(self.cwd)
self.create_file(file_name, text)
def md5_str(self, str):
md5 = hashlib.md5()
md5.update(str.encode())
result = md5.hexdigest()
return result
def get_date(self):
# 时间戳转换
time_local = time.localtime(time.time())
date = time.strftime("%Y-%m-%dT%H", time_local)
return date
def create_xml(self, spider_startime, spider_frequency):
day_date = self.get_date()
UserId = self.get_usersid()
if len(spider_startime) == 1:
end_time = "0{}:05:00".format(spider_startime)
else:
end_time = "{}:14:00".format(spider_startime)
Author = "{0}\\{1}".format(self.host_name, self.user_name)
Command = "{}\crontab_task.vbs".format(self.cwd)
WorkingDirectory = "{}\\".format(self.cwd.split("\\")[0])
URI = self.key
StartBoundary = day_date.split("T")[0] + "T" + end_time
DateStr = day_date + ":00:00"
text = task_xml_demo.replace(
"Command_Command", Command
).replace(
"WorkingDirectory_WorkingDirectory", WorkingDirectory
).replace(
"URI_URI", URI
).replace(
"StartBoundary_StartBoundary", StartBoundary
).replace(
"Date_Date", DateStr
).replace(
"Author_Author", Author
).replace("UserId_UserId", UserId)
file_name = "{}\click_pc_wechat_task.xml".format(self.cwd)
print("创建click_pc_wechat_task.xml")
self.create_file(file_name, text)
cmd = "{}\import_xml.bat".format(self.cwd)
print("执行 bat 文件 导入定时任务计划")
self.run_cmd(cmd)
def create_file(self, filename, text):
if ".xml" in filename:
f = open(filename, "w+", encoding="UTF-16")
else:
f = open(filename, "w+")
f.write(text)
f.close()
def run(self):
result = {"spider_startime": "16",
"spider_frequency": "1d"}
if result:
spider_startime = result.get("spider_startime")
spider_frequency = result.get("spider_frequency")
self.create_xml(spider_startime, spider_frequency)
if __name__ == "__main__":
C = Create()
C.run()