繁体   English   中英

如何使用python禁用Windows防火墙

[英]How to disable Windows Firewall using python

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

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

我找到了这个网站: https : //mail.python.org/pipermail/python-win32/2012-July/012434.html但是问题是,当我从控制面板中检查时,并未真正禁用防火墙。 。

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

最好的方法是使用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_()

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

希望这可以帮助,

杰森

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

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

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

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

  • 注册表设置位于

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

    更改设置具有立竿见影的效果:防火墙服务显然会为密钥设置通知。

  • 可以使用这些设置的设施:

    • COM接口HNetCfg.FwMgr
    • netsh firewall (用于高级防火墙的netsh advfirewall
    • WMI winmgmts:root/Microsoft/HomeNet
    • %windir%\\Inf\\Netfw.inf (除非手动创建,否则不存在)

firewall.cpl反映了本地注册表设置(如果存在并且不允许更改 ,则覆盖组策略设置)和当前活动的配置文件(有关预定义的配置文件和选择方式,请参阅Windows防火墙的工作方式 ,“ Windows XP / 2003的“防火墙配置文件确定”部分和了解 Vista +的防火墙配置文件 )。

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

# -*- 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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