我正在尝试使用PyObjC(3.0.4)更改Mac(10.10.4)上的DNS服务器。在
所有似乎都在工作:我得到一个身份验证对话框,提示我的程序正在尝试更改网络设置,commit/apply命令返回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)
编辑:上面的大多数代码都是基于this page,这也建议“触摸”动态存储以使设置保持不变(执行此操作的代码在末尾被注释掉)。然而,它似乎没有任何作用。在
编辑#2:通过反汇编/usr/sbin/networksetup
我得到的想法是,在接受任何更改之前,我需要一组特定的权限(system.services.systemconfiguration.network
)。在
看起来PyObjC有一些问题导致它无法工作,但是您可以通过使用不同的解决方案来找到一种解决方法。如果我是你,而且我的情况允许的话,我会调用系统命令行工具来设置DNS服务器。在
根据OSXDaily,您可以使用以下方法来完成此操作:
如果您有跨平台的需求,这显然是不可取的。在
相关问题 更多 >
编程相关推荐