Python 3: How to use subprocess.run() as admin (windows 10)

心已入冬 提交于 2021-01-28 02:40:31

问题


I need to run the following information in windows command line. Someone kindly helped me with the syntax for subprocess.run(). I get the error "[WinError 5] Access is denied", which potentially requires admin access rights. How can I use subprocess.run() as administrator? [Not on a corporate pc or anything, I have access to administrator rights]

subprocess.run([
    r'"C:\Program Files\ANSYS Inc\ANSYS Student\v194\Framework\bin\Win64\runwb2"',
     '-B',
     '-F',
    r'E:\MEngA\Ansys\IFD_PartA_Rev3.wbpj',
     '-R',
    r'E:\MEngA\Results\sn07\script_partA.wbjn',
])

If anyone has done this before and knows "[WinError 5] Access is denied" is not related to admin rights, I'd also like to hear about that! Thanks in advance.

Edit - I have seen the following post (Run process as admin with subprocess.run in python) but am not finding it overly helpful. I've also read Python doc (https://docs.python.org/3/library/subprocess.html) and am not feeling enlightened.

Edit - I think this is closer:

processjl = subprocess.Popen(['runas', '/noprofile', '/user:Joe', r'C:\Program Files\ANSYS Inc\ANSYS Student\v194\Framework\bin\Win64\runwb2'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
processjl.stdin.write(b'pass')
stdout, stderr = processjl.communicate()

But in return I get:

Enter the password for Joe: \x00\r\n

Any ideas? I am a mechanical engineer learning python to automate some finite element analysis tasks. I can do data work in python but am having trouble understanding this.


回答1:


You're almost there but you cannot use runas because it will prompt you for password. You need something similar that allows you to provide password in the command line, it is:

https://docs.microsoft.com/en-us/sysinternals/downloads/psexec

Download this and install in your machine. Then you can do this to check it works

psexec.exe -u username -p password command_line_here

Afterwards, your command is simply:

processjl = subprocess.Popen([
      'psexec.exe', '-u', 'username', '-p', 'password',
       r'C:\Program Files\ANSYS Inc\ANSYS Student\v194\Framework\bin\Win64\runwb2'
    ],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE)
stdout, stderr = processjl.communicate()


来源:https://stackoverflow.com/questions/60214168/python-3-how-to-use-subprocess-run-as-admin-windows-10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!