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

2024-05-19 10:27:58 发布

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

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")

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


Tags: txtcompasswordsystemtmpfileproxysubprocess
1条回答
网友
1楼 · 发布于 2024-05-19 10:27:58

您的主要问题(至少正如所发布的那样)是,您已经将以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,比如说

相关问题 更多 >

    热门问题