我正在尝试使用 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)
编辑:以上代码大部分基于this page ,这也建议“触摸”动态存储以使设置保持不变(执行此操作的代码在最后被注释掉)。但是,它似乎没有做任何事情。
EDIT #2:通过反汇编 /usr/sbin/networksetup
我得到了我需要一组特定权限(system.services .systemconfiguration.network
) 在接受任何更改之前。
最佳答案
看起来 PyObjC 存在问题导致此方法无法正常工作,但是您可以通过使用不同的解决方案找到解决方法。如果我是你,并且我的情况允许,我会调用系统命令行工具来设置 DNS 服务器。
根据OSXDaily ,你可以这样做:
networksetup -setdnsservers (Network Service) (DNS IP)
如果您有跨平台需求,这显然不太理想。
关于python - 使用 PyObjC 更改 DNS 设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32073573/