Created
September 2, 2014 03:49
-
-
Save chilcote/f5af1a788ac4a2e4d5df to your computer and use it in GitHub Desktop.
python script to set dns servers and search domains in os x
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
''' | |
This script sets dns servers and search domains for all | |
Ethernet adapters and Wi-fi interfaces. | |
Requirements | |
------------ | |
+ OS X 10.9.x | |
+ python 2.7 | |
''' | |
############################################################################## | |
# Copyright 2014 Joseph Chilcote | |
# | |
# Licensed under the Apache License, Version 2.0 (the "License"); you may not | |
# use this file except in compliance with the License. You may obtain a copy | |
# of the License at | |
# | |
# http://www.apache.org/licenses/LICENSE-2.0 | |
# | |
# Unless required by applicable law or agreed to in writing, software | |
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | |
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the | |
# License for the specific language governing permissions and limitations | |
# under the License. | |
############################################################################## | |
import os, sys, subprocess | |
from SystemConfiguration import * | |
# Edit these lists | |
#-----------------# | |
search_domains = [] | |
dns_servers = [] | |
#-----------------# | |
prefs = SCPreferencesCreate(None, 'foo', None) | |
network_services = SCNetworkServiceCopyAll(prefs) | |
def usage(): | |
print 'Usage: ./pydns.py' | |
def get_networkservicelist(): | |
'''Returns a list of network interfaces''' | |
l = [] | |
for service in network_services: | |
l.append(SCNetworkServiceGetName(service)) | |
return l | |
def set_config(l, argument, category): | |
'''Sets search domains and dns servers''' | |
for i in l: | |
if 'Ethernet' in i or 'Wi-Fi' in i: | |
cmd = '/usr/sbin/networksetup %s "%s" %s' % (argument, | |
i, ' '.join(category)) | |
task = subprocess.Popen(cmd, stdout=subprocess.PIPE, | |
stderr=subprocess.PIPE, shell=True) | |
(out, err) = task.communicate() | |
if err: | |
print 'Unable to set %s: %s' % (category, err) | |
sys.exit(1) | |
def main(): | |
if len(sys.argv) == 1: | |
service_list = get_networkservicelist() | |
set_config(service_list, '-setsearchdomains', search_domains) | |
set_config(service_list, '-setdnsservers', dns_servers) | |
else: | |
usage() | |
sys.exit(0) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment