python执行shell命令行_在Python中执行PowerShell命令

代码抄于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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值