#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
import os
from time import sleep
import time
import json
from glob import glob
import subprocess as sp


class PowerShell:
    # from scapy
    def __init__(self, coding, ):
        cmd = [self._where('PowerShell.exe'),
               "-NoLogo", "-NonInteractive",  # Do not print headers
               "-Command", "-"]  # Listen commands from stdin
        startupinfo = sp.STARTUPINFO()
        startupinfo.dwFlags |= sp.STARTF_USESHOWWINDOW
        self.popen = sp.Popen(cmd, stdout=sp.PIPE, stdin=sp.PIPE, stderr=sp.STDOUT, startupinfo=startupinfo)
        self.coding = coding

    def __enter__(self):
        return self

    def __exit__(self, a, b, c):
        self.popen.kill()

    def run(self, cmd, timeout=15):
        b_cmd = cmd.encode(encoding=self.coding)
        try:
            b_outs, errs = self.popen.communicate(b_cmd, timeout=timeout)
        except sp.TimeoutExpired:
            self.popen.kill()
            b_outs, errs = self.popen.communicate()
        outs_str = b_outs.decode(encoding=self.coding)
        outs = outs_str[27:34].strip()
        headers = {
            'Content-Type': 'application/json',
        }

        params = (
            ('key', '3ab16392-0258-4239-b4a3-cb1c8f0dffd7'),
        )


        # print(data)
        if outs == "Online":
            outs = "市电正常"
            # print(len(outs[27:34].strip()))

            data = '{"msgtype": "markdown","markdown": {"content": ' + '"' + outs + '"' + '}}'
            response = requests.post('https://qyapi.weixin.qq.com/cgi-bin/webhook/send', headers=headers, params=params, data=data.encode('utf-8'))
        else:
            outs = "市电异常"
            # print(len(outs[27:34].strip()))

            data = '{"msgtype": "markdown","markdown": {"content": ' + '"' + outs + '"' + '}}'
            response = requests.post('https://qyapi.weixin.qq.com/cgi-bin/webhook/send', headers=headers, params=params,
                                     data=data.encode('utf-8'))

        return outs, errs

    @staticmethod
    def _where(filename, dirs=None, env="PATH"):
        """Find file in current dir, in deep_lookup cache or in system path"""
        if dirs is None:
            dirs = []
        if not isinstance(dirs, list):
            dirs = [dirs]
        if glob(filename):
            return filename
        paths = [os.curdir] + os.environ[env].split(os.path.pathsep) + dirs
        try:
            return next(os.path.normpath(match)
                        for path in paths
                        for match in glob(os.path.join(path, filename))
                        if match)
        except (StopIteration, RuntimeError):
            raise IOError("File not found: %s" % filename)


if __name__ == '__main__':
    # Example:
    with PowerShell('GBK') as ps:
        outs, errs = ps.run('Add-Type -AssemblyName System.Windows.Forms;[System.windows.Forms.SystemInformation]::PowerStatus')
    # print('error:', os.linesep, errs)
    # print('output:', os.linesep, outs)

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注