第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > python 以管理员权限调用cmd命令

python 以管理员权限调用cmd命令

时间:2024-04-16 03:02:28

相关推荐

python 以管理员权限调用cmd命令

一,将要执行的cmd命令放到xx.bat文件里

二,创建shell.vbs使系统以管理员权限运行

cwd = CreateObject("Scripting.FileSystemObject").GetFile(Wscript.ScriptFullName).ParentFolder.Pathpath = cwd & "\RestartInternet.bat"Set shell = CreateObject("Shell.Application")shell.ShellExecute path,"","","runas",1WScript.Quit

三,python调用

# !/usr/bin/python3# coding: utf-8import osimport subprocessimport tracebackdef runAdmin(cmd, timeout=1800000):# 这一段是将要执行的cmd命令写入.bat, 如果已经有创建好的.bat, 则这一段可以注释掉f = Nonetry:bat = os.getcwd() + r"\RestartInternet.bat"f = open(bat, 'w')f.write(cmd)except Exception as e:traceback.print_exc()raise efinally: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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。