C++ 修改防火墙firewall设置(Windows)

news2024/12/30 3:29:30

在这里插入图片描述

文章目录

  • 1、简介
    • 1.1 防火墙概述
    • 1.2 入站,还是出站?
    • 1.3 防火墙规则优先级
  • 2、系统界面方式
  • 3、命令行方式
    • 3.1 防火墙基本状态设置
    • 3.2 入站出站规则设置
    • 3.3 其他设置
    • 3.4 telnet检测端口
  • 4、C++方式
    • 4.1 注册表
    • 4.2 COM(Windows XP)
    • 4.3 COM(Windows Vista and later)
  • 5、VB方式
  • 结语

1、简介

防火墙(英语:Firewall)技术是通过有机结合各类用于安全管理与筛选的软件和硬件设备,帮助计算机网络于其内、外网之间构建一道相对隔绝的保护屏障,以保护用户资料与信息安全性的一种技术。
在这里插入图片描述

1.1 防火墙概述

所谓“防火墙”是指一种将内部网和公众访问网(如Internet)分开的方法,它实际上是一种建立在现代通信网络技术和信息安全技术基础上的应用性安全技术,隔离技术。越来越多地应用于专用网络与公用网络的互联环境之中,尤其以接入Internet网络为最甚。
在这里插入图片描述

1.2 入站,还是出站?

入站是外网的人访问我;出站是我访问外网。
入站开了本机的443端口,意味着外网的人可以通过443端口访问你的HTTPS服务;出站设置一般是允许访问外网IP的443端口。

入站端口:就是别人来访问我的某个端口。比如我设置阻止连接所有站点的入站端口8080,就是所有其他主机不能访问我这台服务器的8080端口。
出站端口:就是我去访问别人的某个端口。比如我设置阻止连接所有站点的出站端口3306,就是我不能访问所有其他网址的3306端口
在这里插入图片描述

1.3 防火墙规则优先级

Windows防火墙的规则扫描有它自己特定的顺序,其优先级为:
1、只允许安全连接
2、阻止连接
3、允许连接
4. 默认规则(如果没有设置,那就是默认阻止)

As soon as a network packet matches a rule, that rule is applied, and processing stops. For example, an arriving network packet is first compared to the authenticated bypass rules. If it matches one, that rule is applied and processing stops. The packet is not compared to the block, allow, or default profile rules. If the packet does not match an authenticated bypass rule, then it is compared to the block rules. If it matches one, the packet is blocked, and processing stops, and so on.

在这里插入图片描述

2、系统界面方式

打开控制面板,点击系统和安全。
在这里插入图片描述
点击Windows Defender防火墙。
在这里插入图片描述
点击右侧的高级设置。
在这里插入图片描述
点击入站规则,然后点击右侧的新建规则。
在这里插入图片描述
然后勾选端口,点击下一步。
在这里插入图片描述
接着填写开放的端口号(如5000)。
在这里插入图片描述
接着如果是允许连接的话,直接点击下一步。
在这里插入图片描述
接着直接点击下一步。
在这里插入图片描述
接着填写名字和描述,点击完成。
在这里插入图片描述
在入站规则中出现了刚才添加的规则。
在这里插入图片描述

3、命令行方式

在这里插入图片描述

Win10 如何使用cmd命令行配置防火墙:

3.1 防火墙基本状态设置

# 查看当前防火墙状态:
netsh advfirewall show allprofiles
netsh advfirewall show allprofiles state

在这里插入图片描述

# 恢复初始防火墙设置:
netsh advfirewall reset

# 设置默认输入和输出策略:
# 设置为允许
netsh advfirewall set allprofiles firewallpolicy allowinbound,allowoutbound
# 设置为拒绝
netsh advfirewall set allprofiles firewallpolicy blockinbound,blockoutbound
# 显示默认的入站和出站防火墙行为。
netsh advfirewall show allprofiles firewallpolicy

在这里插入图片描述
在这里插入图片描述

# 显示日志记录设置。
netsh advfirewall show allprofiles logging

在这里插入图片描述

# 开启防火墙:
netsh advfirewall set allprofiles state on

在这里插入图片描述

#关闭防火墙:
netsh advfirewall set allprofiles state off

在这里插入图片描述

3.2 入站出站规则设置

  • 添加入站规则
# 允许
netsh advfirewall firewall add rule name=xiaomu1 dir=in action=allow protocol=tcp localport=5000

# 阻止
netsh advfirewall firewall add rule name=xiaomu1 dir=in action=block protocol=tcp localport=5000

在这里插入图片描述

  • 添加出站规则
# 允许
netsh advfirewall firewall add rule name=xiaomu1 dir=out action=allow protocol=tcp localport=5000

# 阻止
netsh advfirewall firewall add rule name=xiaomu1 dir=out action=block protocol=tcp localport=5000

在这里插入图片描述

  • 删除入站出站规则
# 删除入站允许
netsh advfirewall firewall delete rule name=test001 dir=in action=allow protocol=tcp localport=445

# 删除出站允许
netsh advfirewall firewall delete rule name=test001 dir=out action=allow protocol=tcp localport=445
  • bat批处理文件实现添加防火墙出入站规则:
@echo off

rem 以管理员权限执行命令
%1 mshta vbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c %~s0 ::","","runas",1)(window.close)&&exit
cd /d "%~dp0"

rem 设置指定端口变量和出入站规则名称
set INPUT_RULE_NAME=xiaomu_in
set OUT_RULE_NAME=xiaomu_out
set PORT=27700-27702,3316,5000-5010

rem 创建入站规则
echo Input Rule
netsh advfirewall firewall show rule name=%INPUT_RULE_NAME% >nul
rem 如果已经存在则先删除
if not ERRORLEVEL 1 (
    netsh advfirewall firewall delete rule name=%INPUT_RULE_NAME% >nul
) 
netsh advfirewall firewall add rule name=%INPUT_RULE_NAME% dir=in action=allow protocol=TCP localport=%PORT%
echo %INPUT_RULE_NAME% Create Successed!

rem 创建出站规则
echo Output Rule
netsh advfirewall firewall show rule name=%OUT_RULE_NAME% >nul
rem 如果已经存在则先删除
if not ERRORLEVEL 1 (
   netsh advfirewall firewall delete rule name=%OUT_RULE_NAME% >nul
) 
netsh advfirewall firewall add rule name=%OUT_RULE_NAME% dir=out action=allow protocol=TCP localport=%PORT%
echo %OUT_RULE_NAME% Create Successed!

echo Done!
pause

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

3.3 其他设置

  • 允许并阻止ping
    您可以使用netsh来控制给定系统如何响应ping请求以及是否响应。以下两个netsh命令显示了如何阻止然后打开Windows防火墙来ping请求:
netsh advfirewall firewall add rule name="All ICMP V4" dir=in action=block protocol=icmpv4
netsh advfirewall firewall add rule name="All ICMP V4" dir=in action=allow protocol=icmpv4
  • 启用程序
    另一个常见任务是为给定程序打开Windows防火墙。以下示例说明了如何添加使Windows Live Messenger通过Windows防火墙工作的规则:
netsh advfirewall firewall add rule name="Allow Messenger" dir=in action=allow program="C:\programfiles\messenger\msnmsgr.exe"
  • 启用远程管理
    另一个常见要求(尤其是在设置新系统时)是启用远程管理,以便Microsoft Management Console等工具可以连接到远程系统。要打开Windows防火墙进行远程管理,可以使用以下命令:
netsh advfirewall firewall set rule group="remote administration" new enable=yes
  • 启用远程桌面连接
    对设置的大多数服务器系统所做的第一件事就是启用远程桌面连接用于轻松的远程系统管理。以下命令显示如何使用netsh打开Windows防火墙进行远程桌面连接:
netsh advfirewall firewall set rule group="remote desktop" new enable=Yes
  • 导出和导入防火墙设置文件
    配置Windows防火墙后,最好导出设置,以便以后可以轻松地重新应用它们或将其导入另一个系统。
netsh advfirewall export "C:\temp\WFconfiguration.wfw"
netsh advfirewall import "C:\temp\WFconfiguration.wfw"
  • 关闭5900端口
netsh advfirewall firewall add rule name= “deny tcp 5900dir=in protocol=tcp localport=5900 action=block
  • 设置Ip禁止
# remoteip 允许的IP,多个IP用逗号分割
netsh advfirewall firewall add rule name="test" dir=in action=allow protocol=TCP localport=3389,135 remoteip=10.10.12.20,192.168.0.20

3.4 telnet检测端口

完成之后,可以用telnet测试端口是否开放。
打开命令行窗口,输入命令:telnet 127.0.0.1 5000,如果出现下图的界面就说明该端口已经开放。
在这里插入图片描述
如果telnet没有安装的话,请按照如下步骤操作。
使用win+R键打开运行程序,在输入框里输入:OptionalFeatures,点击确定。
在这里插入图片描述
勾选上Telnet客户端并点击确定,就会开始安装telnet客户端。
重新打开一个cmd窗口输入telnet命令,如下所示表明telnet客户端安装成功。
在这里插入图片描述

4、C++方式

在这里插入图片描述

4.1 注册表

#include <Windows.h>
 
int main(void)
{
    HKEY hkResult;
    TCHAR szValueName[MAX_PATH] = { 0 }, szData[1024] = { 0 };
    DWORD dwValueNameLen = MAX_PATH, dwDataLen = 1024;
    const TCHAR* lpSubKey = TEXT("SYSTEM\\ControlSet001\\Services\\SharedAccess\\Defaults\\FirewallPolicy\\FirewallRules");
    if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, lpSubKey, 0, KEY_READ, &hkResult))
    {
        for (DWORD i = 0;; i++)
        {
            if (ERROR_NO_MORE_ITEMS == RegEnumValue(hkResult, i, szValueName, &dwValueNameLen, NULL, NULL, (BYTE*)szData, &dwDataLen))
            {
                break;
            }
            dwValueNameLen = MAX_PATH;
            dwDataLen = 1024;
        }
    }
}

4.2 COM(Windows XP)

/*
	Copyright (c) Microsoft Corporation

	SYNOPSIS

		Sample code for the Windows Firewall COM interface.
*/

#include <windows.h>
#include <crtdbg.h>
#include <netfw.h>
#include <objbase.h>
#include <oleauto.h>
#include <stdio.h>

#pragma comment( lib, "ole32.lib" )
#pragma comment( lib, "oleaut32.lib" )


HRESULT WindowsFirewallInitialize(OUT INetFwProfile** fwProfile)
{
	HRESULT hr = S_OK;
	INetFwMgr* fwMgr = NULL;
	INetFwPolicy* fwPolicy = NULL;

	_ASSERT(fwProfile != NULL);

	*fwProfile = NULL;

	// Create an instance of the firewall settings manager.
	hr = CoCreateInstance(
		__uuidof(NetFwMgr),
		NULL,
		CLSCTX_INPROC_SERVER,
		__uuidof(INetFwMgr),
		(void**)&fwMgr
	);
	if (FAILED(hr))
	{
		printf("CoCreateInstance failed: 0x%08lx\n", hr);
		goto error;
	}

	// Retrieve the local firewall policy.
	hr = fwMgr->get_LocalPolicy(&fwPolicy);
	if (FAILED(hr))
	{
		printf("get_LocalPolicy failed: 0x%08lx\n", hr);
		goto error;
	}

	// Retrieve the firewall profile currently in effect.
	hr = fwPolicy->get_CurrentProfile(fwProfile);
	if (FAILED(hr))
	{
		printf("get_CurrentProfile failed: 0x%08lx\n", hr);
		goto error;
	}

error:

	// Release the local firewall policy.
	if (fwPolicy != NULL)
	{
		fwPolicy->Release();
	}

	// Release the firewall settings manager.
	if (fwMgr != NULL)
	{
		fwMgr->Release();
	}

	return hr;
}


void WindowsFirewallCleanup(IN INetFwProfile* fwProfile)
{
	// Release the firewall profile.
	if (fwProfile != NULL)
	{
		fwProfile->Release();
	}
}


HRESULT WindowsFirewallIsOn(IN INetFwProfile* fwProfile, OUT BOOL* fwOn)
{
	HRESULT hr = S_OK;
	VARIANT_BOOL fwEnabled;

	_ASSERT(fwProfile != NULL);
	_ASSERT(fwOn != NULL);

	*fwOn = FALSE;

	// Get the current state of the firewall.
	hr = fwProfile->get_FirewallEnabled(&fwEnabled);
	if (FAILED(hr))
	{
		printf("get_FirewallEnabled failed: 0x%08lx\n", hr);
		goto error;
	}

	// Check to see if the firewall is on.
	if (fwEnabled != VARIANT_FALSE)
	{
		*fwOn = TRUE;
		printf("The firewall is on.\n");
	}
	else
	{
		printf("The firewall is off.\n");
	}

error:

	return hr;
}


HRESULT WindowsFirewallTurnOn(IN INetFwProfile* fwProfile)
{
	HRESULT hr = S_OK;
	BOOL fwOn;

	_ASSERT(fwProfile != NULL);

	// Check to see if the firewall is off.
	hr = WindowsFirewallIsOn(fwProfile, &fwOn);
	if (FAILED(hr))
	{
		printf("WindowsFirewallIsOn failed: 0x%08lx\n", hr);
		goto error;
	}

	// If it is, turn it on.
	if (!fwOn)
	{
		// Turn the firewall on.
		hr = fwProfile->put_FirewallEnabled(VARIANT_TRUE);
		if (FAILED(hr))
		{
			printf("put_FirewallEnabled failed: 0x%08lx\n", hr);
			goto error;
		}

		printf("The firewall is now on.\n");
	}

error:

	return hr;
}


HRESULT WindowsFirewallTurnOff(IN INetFwProfile* fwProfile)
{
	HRESULT hr = S_OK;
	BOOL fwOn;

	_ASSERT(fwProfile != NULL);

	// Check to see if the firewall is on.
	hr = WindowsFirewallIsOn(fwProfile, &fwOn);
	if (FAILED(hr))
	{
		printf("WindowsFirewallIsOn failed: 0x%08lx\n", hr);
		goto error;
	}

	// If it is, turn it off.
	if (fwOn)
	{
		// Turn the firewall off.
		hr = fwProfile->put_FirewallEnabled(VARIANT_FALSE);
		if (FAILED(hr))
		{
			printf("put_FirewallEnabled failed: 0x%08lx\n", hr);
			goto error;
		}

		printf("The firewall is now off.\n");
	}

error:

	return hr;
}


HRESULT WindowsFirewallAppIsEnabled(
	IN INetFwProfile* fwProfile,
	IN const wchar_t* fwProcessImageFileName,
	OUT BOOL* fwAppEnabled
)
{
	HRESULT hr = S_OK;
	BSTR fwBstrProcessImageFileName = NULL;
	VARIANT_BOOL fwEnabled;
	INetFwAuthorizedApplication* fwApp = NULL;
	INetFwAuthorizedApplications* fwApps = NULL;

	_ASSERT(fwProfile != NULL);
	_ASSERT(fwProcessImageFileName != NULL);
	_ASSERT(fwAppEnabled != NULL);

	*fwAppEnabled = FALSE;

	// Retrieve the authorized application collection.
	hr = fwProfile->get_AuthorizedApplications(&fwApps);
	if (FAILED(hr))
	{
		printf("get_AuthorizedApplications failed: 0x%08lx\n", hr);
		goto error;
	}

	// Allocate a BSTR for the process image file name.
	fwBstrProcessImageFileName = SysAllocString(fwProcessImageFileName);
	if (fwBstrProcessImageFileName == NULL)
	{
		hr = E_OUTOFMEMORY;
		printf("SysAllocString failed: 0x%08lx\n", hr);
		goto error;
	}

	// Attempt to retrieve the authorized application.
	hr = fwApps->Item(fwBstrProcessImageFileName, &fwApp);
	if (SUCCEEDED(hr))
	{
		// Find out if the authorized application is enabled.
		hr = fwApp->get_Enabled(&fwEnabled);
		if (FAILED(hr))
		{
			printf("get_Enabled failed: 0x%08lx\n", hr);
			goto error;
		}

		if (fwEnabled != VARIANT_FALSE)
		{
			// The authorized application is enabled.
			*fwAppEnabled = TRUE;

			printf(
				"Authorized application %lS is enabled in the firewall.\n",
				fwProcessImageFileName
			);
		}
		else
		{
			printf(
				"Authorized application %lS is disabled in the firewall.\n",
				fwProcessImageFileName
			);
		}
	}
	else
	{
		// The authorized application was not in the collection.
		hr = S_OK;

		printf(
			"Authorized application %lS is disabled in the firewall.\n",
			fwProcessImageFileName
		);
	}

error:

	// Free the BSTR.
	SysFreeString(fwBstrProcessImageFileName);

	// Release the authorized application instance.
	if (fwApp != NULL)
	{
		fwApp->Release();
	}

	// Release the authorized application collection.
	if (fwApps != NULL)
	{
		fwApps->Release();
	}

	return hr;
}


HRESULT WindowsFirewallAddApp(
	IN INetFwProfile* fwProfile,
	IN const wchar_t* fwProcessImageFileName,
	IN const wchar_t* fwName
)
{
	HRESULT hr = S_OK;
	BOOL fwAppEnabled;
	BSTR fwBstrName = NULL;
	BSTR fwBstrProcessImageFileName = NULL;
	INetFwAuthorizedApplication* fwApp = NULL;
	INetFwAuthorizedApplications* fwApps = NULL;

	_ASSERT(fwProfile != NULL);
	_ASSERT(fwProcessImageFileName != NULL);
	_ASSERT(fwName != NULL);

	// First check to see if the application is already authorized.
	hr = WindowsFirewallAppIsEnabled(
		fwProfile,
		fwProcessImageFileName,
		&fwAppEnabled
	);
	if (FAILED(hr))
	{
		printf("WindowsFirewallAppIsEnabled failed: 0x%08lx\n", hr);
		goto error;
	}

	// Only add the application if it isn't already authorized.
	if (!fwAppEnabled)
	{
		// Retrieve the authorized application collection.
		hr = fwProfile->get_AuthorizedApplications(&fwApps);
		if (FAILED(hr))
		{
			printf("get_AuthorizedApplications failed: 0x%08lx\n", hr);
			goto error;
		}

		// Create an instance of an authorized application.
		hr = CoCreateInstance(
			__uuidof(NetFwAuthorizedApplication),
			NULL,
			CLSCTX_INPROC_SERVER,
			__uuidof(INetFwAuthorizedApplication),
			(void**)&fwApp
		);
		if (FAILED(hr))
		{
			printf("CoCreateInstance failed: 0x%08lx\n", hr);
			goto error;
		}

		// Allocate a BSTR for the process image file name.
		fwBstrProcessImageFileName = SysAllocString(fwProcessImageFileName);
		if (fwBstrProcessImageFileName == NULL)
		{
			hr = E_OUTOFMEMORY;
			printf("SysAllocString failed: 0x%08lx\n", hr);
			goto error;
		}

		// Set the process image file name.
		hr = fwApp->put_ProcessImageFileName(fwBstrProcessImageFileName);
		if (FAILED(hr))
		{
			printf("put_ProcessImageFileName failed: 0x%08lx\n", hr);
			goto error;
		}

		// Allocate a BSTR for the application friendly name.
		fwBstrName = SysAllocString(fwName);
		if (SysStringLen(fwBstrName) == 0)
		{
			hr = E_OUTOFMEMORY;
			printf("SysAllocString failed: 0x%08lx\n", hr);
			goto error;
		}

		// Set the application friendly name.
		hr = fwApp->put_Name(fwBstrName);
		if (FAILED(hr))
		{
			printf("put_Name failed: 0x%08lx\n", hr);
			goto error;
		}

		// Add the application to the collection.
		hr = fwApps->Add(fwApp);
		if (FAILED(hr))
		{
			printf("Add failed: 0x%08lx\n", hr);
			goto error;
		}

		printf(
			"Authorized application %lS is now enabled in the firewall.\n",
			fwProcessImageFileName
		);
	}

error:

	// Free the BSTRs.
	SysFreeString(fwBstrName);
	SysFreeString(fwBstrProcessImageFileName);

	// Release the authorized application instance.
	if (fwApp != NULL)
	{
		fwApp->Release();
	}

	// Release the authorized application collection.
	if (fwApps != NULL)
	{
		fwApps->Release();
	}

	return hr;
}


HRESULT WindowsFirewallPortIsEnabled(
	IN INetFwProfile* fwProfile,
	IN LONG portNumber,
	IN NET_FW_IP_PROTOCOL ipProtocol,
	OUT BOOL* fwPortEnabled
)
{
	HRESULT hr = S_OK;
	VARIANT_BOOL fwEnabled;
	INetFwOpenPort* fwOpenPort = NULL;
	INetFwOpenPorts* fwOpenPorts = NULL;

	_ASSERT(fwProfile != NULL);
	_ASSERT(fwPortEnabled != NULL);

	*fwPortEnabled = FALSE;

	// Retrieve the globally open ports collection.
	hr = fwProfile->get_GloballyOpenPorts(&fwOpenPorts);
	if (FAILED(hr))
	{
		printf("get_GloballyOpenPorts failed: 0x%08lx\n", hr);
		goto error;
	}

	// Attempt to retrieve the globally open port.
	hr = fwOpenPorts->Item(portNumber, ipProtocol, &fwOpenPort);
	if (SUCCEEDED(hr))
	{
		// Find out if the globally open port is enabled.
		hr = fwOpenPort->get_Enabled(&fwEnabled);
		if (FAILED(hr))
		{
			printf("get_Enabled failed: 0x%08lx\n", hr);
			goto error;
		}

		if (fwEnabled != VARIANT_FALSE)
		{
			// The globally open port is enabled.
			*fwPortEnabled = TRUE;

			printf("Port %ld is open in the firewall.\n", portNumber);
		}
		else
		{
			printf("Port %ld is not open in the firewall.\n", portNumber);
		}
	}
	else
	{
		// The globally open port was not in the collection.
		hr = S_OK;

		printf("Port %ld is not open in the firewall.\n", portNumber);
	}

error:

	// Release the globally open port.
	if (fwOpenPort != NULL)
	{
		fwOpenPort->Release();
	}

	// Release the globally open ports collection.
	if (fwOpenPorts != NULL)
	{
		fwOpenPorts->Release();
	}

	return hr;
}


HRESULT WindowsFirewallPortAdd(
	IN INetFwProfile* fwProfile,
	IN LONG portNumber,
	IN NET_FW_IP_PROTOCOL ipProtocol,
	IN const wchar_t* name
)
{
	HRESULT hr = S_OK;
	BOOL fwPortEnabled;
	BSTR fwBstrName = NULL;
	INetFwOpenPort* fwOpenPort = NULL;
	INetFwOpenPorts* fwOpenPorts = NULL;

	_ASSERT(fwProfile != NULL);
	_ASSERT(name != NULL);

	// First check to see if the port is already added.
	hr = WindowsFirewallPortIsEnabled(
		fwProfile,
		portNumber,
		ipProtocol,
		&fwPortEnabled
	);
	if (FAILED(hr))
	{
		printf("WindowsFirewallPortIsEnabled failed: 0x%08lx\n", hr);
		goto error;
	}

	// Only add the port if it isn't already added.
	if (!fwPortEnabled)
	{
		// Retrieve the collection of globally open ports.
		hr = fwProfile->get_GloballyOpenPorts(&fwOpenPorts);
		if (FAILED(hr))
		{
			printf("get_GloballyOpenPorts failed: 0x%08lx\n", hr);
			goto error;
		}

		// Create an instance of an open port.
		hr = CoCreateInstance(
			__uuidof(NetFwOpenPort),
			NULL,
			CLSCTX_INPROC_SERVER,
			__uuidof(INetFwOpenPort),
			(void**)&fwOpenPort
		);
		if (FAILED(hr))
		{
			printf("CoCreateInstance failed: 0x%08lx\n", hr);
			goto error;
		}

		// Set the port number.
		hr = fwOpenPort->put_Port(portNumber);
		if (FAILED(hr))
		{
			printf("put_Port failed: 0x%08lx\n", hr);
			goto error;
		}

		// Set the IP protocol.
		hr = fwOpenPort->put_Protocol(ipProtocol);
		if (FAILED(hr))
		{
			printf("put_Protocol failed: 0x%08lx\n", hr);
			goto error;
		}

		// Allocate a BSTR for the friendly name of the port.
		fwBstrName = SysAllocString(name);
		if (SysStringLen(fwBstrName) == 0)
		{
			hr = E_OUTOFMEMORY;
			printf("SysAllocString failed: 0x%08lx\n", hr);
			goto error;
		}

		// Set the friendly name of the port.
		hr = fwOpenPort->put_Name(fwBstrName);
		if (FAILED(hr))
		{
			printf("put_Name failed: 0x%08lx\n", hr);
			goto error;
		}

		// Opens the port and adds it to the collection.
		hr = fwOpenPorts->Add(fwOpenPort);
		if (FAILED(hr))
		{
			printf("Add failed: 0x%08lx\n", hr);
			goto error;
		}

		printf("Port %ld is now open in the firewall.\n", portNumber);
	}

error:

	// Free the BSTR.
	SysFreeString(fwBstrName);

	// Release the open port instance.
	if (fwOpenPort != NULL)
	{
		fwOpenPort->Release();
	}

	// Release the globally open ports collection.
	if (fwOpenPorts != NULL)
	{
		fwOpenPorts->Release();
	}

	return hr;
}


int __cdecl wmain(int argc, wchar_t* argv[])
{
	HRESULT hr = S_OK;
	HRESULT comInit = E_FAIL;
	INetFwProfile* fwProfile = NULL;

	// Initialize COM.
	comInit = CoInitializeEx(
		0,
		COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE
	);

	// Ignore RPC_E_CHANGED_MODE; this just means that COM has already been
	// initialized with a different mode. Since we don't care what the mode is,
	// we'll just use the existing mode.
	if (comInit != RPC_E_CHANGED_MODE)
	{
		hr = comInit;
		if (FAILED(hr))
		{
			printf("CoInitializeEx failed: 0x%08lx\n", hr);
			goto error;
		}
	}

	// Retrieve the firewall profile currently in effect.
	hr = WindowsFirewallInitialize(&fwProfile);
	if (FAILED(hr))
	{
		printf("WindowsFirewallInitialize failed: 0x%08lx\n", hr);
		goto error;
	}

	// Turn off the firewall.
	/*hr = WindowsFirewallTurnOff(fwProfile);
	if (FAILED(hr))
	{
		printf("WindowsFirewallTurnOff failed: 0x%08lx\n", hr);
		goto error;
	}*/

	// Turn on the firewall.
	hr = WindowsFirewallTurnOn(fwProfile);
	if (FAILED(hr))
	{
		printf("WindowsFirewallTurnOn failed: 0x%08lx\n", hr);
		goto error;
	}

	// Add Windows Messenger to the authorized application collection.
	hr = WindowsFirewallAddApp(
		fwProfile,
		//L"%ProgramFiles%\\Messenger\\msmsgs.exe",
		L"C:\\program files\\google\\chrome\\application\\chrome.exe",
		L"XiaoMu_add_exe"
	);
	if (FAILED(hr))
	{
		printf("WindowsFirewallAddApp failed: 0x%08lx\n", hr);
		goto error;
	}

	// Add TCP::80 to list of globally open ports.
	hr = WindowsFirewallPortAdd(fwProfile, 12345, NET_FW_IP_PROTOCOL_TCP, L"XiaoMu_add_tcp");
	if (FAILED(hr))
	{
		printf("WindowsFirewallPortAdd failed: 0x%08lx\n", hr);
		goto error;
	}

error:

	// Release the firewall profile.
	WindowsFirewallCleanup(fwProfile);

	// Uninitialize COM.
	if (SUCCEEDED(comInit))
	{
		CoUninitialize();
	}

	return 0;
}

在这里插入图片描述

4.3 COM(Windows Vista and later)

高级安全 Windows 防火墙和此处记录的相关防火墙技术使开发人员能够共享 Internet 连接、使用防火墙保护连接并提供网络地址转换 (NAT)。

微软已经发布了几个版本的防火墙产品,每个版本都建立在以前的技术之上。当前版本“高级安全 Windows 防火墙”允许创建极其具体的防火墙规则。

  • 具体技术如下(此处从最新到最旧列出):

    • 高级安全 Windows 防火墙是最新版本。它最初与Windows Vista一起发布。
    • Windows Firewall 最初是作为 Windows XP Service Pack 2 (SP2) 的一个组件发布的。
    • IPv6 Internet Connection Firewall 作为 Windows XP 高级网络包的组件发布。它在后续版本的 Windows 中不可用。
    • Internet 连接共享和 Internet 连接防火墙最初是在 Windows XP 中发布的,在 Windows Vista 中受支持。它可能在后续版本的 Windows 中被更改或不可用。
  • 添加防火墙规则
    This C++ file includes sample code that adds a LAN rule to the
    currently active profiles using the Microsoft Windows Firewall
    APIs.

#include <windows.h>
#include <stdio.h>
#include <netfw.h>

#pragma comment( lib, "ole32.lib" )
#pragma comment( lib, "oleaut32.lib" )


// Forward declarations
HRESULT     WFCOMInitialize(INetFwPolicy2** ppNetFwPolicy2);


// Instantiate INetFwPolicy2
HRESULT WFCOMInitialize(INetFwPolicy2** ppNetFwPolicy2)
{
	HRESULT hr = S_OK;

	hr = CoCreateInstance(
		__uuidof(NetFwPolicy2),
		NULL,
		CLSCTX_INPROC_SERVER,
		__uuidof(INetFwPolicy2),
		(void**)ppNetFwPolicy2);

	if (FAILED(hr))
	{
		printf("CoCreateInstance for INetFwPolicy2 failed: 0x%08lx\n", hr);
		goto Cleanup;
	}

Cleanup:
	return hr;
}

int main(int argc, TCHAR* argv[])
{
	HRESULT hrComInit = S_OK;
	HRESULT hr = S_OK;

	INetFwPolicy2 *pNetFwPolicy2 = NULL;
	INetFwRules *pFwRules = NULL;
	INetFwRule *pFwRule = NULL;

	long CurrentProfilesBitMask = 0;

	BSTR bstrRuleName = SysAllocString(L"XiaoMu_0129");
	BSTR bstrRuleDescription = SysAllocString(L"Allow incoming network traffic over port 2400 coming from LAN interface type");
	BSTR bstrRuleGroup = SysAllocString(L"Sample Rule Group");
	BSTR bstrRuleLPorts = SysAllocString(L"2400-2450");
	BSTR bstrRuleInterfaceType = SysAllocString(L"LAN");

	// Initialize COM.
	hrComInit = CoInitializeEx(
		0,
		COINIT_APARTMENTTHREADED
	);

	// Ignore RPC_E_CHANGED_MODE; this just means that COM has already been
	// initialized with a different mode. Since we don't care what the mode is,
	// we'll just use the existing mode.
	if (hrComInit != RPC_E_CHANGED_MODE)
	{
		if (FAILED(hrComInit))
		{
			printf("CoInitializeEx failed: 0x%08lx\n", hrComInit);
			goto Cleanup;
		}
	}

	// Retrieve INetFwPolicy2
	hr = WFCOMInitialize(&pNetFwPolicy2);
	if (FAILED(hr))
	{
		goto Cleanup;
	}

	// Retrieve INetFwRules
	hr = pNetFwPolicy2->get_Rules(&pFwRules);
	if (FAILED(hr))
	{
		printf("get_Rules failed: 0x%08lx\n", hr);
		goto Cleanup;
	}

	// Retrieve Current Profiles bitmask
	hr = pNetFwPolicy2->get_CurrentProfileTypes(&CurrentProfilesBitMask);
	if (FAILED(hr))
	{
		printf("get_CurrentProfileTypes failed: 0x%08lx\n", hr);
		goto Cleanup;
	}

	// When possible we avoid adding firewall rules to the Public profile.
	// If Public is currently active and it is not the only active profile, we remove it from the bitmask
	if ((CurrentProfilesBitMask & NET_FW_PROFILE2_PUBLIC) &&
		(CurrentProfilesBitMask != NET_FW_PROFILE2_PUBLIC))
	{
		CurrentProfilesBitMask ^= NET_FW_PROFILE2_PUBLIC;
	}

	// Create a new Firewall Rule object.
	hr = CoCreateInstance(
		__uuidof(NetFwRule),
		NULL,
		CLSCTX_INPROC_SERVER,
		__uuidof(INetFwRule),
		(void**)&pFwRule);
	if (FAILED(hr))
	{
		printf("CoCreateInstance for Firewall Rule failed: 0x%08lx\n", hr);
		goto Cleanup;
	}

	// Populate the Firewall Rule object
	pFwRule->put_Name(bstrRuleName);
	pFwRule->put_Description(bstrRuleDescription);
	pFwRule->put_Protocol(NET_FW_IP_PROTOCOL_TCP);
	pFwRule->put_LocalPorts(bstrRuleLPorts);
	pFwRule->put_Grouping(bstrRuleGroup);
	pFwRule->put_InterfaceTypes(bstrRuleInterfaceType);
	pFwRule->put_Profiles(CurrentProfilesBitMask);
	pFwRule->put_Action(NET_FW_ACTION_ALLOW);
	pFwRule->put_Enabled(VARIANT_TRUE);

	// Add the Firewall Rule
	hr = pFwRules->Add(pFwRule);
	if (FAILED(hr))
	{
		printf("Firewall Rule Add failed: 0x%08lx\n", hr);
		goto Cleanup;
	}

Cleanup:

	// Free BSTR's
	SysFreeString(bstrRuleName);
	SysFreeString(bstrRuleDescription);
	SysFreeString(bstrRuleGroup);
	SysFreeString(bstrRuleLPorts);
	SysFreeString(bstrRuleInterfaceType);

	// Release the INetFwRule object
	if (pFwRule != NULL)
	{
		pFwRule->Release();
	}

	// Release the INetFwRules object
	if (pFwRules != NULL)
	{
		pFwRules->Release();
	}

	// Release the INetFwPolicy2 object
	if (pNetFwPolicy2 != NULL)
	{
		pNetFwPolicy2->Release();
	}

	// Uninitialize COM.
	if (SUCCEEDED(hrComInit))
	{
		CoUninitialize();
	}

	printf("OK.\n");
	getchar();
	return 0;

}

在这里插入图片描述

  • 遍历所有的防火墙规则
/********************************************************************++
Copyright (C) Microsoft. All Rights Reserved.

Abstract:
    This C++ file includes sample code for enumerating Windows Firewall
    rules using the Microsoft Windows Firewall APIs.

********************************************************************/

#include <windows.h>
#include <stdio.h>
#include <comutil.h>
#include <atlcomcli.h>
#include <netfw.h>

#pragma comment( lib, "ole32.lib" )
#pragma comment( lib, "oleaut32.lib" )

#define NET_FW_IP_PROTOCOL_TCP_NAME L"TCP"
#define NET_FW_IP_PROTOCOL_UDP_NAME L"UDP"

#define NET_FW_RULE_DIR_IN_NAME L"In"
#define NET_FW_RULE_DIR_OUT_NAME L"Out"

#define NET_FW_RULE_ACTION_BLOCK_NAME L"Block"
#define NET_FW_RULE_ACTION_ALLOW_NAME L"Allow"

#define NET_FW_RULE_ENABLE_IN_NAME L"TRUE"
#define NET_FW_RULE_DISABLE_IN_NAME L"FALSE"


// Forward declarations
void        DumpFWRulesInCollection(INetFwRule* FwRule);
HRESULT     WFCOMInitialize(INetFwPolicy2** ppNetFwPolicy2);


int __cdecl main()
{
    HRESULT hrComInit = S_OK;
    HRESULT hr = S_OK;

    ULONG cFetched = 0; 
    CComVariant var;

    IUnknown *pEnumerator;
    IEnumVARIANT* pVariant = NULL;

    INetFwPolicy2 *pNetFwPolicy2 = NULL;
    INetFwRules *pFwRules = NULL;
    INetFwRule *pFwRule = NULL;

    long fwRuleCount;

    // Initialize COM.
    hrComInit = CoInitializeEx(
                    0,
                    COINIT_APARTMENTTHREADED
                    );

    // Ignore RPC_E_CHANGED_MODE; this just means that COM has already been
    // initialized with a different mode. Since we don't care what the mode is,
    // we'll just use the existing mode.
    if (hrComInit != RPC_E_CHANGED_MODE)
    {
        if (FAILED(hrComInit))
        {
            wprintf(L"CoInitializeEx failed: 0x%08lx\n", hrComInit);
            goto Cleanup;
        }
    }

    // Retrieve INetFwPolicy2
    hr = WFCOMInitialize(&amp;pNetFwPolicy2);
    if (FAILED(hr))
    {
        goto Cleanup;
    }

    // Retrieve INetFwRules
    hr = pNetFwPolicy2->get_Rules(&amp;pFwRules);
    if (FAILED(hr))
    {
        wprintf(L"get_Rules failed: 0x%08lx\n", hr);
        goto Cleanup;
    }

    // Obtain the number of Firewall rules
    hr = pFwRules->get_Count(&amp;fwRuleCount);
    if (FAILED(hr))
    {
        wprintf(L"get_Count failed: 0x%08lx\n", hr);
        goto Cleanup;
    }
    
    wprintf(L"The number of rules in the Windows Firewall are %d\n", fwRuleCount);

    // Iterate through all of the rules in pFwRules
    pFwRules->get__NewEnum(&amp;pEnumerator);

    if(pEnumerator)
    {
        hr = pEnumerator->QueryInterface(__uuidof(IEnumVARIANT), (void **) &amp;pVariant);
    }

    while(SUCCEEDED(hr) &amp;&amp; hr != S_FALSE)
    {
        var.Clear();
        hr = pVariant->Next(1, &amp;var, &amp;cFetched);

        if (S_FALSE != hr)
        {
            if (SUCCEEDED(hr))
            {
                hr = var.ChangeType(VT_DISPATCH);
            }
            if (SUCCEEDED(hr))
            {
                hr = (V_DISPATCH(&amp;var))->QueryInterface(__uuidof(INetFwRule), reinterpret_cast<void**>(&amp;pFwRule));
            }

            if (SUCCEEDED(hr))
            {
                // Output the properties of this rule
                DumpFWRulesInCollection(pFwRule);
            }
        }
    }
 
Cleanup:

    // Release pFwRule
    if (pFwRule != NULL)
    {
        pFwRule->Release();
    }

    // Release INetFwPolicy2
    if (pNetFwPolicy2 != NULL)
    {
        pNetFwPolicy2->Release();
    }

    // Uninitialize COM.
    if (SUCCEEDED(hrComInit))
    {
        CoUninitialize();
    }
   
    return 0;
}


// Output properties of a Firewall rule 
void DumpFWRulesInCollection(INetFwRule* FwRule)
{
    variant_t InterfaceArray;
    variant_t InterfaceString;  

    VARIANT_BOOL bEnabled;
    BSTR bstrVal;

    long lVal = 0;
    long lProfileBitmask = 0;

    NET_FW_RULE_DIRECTION fwDirection;
    NET_FW_ACTION fwAction;

    struct ProfileMapElement 
    {
        NET_FW_PROFILE_TYPE2 Id;
        LPCWSTR Name;
    };

    ProfileMapElement ProfileMap[3];
    ProfileMap[0].Id = NET_FW_PROFILE2_DOMAIN;
    ProfileMap[0].Name = L"Domain";
    ProfileMap[1].Id = NET_FW_PROFILE2_PRIVATE;
    ProfileMap[1].Name = L"Private";
    ProfileMap[2].Id = NET_FW_PROFILE2_PUBLIC;
    ProfileMap[2].Name = L"Public";

    wprintf(L"---------------------------------------------\n");

    if (SUCCEEDED(FwRule->get_Name(&amp;bstrVal)))
    {
        wprintf(L"Name:             %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_Description(&amp;bstrVal)))
    {
        wprintf(L"Description:      %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_ApplicationName(&amp;bstrVal)))
    {
        wprintf(L"Application Name: %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_ServiceName(&amp;bstrVal)))
    {
        wprintf(L"Service Name:     %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_Protocol(&amp;lVal)))
    {
        switch(lVal)
        {
            case NET_FW_IP_PROTOCOL_TCP: 

                wprintf(L"IP Protocol:      %s\n", NET_FW_IP_PROTOCOL_TCP_NAME);
                break;

            case NET_FW_IP_PROTOCOL_UDP: 

                wprintf(L"IP Protocol:      %s\n", NET_FW_IP_PROTOCOL_UDP_NAME);
                break;

            default:

                break;
        }

        if(lVal != NET_FW_IP_VERSION_V4 &amp;&amp; lVal != NET_FW_IP_VERSION_V6)
        {
            if (SUCCEEDED(FwRule->get_LocalPorts(&amp;bstrVal)))
            {
                wprintf(L"Local Ports:      %s\n", bstrVal);
            }

            if (SUCCEEDED(FwRule->get_RemotePorts(&amp;bstrVal)))
            {
                wprintf(L"Remote Ports:      %s\n", bstrVal);
            }
        }
        else
        {
            if (SUCCEEDED(FwRule->get_IcmpTypesAndCodes(&amp;bstrVal)))
            {
                wprintf(L"ICMP TypeCode:      %s\n", bstrVal);
            }
        }
    }

    if (SUCCEEDED(FwRule->get_LocalAddresses(&amp;bstrVal)))
    {
        wprintf(L"LocalAddresses:   %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_RemoteAddresses(&amp;bstrVal)))
    {
        wprintf(L"RemoteAddresses:  %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_Profiles(&amp;lProfileBitmask)))
    {
        // The returned bitmask can have more than 1 bit set if multiple profiles 
        //   are active or current at the same time

        for (int i=0; i<3; i++)
        {
            if ( lProfileBitmask & ProfileMap[i].Id  )
            {
                wprintf(L"Profile:  %s\n", ProfileMap[i].Name);
            }
        }
    }

    if (SUCCEEDED(FwRule->get_Direction(&amp;fwDirection)))
    {
        switch(fwDirection)
        {
            case NET_FW_RULE_DIR_IN:

                wprintf(L"Direction:        %s\n", NET_FW_RULE_DIR_IN_NAME);
                break;

            case NET_FW_RULE_DIR_OUT:

                wprintf(L"Direction:        %s\n", NET_FW_RULE_DIR_OUT_NAME);
                break;

            default:

                break;
        }
    }

    if (SUCCEEDED(FwRule->get_Action(&amp;fwAction)))
    {
        switch(fwAction)
        {
            case NET_FW_ACTION_BLOCK:

                wprintf(L"Action:           %s\n", NET_FW_RULE_ACTION_BLOCK_NAME);
                break;

            case NET_FW_ACTION_ALLOW:

                wprintf(L"Action:           %s\n", NET_FW_RULE_ACTION_ALLOW_NAME);
                break;

            default:

                break;
        }
    }

    if (SUCCEEDED(FwRule->get_Interfaces(&amp;InterfaceArray)))
    {
        if(InterfaceArray.vt != VT_EMPTY)
        {
            SAFEARRAY    *pSa = NULL;

            pSa = InterfaceArray.parray;

            for(long index= pSa->rgsabound->lLbound; index < (long)pSa->rgsabound->cElements; index++)
            {
                SafeArrayGetElement(pSa, &amp;index, &amp;InterfaceString);
                wprintf(L"Interfaces:       %s\n", (BSTR)InterfaceString.bstrVal);
            }
        }
    }

    if (SUCCEEDED(FwRule->get_InterfaceTypes(&amp;bstrVal)))
    {
        wprintf(L"Interface Types:  %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_Enabled(&amp;bEnabled)))
    {
        if (bEnabled)
        {
            wprintf(L"Enabled:          %s\n", NET_FW_RULE_ENABLE_IN_NAME);
        }
        else
        {
            wprintf(L"Enabled:          %s\n", NET_FW_RULE_DISABLE_IN_NAME);
        }
    }

    if (SUCCEEDED(FwRule->get_Grouping(&amp;bstrVal)))
    {
        wprintf(L"Grouping:         %s\n", bstrVal);
    }

    if (SUCCEEDED(FwRule->get_EdgeTraversal(&amp;bEnabled)))
    {
        if (bEnabled)
        {
            wprintf(L"Edge Traversal:   %s\n", NET_FW_RULE_ENABLE_IN_NAME);
        }
        else
        {
            wprintf(L"Edge Traversal:   %s\n", NET_FW_RULE_DISABLE_IN_NAME);
        }
    }
}


// Instantiate INetFwPolicy2
HRESULT WFCOMInitialize(INetFwPolicy2** ppNetFwPolicy2)
{
    HRESULT hr = S_OK;

    hr = CoCreateInstance(
        __uuidof(NetFwPolicy2), 
        NULL, 
        CLSCTX_INPROC_SERVER, 
        __uuidof(INetFwPolicy2), 
        (void**)ppNetFwPolicy2);

    if (FAILED(hr))
    {
        wprintf(L"CoCreateInstance for INetFwPolicy2 failed: 0x%08lx\n", hr);
        goto Cleanup;        
    }

Cleanup:
    return hr;
}

5、VB方式

在这里插入图片描述

'  This VBScript file includes sample code that enumerates
'  Windows Firewall rules using the Microsoft Windows Firewall APIs.


Option Explicit

Dim CurrentProfiles
Dim InterfaceArray
Dim LowerBound
Dim UpperBound
Dim iterate
Dim rule

' Profile Type
Const NET_FW_PROFILE2_DOMAIN = 1
Const NET_FW_PROFILE2_PRIVATE = 2
Const NET_FW_PROFILE2_PUBLIC = 4

' Protocol
Const NET_FW_IP_PROTOCOL_TCP = 6
Const NET_FW_IP_PROTOCOL_UDP = 17
Const NET_FW_IP_PROTOCOL_ICMPv4 = 1
Const NET_FW_IP_PROTOCOL_ICMPv6 = 58

' Direction
Const NET_FW_RULE_DIR_IN = 1
Const NET_FW_RULE_DIR_OUT = 2

' Action
Const NET_FW_ACTION_BLOCK = 0
Const NET_FW_ACTION_ALLOW = 1


' Create the FwPolicy2 object.
Dim fwPolicy2
Set fwPolicy2 = CreateObject("HNetCfg.FwPolicy2")

CurrentProfiles = fwPolicy2.CurrentProfileTypes

'// The returned 'CurrentProfiles' bitmask can have more than 1 bit set if multiple profiles 
'//   are active or current at the same time

if ( CurrentProfiles AND NET_FW_PROFILE2_DOMAIN ) then
   WScript.Echo("Domain Firewall Profile is active")
end if

if ( CurrentProfiles AND NET_FW_PROFILE2_PRIVATE ) then
   WScript.Echo("Private Firewall Profile is active")
end if

if ( CurrentProfiles AND NET_FW_PROFILE2_PUBLIC ) then
   WScript.Echo("Public Firewall Profile is active")
end if

' Get the Rules object
Dim RulesObject
Set RulesObject = fwPolicy2.Rules

' Print all the rules in currently active firewall profiles.
WScript.Echo("Rules:")

For Each rule In Rulesobject
    if rule.Profiles And CurrentProfiles then
        WScript.Echo("  Rule Name:          " & rule.Name)
        WScript.Echo("   ----------------------------------------------")
        WScript.Echo("  Description:        " & rule.Description)
        WScript.Echo("  Application Name:   " & rule.ApplicationName)
        WScript.Echo("  Service Name:       " & rule.ServiceName)
        Select Case rule.Protocol
            Case NET_FW_IP_PROTOCOL_TCP    WScript.Echo("  IP Protocol:        TCP.")
            Case NET_FW_IP_PROTOCOL_UDP    WScript.Echo("  IP Protocol:        UDP.")
            Case NET_FW_IP_PROTOCOL_ICMPv4 WScript.Echo("  IP Protocol:        UDP.")
            Case NET_FW_IP_PROTOCOL_ICMPv6 WScript.Echo("  IP Protocol:        UDP.")
            Case Else                      WScript.Echo("  IP Protocol:        " & rule.Protocol)
        End Select
        if rule.Protocol = NET_FW_IP_PROTOCOL_TCP or rule.Protocol = NET_FW_IP_PROTOCOL_UDP then
            WScript.Echo("  Local Ports:        " & rule.LocalPorts)
            WScript.Echo("  Remote Ports:       " & rule.RemotePorts)
            WScript.Echo("  LocalAddresses:     " & rule.LocalAddresses)
            WScript.Echo("  RemoteAddresses:    " & rule.RemoteAddresses)
        end if
        if rule.Protocol = NET_FW_IP_PROTOCOL_ICMPv4 or rule.Protocol = NET_FW_IP_PROTOCOL_ICMPv6 then
            WScript.Echo("  ICMP Type and Code:    " & rule.IcmpTypesAndCodes)
        end if
        Select Case rule.Direction
            Case NET_FW_RULE_DIR_IN  WScript.Echo("  Direction:          In")
            Case NET_FW_RULE_DIR_OUT WScript.Echo("  Direction:          Out")
        End Select
        WScript.Echo("  Enabled:            " & rule.Enabled)
        WScript.Echo("  Edge:               " & rule.EdgeTraversal)
        Select Case rule.Action
            Case NET_FW_ACTION_ALLOW  WScript.Echo("  Action:             Allow")
            Case NET_FW_ACTION_BLOCk  WScript.Echo("  Action:             Block")
        End Select
        WScript.Echo("  Grouping:           " & rule.Grouping)
        WScript.Echo("  Edge:               " & rule.EdgeTraversal)
        WScript.Echo("  Interface Types:    " & rule.InterfaceTypes)
        InterfaceArray = rule.Interfaces
        if IsEmpty(InterfaceArray) then
            WScript.Echo("  Interfaces:         All")
        else
            LowerBound = LBound(InterfaceArray)
            UpperBound = UBound(InterfaceArray)
            WScript.Echo("  Interfaces:     ")
            for iterate = LowerBound To UpperBound
                WScript.Echo("       " & InterfaceArray(iterate))
            Next
        end if

        WScript.Echo("")
    end if
Next

在这里插入图片描述

flask默认开启的网站是本地的127.0.0.1:5000
现在把已经有的本机访问改成局域网访问:app.run(host=’0.0.0.0’,port=8080)

结语

如果您觉得该方法或代码有一点点用处,可以给作者点个赞,或打赏杯咖啡;╮( ̄▽ ̄)╭
如果您感觉方法或代码不咋地//(ㄒoㄒ)//,就在评论处留言,作者继续改进;o_O???
如果您需要相关功能的代码定制化开发,可以留言私信作者;(✿◡‿◡)
感谢各位大佬童鞋们的支持!( ´ ▽´ )ノ ( ´ ▽´)っ!!!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/351339.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

深度学习模型概念

Big data features: 5V--volume, velocity, variety, value, veracity.Big data challenges&#xff1a;高维、multi-modal、complexity、privacy 1. Federated Learning 联邦学习 Federated Learning&#xff1a;Server将model分散到各个用户user&#xff0c;clients利用本地…

不同相机之间图片像素对应关系求解(单应性矩阵求解)

一、场景 相机1和相机2相对位置不变&#xff0c;相机拍摄图片有重叠&#xff0c;求他们交叠部分的一一对应关系。数学语言描述为已知相机1图片中P点像素(u1, v1)&#xff0c;相机1中P点在相机2图片中像素值为(u2, v2)&#xff0c;它们存在某种变换&#xff0c;求变换矩阵。 因为…

计算机存储数字的本质,正码,反码,补码

计算机-原码 就是二进制定点表示法&#xff0c;即最高位为符号位&#xff1a;“0”表示正&#xff0c;“1”表示负&#xff0c;其余位表示数值的大小。 该数字不进行其他操作时数字最原始的二进制表示&#xff0c; 对于原码来说&#xff0c;绝对值相等的正数和负数只有符号位不…

高通平台开发系列讲解(USB篇)libuvc详解

文章目录 一、什么是UVC二、UVC拓扑结构三、libuvc的预览时序图沉淀、分享、成长,让自己和他人都能有所收获!😄 📢本篇文章将介绍libuvc。 一、什么是UVC UVC,全称为:USB video(device) class。 UVC是微软与另外几家设备厂商联合推出的为USB视频捕获设备定义的协议标…

缓存雪崩 缓存击穿-总结

目录 缓存雪崩 缓存击穿-总结 缓存雪崩 出现场景&#xff1a; 解决方案&#xff1a; 缓存击穿 出现场景&#xff1a; 举例如图&#xff1a; 缓存击穿的三个前提&#xff1a; 解决方案&#xff1a; 缓存雪崩 缓存击穿-总结 缓存雪崩 出现场景&#xff1a; (1) 对于R…

用于隔离PWM的光耦合器选择和使用

光耦合器&#xff08;或光隔离器&#xff09;是一种将电路电隔离的器件&#xff0c;不仅在隔离方面非常出色&#xff0c;而且允许您连接到具有不同接地层或在不同电压电平下工作的电路。光耦合器具有“故障安全”功能&#xff0c;因为如果受到高于最大额定值的电压&#xff0c;…

3.1 OSPF引入路由

实验目的掌握OSPF引入静态路由的办法掌握OSPF引入直连路由的办法实验拓扑OSPF引入路由实验拓扑如图3-1所示: 图3-1:OSPF引入路由 实验步骤配置IP地址R1的配置 <Huawei>system-view [Huawei]undo info-center enabl

软件测试面试题中的sql题目你会做吗?

目录 1.学生表 2.一道SQL语句面试题&#xff0c;关于group by表内容&#xff1a; 3.表中有A B C三列,用SQL语句实现&#xff1a;当A列大于B列时选择A列否则选择B列&#xff0c;当B列大于C列时选择B列否则选择C列 4. 5.姓名&#xff1a;name 课程&#xff1a;subject 分数&…

node-sass按照失败

一、描述 从网上下载的一个Vue模板项目&#xff0c;导入VsCode&#xff0c;执行npm install命令后&#xff0c;报错了&#xff0c;报错的信息是node-sass安装失败&#xff0c;同时提示需要python环境的错误信息&#xff0c;这是因为安装node-sass失败了&#xff0c;而node-sas…

开源实时监控系统 HertzBeat 对 Linux 操作系统的监控告警实践

使用开源实时监控系统 HertzBeat 对 Linux 操作系统的监控告警实践&#xff0c;5分钟搞定&#xff01; HertzBeat 介绍 HertzBeat 是一款开源&#xff0c;易用友好的实时监控系统&#xff0c;无需Agent&#xff0c;拥有强大自定义监控能力。 集监控-告警-通知为一体&#xff0…

Spring入门案例三:注解进行引用类型的自动装配

本系列文章将会带领大家进行Spring的全面学习&#xff0c;持续关注我&#xff0c;不断更新中… 一.案例分级 简单解析:配置类替代以前的配置文件&#xff0c;实体类提供对象&#xff0c;业务类中有实体类的引用对象&#xff0c;在业务层中实现引用类的自动装配。 二.各层代码…

Java基础 -- 泛型

Java基础 -- 泛型1. Introduction1.1 好处1.2 常用泛型2. User Guide2.1 泛型类2.2 泛型方法2.3 泛型接口3. 限定泛型范围4. Awakening1. Introduction 1.1 好处 代码复用&#xff0c;多种数据类型执行相同的代码在编译期间可以检查类型是否安全&#xff0c;报警ClassCastExce…

什么是webpack

目录 1、什么是webpack&#xff08;必会&#xff09; 2、Webpack的优点是什么&#xff1f;&#xff08;必会&#xff09; 3、webpack的构建流程是什么?从读取配置到输出文件这个过程尽量说全&#xff08;必会&#xff09; 4、说一下 Webpack 的热更新原理(必会) 5、webpa…

为什么说接口幂等性很重要

先讲个故事大概三年前&#xff0c;外卖平台 Uber Eats 在印度发生了一次重大事故&#xff0c;使得用户可以免费获得食品。一天早上&#xff0c;有人试图通过印度的 Uber Eats 订购食物&#xff0c;并使用印度的支付平台 Paytm 付款。但是&#xff0c;他的账户里面没有足够的余额…

蓝牙耳机哪款性价比高音质好?2023公认音质最好的蓝牙耳机

如今音乐成了当下解压的方式之一&#xff0c;甚至是集中注意力的法器。耳机作为传播音乐的媒介&#xff0c;每个人对自己的专属耳机总有那么点小追求&#xff0c;高质量的耳机不仅保护双耳&#xff0c;带来的音质能让你的耳朵分分钟怀孕&#xff0c;下面分享几款2023年音质高的…

Cain执行中间人攻击

实验目的&#xff1a;通过构建虚拟场景&#xff0c;了解中间人攻击和钓鱼网站攻击的执行流程&#xff0c;熟练使用Cain & Abel工具实现攻击&#xff0c;并掌握识别和防御此类攻击的技术原理和方法。 一、场景简介 甄某为犯罪嫌疑人&#xff0c;警察想获得甄某在其单位网站…

IB学科学习方法分享,看看不同学科怎么学习?(一)

在这个部分&#xff0c;我们邀请到了在各个学科中突出的同学们&#xff0c;让他们介绍自己的学习方法。同辈的经验总是我们能够获取的珍贵的宝藏&#xff01; 分享人&#xff1a;吴 分享学科&#xff1a;VA HL &#xff08;个人选课&#xff1a;HL&#xff1a;VA 中文 经济…

同行不同命:极兔喜、韵达愁?

配图来自Canva可画 年前买坚果、牛奶、灯笼、对联等年货&#xff0c;年后寄香肠、腊肉、泡菜、水果等特产&#xff0c;春节前后是快递业迎来收发货小高峰&#xff0c;三通一达&#xff0c;顺丰、京东、极兔相继宣布“春节不打烊”消息&#xff0c;全力保障快递运力。 春节快递…

力扣-组合两个表

大家好&#xff0c;我是空空star&#xff0c;本篇带你了解一道简单的力扣sql练习题。 文章目录前言一、题目&#xff1a;175. 组合两个表二、解题1.left join提交SQL运行结果2.right join提交SQL运行结果总结前言 一、题目&#xff1a;175. 组合两个表 表: Person ----------…

Bernstein-Vazirani算法

B-V算法 (1) 问题描述 给定布尔函数f:{0,1}n→0,1f:{\left\{ {0,1} \right\}^n} \to{0,1}f:{0,1}n→0,1, 函数fff的值是由输入比特串xxx和确定的比特串sss做模2意义下的内积&#xff1a;f(x)x⋅s(mod2),f\left( x \right) x \cdot s\left( {\bmod 2} \right),f(x)x⋅s(mod2),…