使用Python代码以[Powershell模式]运行.bat文件

3

Proxy.bat文件包含:

@ECHO OFF 1>NUL 2>NUL
powershell -Command $pword = read-host "enter password" -AsSecureString ; $BSTR= 
[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword)  ; 
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) > .tmp.txt & set /p password= 
<.tmp.txt & del .tmp.txt
>NUL set http_proxy=http://%1:%password%@abc.yz.com:80
>NUL set https_proxy=https://%1:%password%@abc.yz.com:80
>NUL set no_proxy=abc.yz.com

Python 代码

from subprocess import Popen
import subprocess
def run_batch_file(file_path):
Popen(file_path,creationflags=subprocess.CREATE_NEW_CONSOLE)

run_batch_file("D:\\gower\\proxy.bat")

密码请求未执行。请问如何使脚本能够响应密码,请提供建议。


<.tmp.txt & del .tmp.txt 前面有一个多余的换行符... - aschipfl
1个回答

0

你的主要问题 - 至少是根据发布的内容 - 是你将以 powershell 开头的命令分散在了多行上(没有使用 cmd.exe 的行续行机制,该机制是在行末添加一个 ^,但只能在 "..." 字符串之外)。

这里有一个简化版本,也通过 for /f 循环(PSv5+ 语法)消除了需要临时文件的需要:

for /f "usebackq delims=" %%i in (`
powershell -c "[pscredential]::new('unused', (Read-Host 'enter password' -AsSecureString)).GetNetworkCredential().Password"
`) do set "password=%%i"

注意:由于您正在创建运行批处理文件和带有标志subprocess.CREATE_NEW_CONSOLE的PowerShell的进程,所以新创建的控制台窗口将在批处理文件完成后自动关闭,因此为了查看进程的输出,您必须将其重定向到文件或在批处理文件末尾放置一个pause


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接