1

我正在尝试为我正在工作的一个小项目编写自动化。在过程中,我需要使用 python禁用 Windows 防火墙(对于每个 Windows 版本) (我更喜欢 activepython,因为它已经安装)。

我寻找了很多答案,但没有找到适合我需要的答案。

我找到了这个网站: https ://mail.python.org/pipermail/python-win32/2012-July/012434.html 但问题是当我从控制面板检查时,防火墙的实际禁用没有发生.. .

有人可以帮我解决这个问题吗?

4

4 回答 4

2

Windows 防火墙工具和设置MSDN 文章中广泛介绍了控制 Windows 防火墙的方法(使用 UI 和以编程方式) 。他们是:

  • 注册表设置在

    • HKLM\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\<profile>(本地设置)和
    • HKLM\SOFTWARE\Policies\Microsoft\WindowsFirewall\<profile>(组策略设置)。

    更改设置会立即生效:防火墙服务显然会为密钥设置通知。

  • 使用设置的设施:

    • 通讯接口HNetCfg.FwMgr
    • netsh firewallnetsh advfirewall对于高级防火墙)
    • WMIwinmgmts:root/Microsoft/HomeNet
    • %windir%\Inf\Netfw.inf(除非手动创建,否则不存在)

firewall.cpl反映本地注册表设置(或覆盖组策略设置,如果它们存在并且不允许更改它们)和当前活动的配置文件(对于预定义的配置文件以及如何选择一个,请参阅Windows 防火墙的工作原理,“Windows 防火墙配置文件确定" XP/2003 部分和了解Vista+ 的防火墙配置文件)。

Python 可以使用上述任何工具。尽管其他工具(组策略、.reg文件、netsh命令行)可能更方便,具体取决于您的任务(例如netsh自动选择活动配置文件)。

于 2016-02-02T23:23:12.840 回答
2

最好的方法是使用WMI

import wmi,os

c = wmi.WMI("WinMgmts:\root\Microsoft\HomeNet")

for obj in c.HNet_ConnectionProperties():
    print obj
    print obj.IsFirewalled
    obj.IsFirewalled = False
    obj.Put_()

当然,要做到这一点,您需要以管理员身份运行该程序。

希望这可以帮助,

杰森。

于 2016-01-30T16:28:58.143 回答
1

最简单的方法是让另一个程序为您完成工作。在这种情况下,netsh.exe 有一组命令来控制Windows Vista 及更高版本使用的高级防火墙。例如:

import subprocess
subprocess.check_call('netsh.exe advfirewall set publicprofile state off')

默认配置文件为“domainprofile”、“privateprofile”和“publicprofile”,状态为“on”或“off”。

于 2016-02-02T12:54:13.177 回答
-2
# -*- coding: utf-8 -*-
'''
State for configuring Windows Firewall
'''


def __virtual__():
'''
Load if the module firewall is loaded
'''
return 'win_firewall' if 'firewall.get_config' in __salt__ else False


def disabled(name):
'''
Disable all the firewall profiles (Windows only)
'''
ret = {'name': name,
       'result': True,
       'changes': {},
       'comment': ''}

# Determine what to do
action = False
current_config = __salt__['firewall.get_config']()
for key in current_config:
    if current_config[key]:
        action = True
        ret['changes'] = {'fw': 'disabled'}
        break

if __opts__['test']:
    ret['result'] = None
    return ret

# Disable it
if action:
    ret['result'] = __salt__['firewall.disable']()
    if not ret['result']:
        ret['comment'] = 'Could not disable the FW'
else:
    ret['comment'] = 'All the firewall profiles are disabled'

return ret
于 2016-01-30T16:29:47.010 回答