使用python打开cmd并自动输入密码

2024-09-28 21:15:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经设法让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)

Tags: 代码testimportcmd密码stderrstdinstdout
3条回答

这段代码实际上可以工作(在Windows2008服务器上测试)。我用它为另一个用户调用runas,并传递他的密码。使用新用户上下文打开的新命令提示,无需输入密码。

请注意,您必须安装pywin32才能访问win32 API。

想法是:

  • 对于Popen命令,在没有任何输入重定向的情况下,重定向输出
  • 逐字符读取,直到遇到“:”(密码提示的最后一个字符)。
  • 使用win32包将密钥事件发送到控制台,最后使用\r结束密码输入。

(改编自this code):

import win32console, win32con, time
import subprocess

username = "me"
domain = "my_domain"
password ="xxx"

free_console=True
try:
    win32console.AllocConsole()
except win32console.error as exc:
    if exc.winerror!=5:
        raise
    ## only free console if one was created successfully
    free_console=False

stdin=win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)

p = subprocess.Popen(["runas",r"/user:{}\{}".format(domain,username),"cmd.exe"],stdout=subprocess.PIPE)
while True:
    if p.stdout.read(1)==":":
        for c in "{}\r".format(password):  # end by CR to send "RETURN"
            ## write some records to the input queue
            x=win32console.PyINPUT_RECORDType(win32console.KEY_EVENT)
            x.Char=unicode(c)
            x.KeyDown=True
            x.RepeatCount=1
            x.VirtualKeyCode=0x0
            x.ControlKeyState=win32con.SHIFT_PRESSED
            stdin.WriteConsoleInput([x])

        p.wait()
        break

虽然这不是你问题的答案,但它可以解决你的问题。使用psexec而不是runas。你可以这样运行:

psexec -u user -p password cmd

(或者使用subprocess.Popen或其他方式从Python运行它)

我正试着做和那个配偶一样的事。 复制代码 `

args=(["runas.exe", "/user:admin", "program.exe"])
proc = subprocess.Popen(args, 
                        stdin=subprocess.PIPE, 
                        stdout=subprocess.PIPE, 
                        stderr=subprocess.PIPE,
                        universal_newlines=True)
passw='password'
proc.stdin.write(passw)
proc.stdin.flush()

stdout, stderr = proc.communicate()
print (stdout)
print (stderr)`

添加universal\u newlines=True似乎它可以像str那样写pass,而不像像objects那样写bytes。。

相关问题 更多 >