Skip to content

Instantly share code, notes, and snippets.

@AlexW867
Forked from timsutton/rename_ios_devices.py
Last active December 16, 2020 08:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AlexW867/d038a4e171185cd3fb30bf43ec6eab55 to your computer and use it in GitHub Desktop.
Save AlexW867/d038a4e171185cd3fb30bf43ec6eab55 to your computer and use it in GitHub Desktop.
Simple script to rename connected iOS devices according to a CSV file, using Apple Configurator 2's cfgutil command.
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Simple script to batch-rename attached iOS devices according to UUID to name mappings
# in a CSV file.
# Fork from https://gist.github.com/timsutton/3781d7483b7cdf0358eb86cf28b49e50
# Taiwan zh-Hant version by https://gist.github.com/AlexW867/d038a4e171185cd3fb30bf43ec6eab55
#
# for mac built-in python2.x
# 使用方式: python rename_ios_devices.py <csvfile>
#
# csvfile 檔案為逗點分隔格式,必須包含 "UUID"(大寫) 和 "名稱" 這兩個欄位,可由 Apple Configutator 2 直接輸出裝置資訊。
# CSV 檔案內的其他欄位會被忽略。
# 以下為範例格式
#
# UDID,名稱
# 19644dad28bfc9019cuaja9dfb4c0b1c21bfff01,A01
# b8a7209acef4e0be75f91ba9s891j20cce8a6f17,A02
import csv
import os
import plistlib
import subprocess
import sys
from pprint import pprint
CFGUTIL = '/Applications/Apple Configurator 2.app/Contents/MacOS/cfgutil'
def main():
if len(sys.argv) != 2:
sys.exit("本工具必須只能有一個參數: CSV 檔案")
csv_file = sys.argv[1]
if not os.path.exists(csv_file):
sys.exit("無法讀取 CSV 檔案 %s" % csv_file)
# names will be populated with string UDID keys mapping to string user-facing names for the iPads
names = {}
with open(csv_file, 'rb') as csv_fd:
reader = csv.DictReader(csv_fd, delimiter=',')
for row in reader:
names[row['UDID']] = row['名稱']
proc = subprocess.Popen([CFGUTIL, '--format', 'plist', 'list'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = proc.communicate()
try:
ipad_devices = plistlib.readPlistFromString(out)['Output']
except:
sys.exit("cfgutil 取得裝置列表發生錯誤")
for ecid, data in ipad_devices.iteritems():
if data['UDID'] in names.keys():
name_to_set = names[data['UDID']]
if name_to_set == data['name']:
print "裝置 %s 先前已命名為 %s, 略過..." % (
data['UDID'], name_to_set)
continue
print "找到符合 UDID %s 的裝置: %s - 正在重新命名" % (
data['UDID'], name_to_set)
cmd = [CFGUTIL, '--ecid', ecid, '--progress', '-v', 'rename', name_to_set]
print "執行指令: %s" % ' '.join(cmd)
subprocess.call(cmd)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment