You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:如何将subprocess调用防火墙状态的结果赋值给变量并提取状态

Extract Windows Firewall States Using Python's subprocess

Hey there! Let's sort out how to capture those firewall states properly. The issue with subprocess.check_call() is that it executes the command and dumps output directly to the console—it doesn't return the output for you to process. Instead, we'll use subprocess.check_output() to capture the output, then parse it to pull out the ON/OFF values.

Here's a step-by-step solution:

  1. Capture the command output
    check_output() returns the command's stdout as bytes, which we'll convert to a string for parsing:

    import subprocess
    
    # Run the command and capture output (bytes format)
    raw_output = subprocess.check_output('netsh advfirewall show allprofiles state', shell=True)
    
    # Convert bytes to a human-readable string (use 'utf-8' encoding)
    output_text = raw_output.decode('utf-8')
    
  2. Parse the output to extract states
    We'll iterate through each line of the output, first identifying which profile we're looking at, then grabbing the corresponding state value:

    firewall_states = {}
    current_profile = None
    
    # Split the output into individual lines
    for line in output_text.splitlines():
        cleaned_line = line.strip()
        # Check if we've found a profile header
        if cleaned_line.endswith('Profile Settings:'):
            # Extract the profile name (e.g., "Domain", "Private")
            current_profile = cleaned_line.split()[0]
        # Check if we've found the state line for the current profile
        elif cleaned_line.startswith('State') and current_profile is not None:
            # The state is the last word in the line
            state_value = cleaned_line.split()[-1]
            firewall_states[current_profile] = state_value
    
  3. Use the captured states
    Now you have a dictionary mapping each firewall profile to its state:

    print(firewall_states)
    # Output: {'Domain': 'ON', 'Private': 'ON', 'Public': 'ON'}
    

Why this works:

  • subprocess.check_output() captures the command's output instead of printing it directly, giving you full control over processing.
  • We parse the output line by line to link each profile name to its corresponding state, avoiding fragile string slicing that might break if the output format changes slightly.

内容的提问来源于stack exchange,提问作者Park Yo Jin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:32:12