使用PyObjC更改DNS设置

rob*_*lep 18 python macos pyobjc

我正在尝试使用PyObjC(3.0.4)更改Mac(10.10.4)上的DNS服务器.

一切似乎都有效:我收到一个身份验证对话框,提示我的程序正在尝试更改网络设置,并返回提交/应用命令True,这表明它们已成功.

但是,系统设置实际上并未更改:它们保持不变.知道为什么他们不"坚持"?

代码(独立,如果你安装了最新版本的PyObjC,应该可以工作):

#!/usr/bin/env python

import  objc
from    SystemConfiguration import *

# Open dynamic store and get primary interface
store = SCDynamicStoreCreate(None, 'MyApp', None, None)
primaryif = SCDynamicStoreCopyValue(store, 'State:/Network/Global/IPv4')['PrimaryInterface']
if primaryif:
    print "Using %s as primary interface" % primaryif
else:
    raise "Can't find primary interface"

# Load SecurityInterface framework to provide SFAuthorization
objc.initFrameworkWrapper(
    frameworkName       = "SecurityInterface",
    frameworkIdentifier = "com.apple.securityinterface",
    frameworkPath       = objc.pathForFramework("/System/Library/Frameworks/SecurityInterface.framework"),
    globals             = globals()
)

# Access system preferences
preferences = SCPreferencesCreateWithAuthorization(None, 'MyApp', None, SFAuthorization.authorization().authorizationRef())

# Lock preferences
SCPreferencesLock(preferences, True)

# Get list of network services
networkSet = SCNetworkSetCopyCurrent(preferences)
networkSetServices = SCNetworkSetCopyServices(networkSet)

# Find the network service that belongs to the primary interface
for networkService in networkSetServices:
    interface = SCNetworkServiceGetInterface(networkService)
    if primaryif != SCNetworkInterfaceGetBSDName(interface):
        continue

    # Load currently configured DNS servers
    networkProtocol = SCNetworkServiceCopyProtocol(networkService, kSCNetworkProtocolTypeDNS)
    DNSDict = SCNetworkProtocolGetConfiguration(networkProtocol) or {}

    # Set new DNS servers
    DNSDict[kSCPropNetDNSServerAddresses] = [ '192.168.23.12', '8.8.4.4' ]
    SCNetworkProtocolSetConfiguration(networkService, DNSDict)

    # Unlock, commit and apply preferences
    print "UL", SCPreferencesUnlock(preferences)
    print "CO", SCPreferencesCommitChanges(preferences)
    print "AP", SCPreferencesApplyChanges(preferences)
Run Code Online (Sandbox Code Playgroud)

编辑:上面的大部分代码都基于这个页面,它也建议"触摸"动态存储以使设置保持不变(执行此操作的代码在最后注释掉).但是,它似乎没有做任何事情.

编辑#2:通过反汇编,/usr/sbin/networksetup我认为system.services.systemconfiguration.network在接受任何更改之前我需要一组特定权限().

jay*_*ypb 2

看起来 PyObjC 存在问题,导致此功能无法正常工作,但是您可以通过使用不同的解决方案找到解决方法。如果我是你,并且我的情况允许的话,我会调用系统命令行工具来设置 DNS 服务器。

根据OSXDaily 的说法,您可以通过以下方式执行此操作:

networksetup -setdnsservers (Network Service) (DNS IP)
Run Code Online (Sandbox Code Playgroud)

如果您有跨平台要求,这显然不太理想。