Python:如何将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:
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')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_valueUse 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

