简体   繁体   中英

Best way to snip this long string

I want to run a peice of code, and it tell me if my firewall is on or off, for public and private networks. To do this I'm running the "netsh advfirewall show allprofiles" command in CMD, putting the output into a string and now I want to snip it so I just get the status of the firewall for public and private. This is my code for saving it in a string:

TextBox TxtResult = new TextBox();
string Command = "netsh advfirewall show allprofiles";

System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + Command);

procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;

procStartInfo.CreateNoWindow = true;

System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();

TxtResult.Text += proc.StandardOutput.ReadToEnd();

and that gives the following string:

netsh advfirewall show allprofiles

Domain Profile Settings: 
----------------------------------------------------------------------
State                                 ON
Firewall Policy                       BlockInbound,AllowOutbound
LocalFirewallRules                    N/A (GPO-store only)
LocalConSecRules                      N/A (GPO-store only)
InboundUserNotification               Enable
RemoteManagement                      Disable
UnicastResponseToMulticast            Enable

Logging:
LogAllowedConnections                 Disable
LogDroppedConnections                 Disable
FileName                              %systemroot%\system32\LogFiles\Firewall\pfirewall.log
MaxFileSize                           4096


Private Profile Settings: 
----------------------------------------------------------------------
State                                 ON
Firewall Policy                       BlockInbound,AllowOutbound
LocalFirewallRules                    N/A (GPO-store only)
LocalConSecRules                      N/A (GPO-store only)
InboundUserNotification               Enable
RemoteManagement                      Disable
UnicastResponseToMulticast            Enable

Logging:
LogAllowedConnections                 Disable
LogDroppedConnections                 Disable
FileName                              %systemroot%\system32\LogFiles\Firewall\pfirewall.log
MaxFileSize                           4096


Public Profile Settings: 
----------------------------------------------------------------------
State                                 ON
Firewall Policy                       BlockInbound,AllowOutbound
LocalFirewallRules                    N/A (GPO-store only)
LocalConSecRules                      N/A (GPO-store only)
InboundUserNotification               Enable
RemoteManagement                      Disable
UnicastResponseToMulticast            Enable

Logging:
LogAllowedConnections                 Disable
LogDroppedConnections                 Disable
FileName                              %systemroot%\system32\LogFiles\Firewall\pfirewall.log
MaxFileSize                           4096

Ok.

What would be the best way to get the state (on/off) for private profile and public profile into 2 variables. Should I search for the 2nd instance of the word "state", delete everything before it, and save the next 8 letters or so into a string? I'm not sure how reliable that is; any advice is appreciated.

You shouln't do this. It might work, but it's unstable. Keep in mind, not everyone has the systemsettings in english.

That said, you should better use an api to retrieve the values you are looking for.

From Rod Stephens's Blog :

// Create the firewall type.
Type FWManagerType = Type.GetTypeFromProgID("HNetCfg.FwMgr");

// Use the firewall type to create a firewall manager object.
dynamic FWManager = Activator.CreateInstance(FWManagerType);

// Check the status of the firewall.
bool enabled = FWManager.LocalPolicy.CurrentProfile.FirewallEnabled;

He also continued how to specify the profiles:

// Create consts for firewall types.
const int NET_FW_PROFILE2_DOMAIN = 1;
const int NET_FW_PROFILE2_PRIVATE = 2;
const int NET_FW_PROFILE2_PUBLIC = 4;

// Create the firewall type.
Type FWManagerType = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");

// Use the firewall type to create a firewall manager object.
dynamic FWManager = Activator.CreateInstance(FWManagerType);

// Get the firewall settings.
bool CheckDomain =
    FWManager.FirewallEnabled(NET_FW_PROFILE2_DOMAIN);
bool CheckPrivate =
    FWManager.FirewallEnabled(NET_FW_PROFILE2_PRIVATE);
bool CheckPublic =
    FWManager.FirewallEnabled(NET_FW_PROFILE2_PUBLIC);

Based on Retrieving Firewall Settings , you can use HNetCfg.FwPolicy2 :

dynamic fwPolicy2 = Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2")); // as NetFwTypeLib.INetFwPolicy2;

bool DomainProfileIsOn  = fwPolicy2.FirewallEnabled[1]; // fwPolicy2.FirewallEnabled[NetFwTypeLib.NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN];
bool PrivateProfileIsOn = fwPolicy2.FirewallEnabled[2]; // fwPolicy2.FirewallEnabled[NetFwTypeLib.NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE];
bool PublicProfileIsOn  = fwPolicy2.FirewallEnabled[4]; // fwPolicy2.FirewallEnabled[NetFwTypeLib.NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC];

For early binding, you can add reference to C:\\Windows\\System32\\FirewallAPI.dll and use the code in the comments.

The best way to parse it is using a regular expression. Try something like this:

Regex rx = new Regex(@"Private Profile Settings:[\s\S]*?State\s+(\w+)");
string status = rx.Match(text).Groups[1].Value;

The part in () is a group you are looking for, it has #1 (#0 is a whole matched text) - so you can refer to it in the rx.Match expression.

If you're looking for a boolean value:

bool statusbool = string.Equals(status, "ON", StringComparison.InvariantCultureIgnoreCase);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM