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

使用python代码运行.bat文件[Powershell模式],python,powershell,batch-file,Python,Powershell,Batch File,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]::PtrToString

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

密码请求未执行。您能否建议如何使用密码响应执行脚本。

您的主要问题(至少是发布的问题)是您已将以
powershell
开头的命令分散到多行(不使用
cmd.exe
的行延续机制,该机制是行末尾的
^
,但仅在
“…
字符串之外)

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


注意:由于您正在创建运行批处理文件的进程,然后是带有标记的PowerShell
子进程。CREATE_NEW_CONSOLE
,新创建的CONSOLE窗口将在批处理文件完成时自动关闭,因此为了查看进程的输出,您必须将其重定向到一个文件或放置一个
暂停例如,批处理文件末尾的de>。


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