我已经设法让python打开了cmd。但是,在执行cmd.exe之前,使用runas administrator会附带密码检查。
我用这个打开命令。。。
import subprocess
subprocess.call(["runas", "/user:Administrator", "cmd.exe"])
我正在寻找一种方法来自动将密码输入到runas.exe提示符中,该提示符在我运行代码时打开。假设我要创建var = "test"
并将其添加到import subprocess
之后,我将如何创建它,以便将此变量传递给runas.exe并将其视为其输入?
该解决方案只需要3.4或更高版本中的python模块。
我发现了一些直接输入runas.exe的代码。然而,显然的输入是\x00\r\n
当在代码中输入应该是test
时,我非常确定如果我可以将输入设置为test
,那么代码将成功。
代码如下:
import subprocess
args = ['runas', '/user:Administrator', 'cmd.exe']
proc = subprocess.Popen(args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
proc.stdin.write(b'test\n')
proc.stdin.flush()
stdout, stderr = proc.communicate()
print (stdout)
print (stderr)
这段代码实际上可以工作(在Windows2008服务器上测试)。我用它为另一个用户调用
runas
,并传递他的密码。使用新用户上下文打开的新命令提示,无需输入密码。请注意,您必须安装
pywin32
才能访问win32 API。想法是:
Popen
命令,在没有任何输入重定向的情况下,重定向输出win32
包将密钥事件发送到控制台,最后使用\r
结束密码输入。(改编自this code):
虽然这不是你问题的答案,但它可以解决你的问题。使用psexec而不是runas。你可以这样运行:
(或者使用
subprocess.Popen
或其他方式从Python运行它)我正试着做和那个配偶一样的事。 复制代码 `
添加universal\u newlines=True似乎它可以像str那样写pass,而不像像objects那样写bytes。。
相关问题 更多 >
编程相关推荐