我正在尝试使用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)
编辑:上述大部分代码是基于此页面,该页面建议“触摸”动态存储以使设置生效(代码在末尾被注释掉)。但是,似乎没有任何作用。
编辑#2:通过反汇编/usr/sbin/networksetup
,我得到的想法是,在接受任何更改之前,我需要一组特定的权限(system.services.systemconfiguration.network
)。
sudo
运行脚本吗? - l'L'lDNSDict
可能为空(我已将它们手动设置),因此我也进行了修复。至于更新PyObjC,我建议使用virtualenv
。我的经验是更新系统提供的PyObjC并不是很好。 - robertklepSystem Configuration
中的三个.plist
文件从未被更新(甚至没有被访问),并且没有随着networksetup更改而改变。我不确定为什么会发生这种情况(也许是苹果公司做了一些改变?),但是我在github上找到了一个示例,它使用Python的os
命令来更改设置,确实有效。我意识到这是一种稍微不同的方法,但也许它可能有一些用处。 - l'L'lcom.apple.networkextension.plist
、preferences.plist
和resolv.conf
。如果你在终端运行networksetup
实用程序并在那里设置 dns,则这些值将在这些首选项中设置。 - l'L'l