一,将要执行的cmd命令放到xx.bat文件里
二,创建shell.vbs使系统以管理员权限运行
cwd = CreateObject("Scripting.FileSystemObject").GetFile(Wscript.ScriptFullName).ParentFolder.Path
path = cwd & "\RestartInternet.bat"
Set shell = CreateObject("Shell.Application")
shell.ShellExecute path,"","","runas",1
WScript.Quit
三,python调用
# !/usr/bin/python3
# coding: utf-8
import os
import subprocess
import traceback
def runAdmin(cmd, timeout=1800000):
# 这一段是将要执行的cmd命令写入.bat, 如果已经有创建好的.bat, 则这一段可以注释掉
f = None
try:
bat = os.getcwd() + r"\RestartInternet.bat"
f = open(bat, 'w')
f.write(cmd)
except Exception as e:
traceback.print_exc()
raise e
finally:
if f:
f.close()
try:
shell = os.getcwd() + r"\shell.vbs"
sp = subprocess.Popen(
shell,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
print("[PID] %s: %s" % (sp.pid, cmd))
sp.wait(timeout=timeout)
stderr = str(sp.stderr.read().decode("gbk")).strip()
stdout = str(sp.stdout.read().decode("gbk")).strip()
if "" != stderr:
raise Exception(stderr)
if stdout.find("失败") > -1:
raise Exception(stdout)
except Exception as e:
raise e