美文网首页亲好鉴定
在Python中执行PowerShell命令

在Python中执行PowerShell命令

作者: eleksbai | 来源:发表于2019-06-02 19:14 被阅读112次

    代码抄于scapy,使用方法见Example,
    使用with创建power shell对象,调run方法即可。

    import os
    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 = b_outs.decode(encoding=self.coding)
            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('ping 127.0.0.1')
        print('error:', os.linesep, errs)
        print('output:', os.linesep, outs)
    

    相关文章

      网友评论

        本文标题:在Python中执行PowerShell命令

        本文链接:https://www.haomeiwen.com/subject/fxffxctx.html