Admin Tools

sudo のログを取得する(macOS15以降用)


AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003# com.cocolog-nifty.quicktimer.icefloe
004# オリジナルスクリプト
005# https://derflounder.wordpress.com/2024/10/18/successfully-run-sudo-commands-are-no-longer-logged-by-default-to-unified-logging-on-macos-sequoia/
006#回数は行数から取得しているのでアバウトな値です
007----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
008use AppleScript version "2.8"
009use framework "Foundation"
010use framework "AppKit"
011use scripting additions
012
013property refMe : a reference to current application
014
015#設定項目 ログの精査する時間
016set strTimeH to "3h"
017
018
019#保存先
020set appFileManager to refMe's NSFileManager's defaultManager()
021set ocidTempDirURL to appFileManager's temporaryDirectory()
022set ocidUUID to refMe's NSUUID's alloc()'s init()
023set ocidUUIDString to ocidUUID's UUIDString
024set ocidSaveDirPathURL to ocidTempDirURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:true
025set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
026ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
027set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference)
028#保存ファイル
029set strFileName to "sudo.log" as text
030set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strFileName) isDirectory:false
031#出力用のテキスト
032set ocidOutputString to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
033
034#コマンド実行 エラー回数
035set strCommandText to ("/usr/bin/log  show --last " & strTimeH & " --style syslog --predicate 'process == \"sudo\" AND composedMessage CONTAINS \"incorrect\"'") as text
036log "\n" & strCommandText & "\n"
037try
038  set strResponse to (do shell script strCommandText) as string
039on error
040  return "log でエラーしましたA"
041end try
042ocidOutputString's appendString:(strResponse)
043set ocidOutputString to (ocidOutputString's stringByReplacingOccurrencesOfString:("\r") withString:("\n"))
044#
045set ocidIncorrectArray to ocidOutputString's componentsSeparatedByString:("\n")
046#行数数えて
047set numCntIncorrect to ocidIncorrectArray's |count|()
048if (numCntIncorrect as integer) >= 2 then
049  display notification "sudo エラーが発生しています" with title "セキュリティアラート" subtitle "sudoコマンドでのエラーが発生しました。アカウントのセキュリティを確認してください" sound name "Sonumi"
050  display alert "sudo エラーが発生しています" message "sudoコマンドでのエラーが発生しました。アカウントのセキュリティを確認してください" giving up after 2 as critical
051end if
052
053#コマンド実行
054set strCommandText to ("/usr/bin/log  show --last " & strTimeH & " --style syslog --predicate 'process == \"sudo\"'") as text
055log "\n" & strCommandText & "\n"
056try
057  set strResponse to (do shell script strCommandText) as string
058on error
059  return "log でエラーしましたB"
060end try
061##改行置換
062ocidOutputString's appendString:("------\n")
063ocidOutputString's appendString:(strResponse)
064set ocidOutputString to (ocidOutputString's stringByReplacingOccurrencesOfString:("\r") withString:("\n"))
065ocidOutputString's appendString:("------\n")
066#行数数えて
067set ocidFilePathStr to refMe's NSString's stringWithString:(strResponse)
068set ocidSudoArray to ocidOutputString's componentsSeparatedByString:("\n")
069set numCntSudo to ocidSudoArray's |count|()
070#
071set strRawNo to ("sudo回数: " & (numCntSudo as text) & "回\nうちエラー回数: " & (numCntIncorrect as text) & "回\n") as text
072set strMes to ("sudoのログです") as text
073#
074tell current application
075  set strName to name as text
076end tell
077if strName is "osascript" then
078  tell application "Finder"
079    activate
080  end tell
081else
082  tell current application
083    activate
084  end tell
085end if
086set aliasIconPath to (POSIX file "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/Actions.icns") as alias
087try
088  set recordResult to (display dialog strMes with title "戻り値です" default answer strRawNo buttons {"クリップボードにコピー", "終了", "詳細ログを開く"} default button "詳細ログを開く" cancel button "終了" giving up after 20 with icon aliasIconPath without hidden answer) as record
089on error
090  return "エラーしました"
091end try
092if (gave up of recordResult) is true then
093  return "時間切れです"
094end if
095##############################
096#####
097##############################
098if button returned of recordResult is "詳細ログを開く" then
099  set listDone to (ocidOutputString's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error| :(reference))
100  #開く
101  set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
102  set boolDone to appSharedWorkspace's openURL:(ocidSaveFilePathURL)
103end if
104##############################
105#####値のコピー
106##############################
107if button returned of recordResult is "クリップボードにコピー" then
108  try
109    set strText to text returned of recordResult as text
110    ####ペーストボード宣言
111    set appPasteboard to refMe's NSPasteboard's generalPasteboard()
112    set ocidText to (refMe's NSString's stringWithString:(strText))
113    appPasteboard's clearContents()
114    appPasteboard's setString:(ocidText) forType:(refMe's NSPasteboardTypeString)
115  on error
116    tell application "Finder"
117      set the clipboard to strText as text
118    end tell
119  end try
120end if
121
122
123return 0
124
125
AppleScriptで生成しました

|

AEA1 拡張子 aea の解凍


サンプルコード

サンプルソース(参考)
行番号ソース
001#!/bin/bash
002#com.cocolog-nifty.quicktimer.icefloe
003# ipsw バイナリー
004# iOS/macOS Research
005# https://github.com/blacktop/ipsw
006#################################################
007
008
009STAT_USR=$(/usr/bin/stat -f%Su /dev/console)
010STR_BIN_PATH="/Users/${STAT_USR}/bin/ipsw/ipsw"
011STR_AEA_PATH="/Users/${STAT_USR}/Downloads/UniversalMac_15.0_24A335_Restore/096-29336-585.dmg.aea"
012#ファイル名
013STR_EXTRACT_PATH=$(/usr/bin/basename "$STR_AEA_PATH" ".aea")
014PARENT_DIR=$(/usr/bin/dirname "$STR_AEA_PATH")
015STR_SAVE_PATH="${PARENT_DIR}/${STR_EXTRACT_PATH}"
016
017STR_KEY_VALUE=$("$STR_BIN_PATH" fw aea --key "$STR_AEA_PATH")
018
019/usr/bin/aea decrypt -i "$STR_AEA_PATH" -o "$STR_SAVE_PATH" -key-value "$STR_KEY_VALUE"
020
021
022/bin/echo "DONE"
AppleScriptで生成しました

|

[lsof]プロセスが握っているファイルの一覧を出力する

使用中ファイル(キーワードGrep)
AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004#com.cocolog-nifty.quicktimer.icefloe
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use framework "Foundation"
008use framework "AppKit"
009use scripting additions
010
011property refMe : a reference to current application
012set strMes to ("プロセス名やプロセス番号等を入力\nよく使う気ワード\nsock ソケット\nTCP ESTABLISHED\nユーザー名 root wheel等\nディスク名\n接続名 DIR REG ") as text
013
014########################
015## クリップボードの中身取り出し
016########################
017###初期化
018set appPasteboard to refMe's NSPasteboard's generalPasteboard()
019##格納されているタイプをリストにして
020set ocidPastBoardTypeArray to appPasteboard's types
021###テキストがあれば
022set boolContain to ocidPastBoardTypeArray's containsObject:("public.utf8-plain-text")
023if (boolContain as boolean) is true then
024  ###値を格納する
025  tell application "Finder"
026    set strReadString to (the clipboard as text) as text
027  end tell
028else
029  ###UTF8が無いなら
030  ##テキスト形式があるか?確認して
031  set boolContain to ocidPastBoardTypeArray's containsObject:(refMe's NSPasteboardTypeString)
032  ##テキスト形式があるなら
033  if (boolContain as boolean) is true then
034    set ocidTypeClassArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
035    ocidTypeClassArray's addObject:(refMe's NSString)
036    set ocidReadString to appPasteboard's readObjectsForClasses:(ocidTypeClassArray) options:(missing value)
037    set strReadString to ocidReadString as text
038  else
039    log "テキストなし"
040    set strReadString to strMes as text
041  end if
042end if
043##############################
044#####ダイアログ
045##############################
046###ダイアログを前面に出す
047set strName to (name of current application) as text
048if strName is "osascript" then
049  tell application "Finder" to activate
050else
051  tell current application to activate
052end if
053set aliasIconPath to POSIX file "/System/Applications/Calculator.app/Contents/Resources/AppIcon.icns" as alias
054try
055  set recordResult to (display dialog strMes with title "入力してください" default answer strReadString buttons {"OK", "キャンセル"} default button "OK" with icon aliasIconPath giving up after 20 without hidden answer) as record
056on error
057  log "エラーしました"
058  return
059end try
060if "OK" is equal to (button returned of recordResult) then
061  set strReturnedText to (text returned of recordResult) as text
062else if (gave up of recordResult) is true then
063  return "時間切れです"
064else
065  return "キャンセル"
066end if
067##############################
068#####戻り値整形
069##############################
070set ocidResponseText to (refMe's NSString's stringWithString:(strReturnedText))
071###タブと改行を除去しておく
072set ocidTextM to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
073ocidTextM's appendString:(ocidResponseText)
074###除去する文字列リスト
075set listRemoveChar to {"\n", "\r", "\t", "¥", "¥", "\\s"} as list
076##置換
077repeat with itemChar in listRemoveChar
078  set strPattern to itemChar as text
079  set strTemplate to ("") as text
080  set ocidOption to (refMe's NSRegularExpressionCaseInsensitive)
081  set listResponse to (refMe's NSRegularExpression's regularExpressionWithPattern:(strPattern) options:(ocidOption) |error| :(reference))
082  if (item 2 of listResponse) ≠ (missing value) then
083    log (item 2 of listResponse)'s localizedDescription() as text
084    return "正規表現パターンに誤りがあります"
085  else
086    set ocidRegex to (item 1 of listResponse)
087  end if
088  set numLength to ocidResponseText's |length|()
089  set ocidRange to refMe's NSRange's NSMakeRange(0, numLength)
090  set ocidResponseText to (ocidRegex's stringByReplacingMatchesInString:(ocidResponseText) options:0 range:(ocidRange) withTemplate:(strTemplate))
091end repeat
092
093set strResponseText to ocidResponseText as text
094
095set strComandText to ("/usr/sbin/lsof | grep \"" & strResponseText & "\"") as text
096log strComandText
097try
098  set strResponse to (do shell script strComandText) as text
099on error
100  set strResponse to "使用中のファイルはありませんでした"
101end try
102
103
104#######
105set strDateNo to doGetDateNo("yyyyMMddhhmmss")
106set strFileName to strDateNo & ".txt" as text
107set aliasTemporaryPath to path to temporary items from user domain as alias
108set strFilePath to (POSIX path of aliasTemporaryPath) & strFileName as text
109tell application "TextEdit"
110  activate
111  make new document with properties {name:strFileName, path:strFilePath}
112  tell document strFileName
113    activate
114    set its text to "使用中のファイルのパス\r" & strResponse
115    save in (POSIX file strFilePath)
116  end tell
117end tell
118#######
119
120tell application "Finder"
121  set aliasPathToMe to (path to me) as alias
122end tell
123run script aliasPathToMe with parameters "再実行"
124
125
126
127to doGetDateNo(strDateFormat)
128  ####日付情報の取得
129  set ocidDate to refMe's NSDate's |date|()
130  ###日付のフォーマットを定義
131  set ocidNSDateFormatter to refMe's NSDateFormatter's alloc()'s init()
132  ocidNSDateFormatter's setLocale:(refMe's NSLocale's localeWithLocaleIdentifier:"en_US")
133  ocidNSDateFormatter's setDateFormat:strDateFormat
134  
135  set ocidDateAndTime to ocidNSDateFormatter's stringFromDate:ocidDate
136  set strDateAndTime to ocidDateAndTime as text
137  return strDateAndTime
138end doGetDateNo
AppleScriptで生成しました

使用中ファイル(ディスク指定)
AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004#com.cocolog-nifty.quicktimer.icefloe
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006
007use AppleScript version "2.8"
008use framework "Foundation"
009use scripting additions
010
011property refMe : a reference to current application
012
013##########################
014## ディスクリスト
015##########################
016set listDiskName to {}
017
018tell application "System Events"
019  set listObjDisk to every disk as list
020  repeat with objDisk in listObjDisk
021    tell objDisk
022      ##ディスク名をリストに格納
023      set srtDiskName to name
024      copy "" & srtDiskName & "" to end of listDiskName
025    end tell
026  end repeat
027end tell
028
029##########################
030## ダイアログ
031##########################
032###ダイアログを前面に出す
033set strName to (name of current application) as text
034if strName is "osascript" then
035  tell application "Finder" to activate
036else
037  tell current application to activate
038end if
039set numCntDisk to (count of listDiskName) as integer
040try
041  set strDiskName to (choose from list listDiskName with title "ディスクの選択" with prompt "使用中のファイルリストを出力します" default items (item numCntDisk of listDiskName) OK button name "OK" cancel button name "キャンセル" with multiple selections allowed without empty selection allowed)
042on error
043  log "エラーしました"
044  return
045end try
046if strDiskName is false then
047  return
048end if
049try
050  set theComandText to ("/usr/sbin/lsof \"/Volumes/" & strDiskName & "\"") as text
051  set strResponse to (do shell script theComandText) as text
052on error
053  set strResponse to "使用中のファイルはありませんでした"
054end try
055
056set strDateNo to doGetDateNo("yyyyMMddhhmmss")
057set strFileName to strDateNo & ".txt" as text
058set aliasTemporaryPath to path to temporary items from user domain as alias
059set strFilePath to (POSIX path of aliasTemporaryPath) & strFileName as text
060tell application "TextEdit"
061  activate
062  make new document with properties {name:strFileName, path:strFilePath}
063  tell document strFileName
064    activate
065    set its text to "使用中のファイルのパス\r" & strResponse
066    save in (POSIX file strFilePath)
067  end tell
068end tell
069
070#######
071
072tell application "Finder"
073  set aliasPathToMe to (path to me) as alias
074end tell
075run script aliasPathToMe with parameters "再実行"
076
077
078to doGetDateNo(strDateFormat)
079  ####日付情報の取得
080  set ocidDate to refMe's NSDate's |date|()
081  ###日付のフォーマットを定義
082  set ocidNSDateFormatter to refMe's NSDateFormatter's alloc()'s init()
083  ocidNSDateFormatter's setLocale:(refMe's NSLocale's localeWithLocaleIdentifier:"en_US")
084  ocidNSDateFormatter's setDateFormat:strDateFormat
085  
086  set ocidDateAndTime to ocidNSDateFormatter's stringFromDate:ocidDate
087  set strDateAndTime to ocidDateAndTime as text
088  return strDateAndTime
089end doGetDateNo
AppleScriptで生成しました

|

Affinityのダウンロード用のURLを取得する(クエリー付き)


AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004#com.cocolog-nifty.quicktimer.icefloe
005#
006#
007#
008----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
009use AppleScript version "2.8"
010use framework "Foundation"
011use framework "AppKit"
012use scripting additions
013property refMe : a reference to current application
014
015
016#対象のURL
017# set strURL to ("https://store.serif.com/en-gb/update/macos/publisher/2/") as text
018# set strURL to ("https://store.serif.com/en-gb/update/macos/photo/2/") as text
019set strURL to ("https://store.serif.com/en-gb/update/macos/designer/2/") as text
020
021#URL
022set ocidURLString to (refMe's NSString's stringWithString:(strURL))
023set ocidURL to (refMe's NSURL's alloc()'s initWithString:(ocidURLString))
024
025#XML
026set ocidOption to (refMe's NSXMLDocumentTidyHTML)
027set listReadXMLDoc to (refMe's NSXMLDocument's alloc()'s initWithContentsOfURL:(ocidURL) options:(ocidOption) |error| :(reference))
028set ocidReadXMLDoc to (item 1 of listReadXMLDoc)
029set ocidRootElement to ocidReadXMLDoc's rootElement()
030set ocidHeadElement to (ocidRootElement's elementsForName:("body"))'s firstObject()
031set listResponse to (ocidHeadElement's nodesForXPath:("//a") |error| :(reference))
032if (item 2 of listResponse) = (missing value) then
033  set ocidAArray to (item 1 of listResponse)
034else if (item 2 of listResponse) ≠ (missing value) then
035  set strErrorNO to (item 2 of listResponse)'s code() as text
036  set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text
037  refMe's NSLog("■:" & strErrorNO & strErrorMes)
038  return "エラーしました" & strErrorNO & strErrorMes
039end if
040
041#出力用テキスト
042set ocidOutPutstring to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
043
044#収集したURLの数だけ繰り返し
045repeat with itemNode in ocidAArray
046  set ocidLinkAttr to (itemNode's attributeForName:("href"))
047  set strLinkURL to ocidLinkAttr's stringValue() as text
048  set ocidLinkURLString to (refMe's NSString's stringWithString:(strLinkURL))
049  set ocidLinkURL to (refMe's NSURL's alloc()'s initWithString:(ocidLinkURLString))
050  set strExtensionName to ocidLinkURL's pathExtension() as text
051  if strExtensionName is "dmg" then
052    (ocidOutPutstring's appendString:(ocidLinkURLString))
053    (ocidOutPutstring's appendString:("\n--------------------------\n"))
054  end if
055end repeat
056
057log ocidOutPutstring as text
058
059
060return (ocidOutPutstring as text)
AppleScriptで生成しました

|

デバイスの情報表示(仮)

JamfCheck
https://github.com/txhaflaire/JamfCheck
SilentKnight
https://eclecticlight.co/lockrattler-systhist/

足して2で割ったようなのを目指したが断念
まぁ普通に表示まではいけます

AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#! /usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#com.cocolog-nifty.quicktimer.icefloe
004# 各種情報を収集HTML表示
005# 計画性なく作ったV1
006----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
007use AppleScript version "2.8"
008use framework "Foundation"
009use framework "AppKit"
010use scripting additions
011
012property refMe : a reference to current application
013
014
015##########################################
016#【1】コンピューター名
017set appFileManager to refMe's NSFileManager's defaultManager()
018set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSLibraryDirectory) inDomains:(refMe's NSLocalDomainMask))
019set ocidLibraryDirPathURL to ocidURLsArray's firstObject()
020set ocidPlistFilePathURL to ocidLibraryDirPathURL's URLByAppendingPathComponent:("Preferences/SystemConfiguration/preferences.plist") isDirectory:(false)
021#
022set listResponse to refMe's NSDictionary's alloc()'s initWithContentsOfURL:(ocidPlistFilePathURL) |error| :(reference)
023if (item 2 of listResponse) = (missing value) then
024  log "正常処理"
025  set ocidPlistDict to (item 1 of listResponse)
026else if (item 2 of listResponse) ≠ (missing value) then
027  log (item 2 of listResponse)'s code() as text
028  log (item 2 of listResponse)'s localizedDescription() as text
029  log "エラーしました"
030  return false
031end if
032set ocidPlistFilePathURL to ocidLibraryDirPathURL's URLByAppendingPathComponent:("Preferences/SystemConfiguration/com.apple.smb.server.plist") isDirectory:(false)
033#
034set listResponse to refMe's NSDictionary's alloc()'s initWithContentsOfURL:(ocidPlistFilePathURL) |error| :(reference)
035if (item 2 of listResponse) = (missing value) then
036  log "正常処理"
037  set ocidPlistDictSMB to (item 1 of listResponse)
038else if (item 2 of listResponse) ≠ (missing value) then
039  log (item 2 of listResponse)'s code() as text
040  log (item 2 of listResponse)'s localizedDescription() as text
041  log "エラーしました"
042  return false
043end if
044(* この方法だとBonjourとSMB名が取れないので使わない
045set recordSystemInfo to (system info) as record
046###MacOS用
047set strComputerName to (computer name of recordSystemInfo) as text
048###/bin/hostname と同等
049set strHostName to (host name of recordSystemInfo) as text
050*)
051###Bonjourローカルネットワーク用
052set ocidLocalHostName to (ocidPlistDict's valueForKeyPath:("System.Network.HostNames.LocalHostName"))
053###MacOS用
054set ocidComputerName to (ocidPlistDict's valueForKeyPath:("System.System.ComputerName"))
055###/bin/hostname と同等
056set ocidHostName to (ocidPlistDict's valueForKeyPath:("System.System.HostName"))
057###SMB用
058set ocidNetBIOSName to (ocidPlistDictSMB's valueForKeyPath:("NetBIOSName"))
059
060log ocidLocalHostName as text
061log ocidComputerName as text
062log ocidHostName as text
063log ocidNetBIOSName as text
064
065
066##########################################
067#【2】OS情報
068set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSCoreServiceDirectory) inDomains:(refMe's NSSystemDomainMask))
069set ocidCoreServiceDirPathURL to ocidURLsArray's firstObject()
070set ocidPlistFilePathURL to ocidCoreServiceDirPathURL's URLByAppendingPathComponent:("SystemVersion.plist") isDirectory:(false)
071#
072set listResponse to refMe's NSDictionary's alloc()'s initWithContentsOfURL:(ocidPlistFilePathURL) |error| :(reference)
073if (item 2 of listResponse) = (missing value) then
074  log "正常処理"
075  set ocidPlistDict to (item 1 of listResponse)
076else if (item 2 of listResponse) ≠ (missing value) then
077  log (item 2 of listResponse)'s code() as text
078  log (item 2 of listResponse)'s localizedDescription() as text
079  log "エラーしました"
080  return false
081end if
082(* この方法だとビルド番号が取れないので使わない
083set recordSystemInfo to (system info) as record
084###OSバージョン
085set strProductBuildVersion to (system version of recordSystemInfo) as text
086*)
087###ビルド番号
088set ocidProductBuildVersion to (ocidPlistDict's valueForKeyPath:("ProductBuildVersion"))
089###OSバージョン
090set ocidProductVersion to (ocidPlistDict's valueForKeyPath:("ProductVersion"))
091
092log ocidProductBuildVersion as text
093log ocidProductBuildVersion as text
094
095##########################################
096#【3】シリアル番号 system_profiler JSON
097set ocidSerialNo to doSPHardwareDataTypeJson("SPHardwareDataType.serial_number")'s firstObject()
098set ocidModelName to doSPHardwareDataTypeJson("SPHardwareDataType.machine_model")
099set ocidPlatform_UUID to doSPHardwareDataTypeJson("SPHardwareDataType.platform_UUID")
100set ocidBootRomVer to doSPHardwareDataTypeJson("SPHardwareDataType.boot_rom_version")
101
102log ocidSerialNo as text
103log ocidModelName as text
104log ocidPlatform_UUID as text
105log ocidBootRomVer as text
106
107##########################################
108#【4】モデル名 ConfigCode
109set ocidConfigCode to doGetConfigCode(ocidSerialNo)
110log ocidConfigCode as text
111
112##########################################
113#【5】メモリー量
114set ocidProcessInfo to refMe's NSProcessInfo's processInfo()
115set realMemoryByte to ocidProcessInfo's physicalMemory() as real
116set realGB to "1073741824" as real
117set numPhysicalMemory to (realMemoryByte / realGB) as integer
118(* これはこの方法でも良かった
119set recordSystemInfo to (system info) as record
120set numMem to (physical memory of recordSystemInfo) as real
121set numPhysicalMemory to (numMem / 1000) as integer
122*)
123
124##########################################
125#【6】ディスク キャパ と 残 diskutil
126set listVolumeInfo to doGetVolumeInfo()
127set ocidVolumeName to (item 1 of listVolumeInfo)
128set ocidFileVault to (item 2 of listVolumeInfo)
129set ocidEncryption to (item 3 of listVolumeInfo)
130set numTotalSize to (item 4 of listVolumeInfo)
131set numContainerFree to (item 5 of listVolumeInfo)
132set ocidDiskUUID to (item 6 of listVolumeInfo)
133log ocidVolumeName as text
134log ocidFileVault as text
135log ocidEncryption as text
136log numTotalSize as text
137log numContainerFree as text
138log ocidDiskUUID as text
139(*ディスクサイズとディスク残はこの方法でも良い
140
141tell application "System Events"
142  set strVolumeName to (name of startup disk) as text
143  tell startup disk
144    set numDiskCapacity to capacity as real
145    set numFreeSpace to free space as real
146  end tell
147end tell
148set intGB to "1073741824" as integer
149set intGB to "1000000000" as integer
150set numTotalSize to (numTotalSize / intGB) as integer
151set numContainerFree to (numContainerFree / intGB) as integer
152*)
153
154##########################################
155#【7】システム保護
156set strCommandText to ("/bin/bash -c '/usr/bin/csrutil status 2>&1'") as text
157set strResponse to (do shell script strCommandText) as text
158if strResponse contains "enabled" then
159  log "System Integrity Protection ON"
160  set ocidSIP to ("ON") as text
161else
162  log "System Integrity ProtectionがOFFです"
163  set ocidSIP to ("OFF") as text
164end if
165
166
167##########################################
168#【8】XProtect
169set strCommandText to ("/bin/bash -c '/usr/sbin/spctl --status 2>&1'") as text
170set strResponse to (do shell script strCommandText) as text
171if strResponse contains "enabled" then
172  log "XProtect ON"
173  set ocidXProtect to ("ON") as text
174else
175  log "XProtectがOFFです"
176  set ocidXProtect to ("OFF") as text
177end if
178
179
180##########################################
181#【9】TCCバージョン
182set strChkFilePath to ("/Library/Apple/Library/Bundles/TCC_Compatibility.bundle") as text
183#バージョン取得
184set ocidTCCver to doGetVersion(strChkFilePath)
185log ocidTCCver as text
186
187##########################################
188#【10】AppleKext バージョン
189set strChkFilePath to ("/Library/Apple/System/Library/Extensions/AppleKextExcludeList.kext") as text
190#バージョン取得
191set ocidKEXTver to doGetVersion(strChkFilePath)
192log ocidKEXTver as text
193
194##########################################
195#【11】XProtect バージョン
196set strChkFilePath to ("/Library/Apple/System/Library/CoreServices/XProtect.bundle/Contents/Info.plist") as text
197#バージョン取得
198set ocidMRTver to doGetPlistValue(strChkFilePath, "CFBundleShortVersionString")
199log ocidMRTver as text
200
201##########################################
202#【12】ディスクの暗号化 fdesetup
203set strCommandText to ("/bin/bash -c '/usr/bin/fdesetup status 2>&1'") as text
204set strResponse to (do shell script strCommandText) as text
205if strResponse contains "Off" then
206  log "FileVault未設定"
207  set ocidFileVault to ("OFF") as text
208else
209  log "FileVault実行中"
210  set ocidFileVault to ("ON") as text
211end if
212
213##########################################
214#【13】ユーザー情報
215(* 一般的にはこの方法がいいでしょう
216##system infoを使う
217set recordSystemInfo to (system info) as record
218set strUserName to (short user name of recordSystemInfo) as text
219set strUserNameLong to (long user name of recordSystemInfo) as text
220set strUID to (user ID of recordSystemInfo) as text
221#ここだけエイリアスが戻り値
222set aliasHomeDirPath to (home directory of recordSystemInfo) as alias
223set strHomeDirPath to (POSIX path of aliasHomeDirPath) as text
224*)
225#ユーザー名ショート
226set ocidUserName to refMe's NSUserName()
227#ユーザー名ロング
228set ocidUserNameLong to refMe's NSFullUserName()
229#Unixパス ホームディレクトリ
230set ocidHomeDirPath to refMe's NSHomeDirectory()
231#NSURL ホームディレクトリ
232set ocidHomeDirPathURL to appFileManager's homeDirectoryForUser:(ocidUserName)
233set ocidHomeDirPath to ocidHomeDirPathURL's |path|()
234#コンソールのIDを取得する方法
235set strDevDirPath to ("/dev/console") as text
236set ocidDevDirPathStr to refMe's NSString's stringWithString:(strDevDirPath)
237set ocidDevDirPath to ocidDevDirPathStr's stringByStandardizingPath()
238#アトリビュートを取得して
239set listResponse to appFileManager's attributesOfItemAtPath:(ocidDevDirPath) |error| :(reference)
240if (item 2 of listResponse) = (missing value) then
241  log "正常処理"
242  set ocidAttarDict to (item 1 of listResponse)
243else if (item 2 of listResponse) ≠ (missing value) then
244  log (item 2 of listResponse)'s code() as text
245  log (item 2 of listResponse)'s localizedDescription() as text
246  return "エラーしました"
247end if
248#UIDを取得する
249set ocidUID to (ocidAttarDict's valueForKey:(refMe's NSFileOwnerAccountID))
250
251##########################################
252#【14】電源情報 pmset
253
254if (ocidModelName as text) contains "book" then
255  set listResponse to doGetPmset()
256  set ocidBatterySerialNumber to (item 1 of listResponse)
257  set ocidBatteryHealth to (item 2 of listResponse)
258  set ocidOptimized to (item 3 of listResponse)
259  log ocidBatterySerialNumber as text
260  log ocidBatteryHealth as text
261  log ocidOptimized as text
262  
263end if
264##########################################
265#【OUTPUT】HTMLにして表示
266
267set strHTML to ("<!DOCTYPE html><html lang=\"ja\"><head><title>システム情報</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><meta name=\"viewport\" content=\"width=720\"><style>body {margin: 10px;background-color: #FFFFFF;font-family: system-ui;}article {max-width: 720px;}.content {display: flex;flex-wrap: wrap;gap: 12px;}.module {width: 216px;height: 72px;border-radius: .5em;background-color: lightgrey;flex-direction: column;align-items: center;text-align: center;border: 1px solid #ccc;}.module p,.module h4,.module h5 {margin: 5px 0;}a {text-decoration: none;}small{font-size: 0.5rem;}</style><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no\"></head><body><header id=\"header\" class=\"body_header\"><div><h3>システム情報</h3></div></header><article id=\"article\" class=\"body_article\"><div class=\"content\"><div class=\"module\"><h4>コンピューター名<a href=\"x-apple.systempreferences:com.apple.SystemProfiler.AboutExtension?aboutSection\">⚒️</a></h4><h5>ComputerName</h5><p>" & ocidComputerName & "</p></div><div class=\"module\"><h4>Bonjour名<a href=\"x-apple.systempreferences:com.apple.Sharing-Settings.extension?Services_PersonalFileSharing\">⚒️</a></h4><h5>LocalHostName</h5><p>" & ocidLocalHostName & "</p></div><div class=\"module\"><h4>ホスト名<a href=\"x-apple.systempreferences:com.apple.SystemProfiler.AboutExtension?aboutSection\">⚒️</a></h4><h5>HostName</h5><p>" & ocidHostName & "</p></div><div class=\"module\"><h4>SMB名<a href=\"x-apple.systempreferences:com.apple.Sharing-Settings.extension?Services_WindowsSharing\">⚒️</a></h4><h5>NetBIOSName</h5><p>" & ocidNetBIOSName & "</p></div><div class=\"module\"><h4>Osバージョン<a href=\"x-apple.systempreferences:com.apple.SystemProfiler.AboutExtension?softwareSection\">⚒️</a></h4><h5>ProductVersion</h5><p>" & ocidProductVersion & "</p></div><div class=\"module\"><h4>ビルド番号<a href=\"x-apple.systempreferences:com.apple.SystemProfiler.AboutExtension?softwareSection\">⚒️</a></h4><h5>ProductBuildVersion</h5><p>" & ocidProductBuildVersion & "</p></div><div class=\"module\"><h4>モデル番号<a href=\"x-apple.systempreferences:com.apple.SystemProfiler.AboutExtension?aboutSection\">⚒️</a></h4><h5>machine_model</h5><p>" & ocidModelName & "</p></div><div class=\"module\"><h4>モデル名<a href=\"x-apple.systempreferences:com.apple.SystemProfiler.AboutExtension?aboutSection\">⚒️</a></h4><h5>ConfigCode</h5><p><small>" & ocidConfigCode & "</small></p></div><div class=\"module\"><h4>シリアルNO<a href=\"x-apple.systempreferences:com.apple.SystemProfiler.AboutExtension?aboutSection\">⚒️</a></h4><h5>serial_number</h5><p>" & ocidSerialNo & "</p></div><div class=\"module\"><h4>デバイスUUID<a href=\"file:///System/Applications/Utilities/System Information.app\">⚙️</a></h4><h5>platform_UUID</h5><p><small>" & ocidPlatform_UUID & "</small></p></div><div class=\"module\"><h4>BootRomバージョン<a href=\"file:///System/Applications/Utilities/System Information.app\">⚙️</a></h4><h5>boot_rom_version</h5><p>" & ocidBootRomVer & "</p></div><div class=\"module\"><h4>メモリー搭載量<a href=\"x-apple.systempreferences:com.apple.SystemProfiler.AboutExtension?aboutSection\">⚒️</a></h4><h5>physicalMemory</h5><p>" & numPhysicalMemory & "GB" & "</p></div><div class=\"module\"><h4>ディスク容量<a href=\"x-apple.systempreferences:com.apple.settings.Storage?storagePref\">🗄️</a></h4><h5>TotalSize</h5><p>" & numTotalSize & "GB" & "</p></div><div class=\"module\"><h4>ディスク残<a href=\"x-apple.systempreferences:com.apple.settings.Storage?storagePref\">🗄️</a></h4><h5>APFSContainerFree</h5><p>" & numContainerFree & "GB" & "</p></div><div class=\"module\"><h4>ディスクUUID<a href=\"file:///System/Applications/Utilities/System Information.app\">⚙️</a></h4><h5>DiskUUID</h5><p><small>" & ocidDiskUUID & "</small></p></div><div class=\"module\"><h4>FileVault実行<a href=\"x-apple.systempreferences:com.apple.settings.PrivacySecurity.extension?FileVault\">🗄️</a></h4><h5>FileVault</h5><p>" & ocidFileVault & "</p></div><div class=\"module\"><h4>暗号化<a href=\"x-apple.systempreferences:com.apple.settings.PrivacySecurity.extension?FileVault\">🗄️</a></h4><h5>Encryption</h5><p>" & ocidEncryption & "</p></div><div class=\"module\"><h4>起動ディスク名<a href=\"x-apple.systempreferences:com.apple.Startup-Disk-Settings.extension?StartupSearchGroup\">🗄️</a></h4><h5>VolumeName</h5><p>" & ocidVolumeName & "</p></div><div class=\"module\"><h4>システム保護SIP<a href=\"x-apple.systempreferences:com.apple.settings.PrivacySecurity.extension?Security\">🗄️</a></h4><h5>csrutil</h5><p>" & ocidSIP & "</p></div><div class=\"module\"><h4>XProtect</h4><h5>spctl</h5><p>" & ocidXProtect & "</p></div><div class=\"module\"><h4>TCCバージョン</h4><h5>TCC_Compatibility</h5><p>" & ocidTCCver & "</p></div><div class=\"module\"><h4>AppleKext</h4><h5>ExcludeList</h5><p>" & ocidKEXTver & "</p></div><div class=\"module\"><h4>XProtect</h4><h5>XProtect</h5><p>" & ocidMRTver & "</p></div><div class=\"module\"><h4>FileVault<a href=\"x-apple.systempreferences:com.apple.settings.PrivacySecurity.extension?FileVault\">🗄️</a></h4><h5>fdesetup</h5><p>" & ocidFileVault & "</p></div><div class=\"module\"><h4>ユーザー名<a href=\"x-apple.systempreferences:com.apple.Users-Groups-Settings.extension\">👤</a></h4><h5>NSUserName</h5><p>" & ocidUserName & "</p></div><div class=\"module\"><h4>ユーザーID<a href=\"x-apple.systempreferences:com.apple.Users-Groups-Settings.extension\">👤</a></h4><h5>AccountID</h5><p>" & ocidUID & "</p></div><div class=\"module\"><h4> </h4><h5> </h5><p> </p></div><div class=\"module\"><h4>バッテリーシリアル<a href=\"file:///System/Applications/Utilities/System Information.app\">⚙️</a></h4><h5>Hardware Serial Number</h5><p>" & ocidBatterySerialNumber & "</p></div><div class=\"module\"><h4>バッテリー最適化<a href=\"x-apple.systempreferences:com.apple.Battery-Settings.extension*BatteryPreferences?batteryhealth\">🔋</a></h4><h5>Optimized Battery</h5><p>" & ocidOptimized & "</p></div><div class=\"module\"><h4>バッテリー状態<a href=\"x-apple.systempreferences:com.apple.Battery-Settings.extension*BatteryPreferences?currentSource\">🔋</a></h4><h5>BatteryHealth</h5><p>" & ocidBatteryHealth & "</p></div></div></article><footer id=\"footer\" class=\"body_footer\"><div><p><a href=\"https://quicktimer.cocolog-nifty.com/icefloe/2024/06/post-9cf776.html\" target=\"_blank\">AppleScriptで生成しました</a></p></div></footer></body></html>") as text
268
269set ocidSaveFilePathURL to doSaveText(strHTML)
270##HTMLを開く
271set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
272set boolDone to appSharedWorkspace's openURL:(ocidSaveFilePathURL)
273
274##########################################
275#HTMLとして保存
276to doSaveText(argText)
277  ###ディレクトリ
278  set appFileManager to refMe's NSFileManager's defaultManager()
279  set ocidTempDirURL to appFileManager's temporaryDirectory()
280  set ocidUUID to refMe's NSUUID's alloc()'s init()
281  set ocidUUIDString to ocidUUID's UUIDString
282  set ocidSaveDirPathURL to ocidTempDirURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:true
283  #
284  set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
285  # 777-->511 755-->493 700-->448 766-->502
286  ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
287  set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference)
288  ###パス
289  set strFileName to "device_info.html" as text
290  set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strFileName) isDirectory:false
291  #
292  set ocidSaveString to refMe's NSString's stringWithString:(argText)
293  set listDone to ocidSaveString's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error| :(reference)
294  if (item 1 of listDone) is true then
295    log "正常処理"
296    return ocidSaveFilePathURL
297  else if (item 2 of listDone) ≠ (missing value) then
298    log (item 2 of listDone)'s code() as text
299    log (item 2 of listDone)'s localizedDescription() as text
300    log "エラーしました"
301    return false
302  end if
303  
304  
305end doSaveText
306return
307
308##########################################
309#【14】電源情報 pmset
310
311to doGetPmset()
312  set strCommandText to ("/bin/zsh -c '/usr/bin/pmset -g batt -xml'") as text
313  log strCommandText
314  try
315    set strResponse to (do shell script strCommandText) as text
316  on error
317    log "コマンドでエラーしました"
318    return false
319  end try
320  #戻り値をストリングに
321  set ocidPlistStrings to refMe's NSString's stringWithString:(strResponse)
322  #NSDATAにして
323  set ocidPlisStringstData to ocidPlistStrings's dataUsingEncoding:(refMe's NSUTF8StringEncoding)
324  #PLIST初期化して
325  set ocidFormat to (refMe's NSPropertyListXMLFormat_v1_0)
326  set listResponse to refMe's NSPropertyListSerialization's propertyListWithData:ocidPlisStringstData options:(0) format:(ocidFormat) |error| :(reference)
327  if (item 2 of listResponse) = (missing value) then
328    log "正常処理"
329    set ocidPlistDict to (item 1 of listResponse)
330  else if (item 2 of listResponse) ≠ (missing value) then
331    log (item 2 of listResponse)'s code() as text
332    log (item 2 of listResponse)'s localizedDescription() as text
333    return "エラーしました"
334  end if
335  set ocidBatterySerialNumber to ocidPlistDict's valueForKey:("Hardware Serial Number")
336  set ocidBatteryHealth to ocidPlistDict's valueForKey:("BatteryHealth")
337  set ocidOptimized to ocidPlistDict's valueForKey:("Optimized Battery Charging Engaged")
338  
339  return {ocidBatterySerialNumber, ocidBatteryHealth, ocidOptimized}
340  
341end doGetPmset
342
343##########################################
344# 【13】 アップデート softwareupdate
345set strCommandText to ("/bin/bash -c '/usr/sbin/softwareupdate  --list --include-config-data 2>&1'") as text
346log strCommandText
347set strResponse to (do shell script strCommandText) as text
348if strResponse contains "No new software available" then
349  log "最新です"
350else
351  log "アップデートがあります"
352end if
353
354##########################################
355#【6】ディスク キャパ と 残 diskutil
356to doGetVolumeInfo()
357  set strCommandText to "/usr/sbin/diskutil info -plist /" as text
358  log strCommandText
359  try
360    set strResponse to (do shell script strCommandText) as text
361  on error
362    log "コマンドでエラーしました"
363    return false
364  end try
365  #戻り値をストリングに
366  set ocidPlistStrings to refMe's NSString's stringWithString:(strResponse)
367  #NSDATAにして
368  set ocidPlisStringstData to ocidPlistStrings's dataUsingEncoding:(refMe's NSUTF8StringEncoding)
369  #PLIST初期化して
370  set ocidFormat to (refMe's NSPropertyListXMLFormat_v1_0)
371  set listResponse to refMe's NSPropertyListSerialization's propertyListWithData:ocidPlisStringstData options:(0) format:(ocidFormat) |error| :(reference)
372  if (item 2 of listResponse) = (missing value) then
373    log "正常処理"
374    set ocidPlistDict to (item 1 of listResponse)
375  else if (item 2 of listResponse) ≠ (missing value) then
376    log (item 2 of listResponse)'s code() as text
377    log (item 2 of listResponse)'s localizedDescription() as text
378    return "エラーしました"
379  end if
380  #
381  set ocidVolumeName to (ocidPlistDict's valueForKey:"VolumeName")
382  set ocidDiskUUID to (ocidPlistDict's valueForKey:"DiskUUID")
383  set ocidVolumeUUID to (ocidPlistDict's valueForKey:"VolumeUUID")
384  set ocidFilesystemName to (ocidPlistDict's valueForKey:"FilesystemName")
385  set ocidFileVault to (ocidPlistDict's valueForKey:"FileVault")
386  set ocidEncryption to (ocidPlistDict's valueForKey:"Encryption")
387  #サイズ
388  set ocidTotalSize to (ocidPlistDict's valueForKey:"TotalSize")
389  set intGB to "1073741824" as integer
390  set ocidGB to (refMe's NSNumber's numberWithInteger:intGB)
391  set numTotalSize to ((ocidTotalSize's doubleValue as real) / (ocidGB's doubleValue as real)) as integer
392  #残
393  set ocidAPFSContainerFree to (ocidPlistDict's valueForKey:"APFSContainerFree")
394  set intGB to "1073741824" as integer
395  set ocidGB to (refMe's NSNumber's numberWithInteger:intGB)
396  set numContainerFree to ((ocidAPFSContainerFree's doubleValue as real) / (ocidGB's doubleValue as real)) as integer
397  
398  return {ocidVolumeName, ocidFileVault, ocidEncryption, numTotalSize, numContainerFree, ocidDiskUUID}
399end doGetVolumeInfo
400
401##########################################
402#【4】モデル名 ConfigCode
403to doGetConfigCode(argSerialNo)
404  #ConfigCodeになる4文字を取り出して
405  set intTextlength to (argSerialNo's |length|) as integer
406  set ocidRenge to refMe's NSMakeRange((intTextlength - 4), 4)
407  set strConfigCode to (argSerialNo's substringWithRange:(ocidRenge)) as text
408  #URL整形
409  set ocidURLComponents to refMe's NSURLComponents's alloc()'s init()
410  #スキーム を追加
411  ocidURLComponents's setScheme:("https")
412  #ホスト追加
413  ocidURLComponents's setHost:("support-sp.apple.com")
414  #パスを追加(setHostじゃないよ)
415  ocidURLComponents's setPath:("/sp/product")
416  #CC config Codeクエリーを追加
417  set ocidComponentArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
418  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("cc") value:(strConfigCode)
419  ocidComponentArray's addObject:(ocidQueryItem)
420  #langクエリーを追加
421  set ocidLocale to refMe's NSLocale's currentLocale()
422  set ocidLocaleID to ocidLocale's localeIdentifier()
423  set ocidQueryItem to (refMe's NSURLQueryItem's alloc()'s initWithName:("lang") value:(ocidLocaleID))
424  (ocidComponentArray's addObject:(ocidQueryItem))
425  #検索クエリーとして追加
426  (ocidURLComponents's setQueryItems:(ocidComponentArray))
427  #コンポーネントをURLに展開
428  set ocidURL to ocidURLComponents's |URL|()
429  #XML読み込み
430  set ocidOption to (refMe's NSXMLDocumentTidyXML)
431  set listResponse to refMe's NSXMLDocument's alloc()'s initWithContentsOfURL:(ocidURL) options:(ocidOption) |error| :(reference)
432  if (item 2 of listResponse) = (missing value) then
433    log "正常処理"
434    set ocidReadXMLDoc to (item 1 of listResponse)
435  else if (item 2 of listResponse) ≠ (missing value) then
436    log (item 2 of listResponse)'s code() as text
437    log (item 2 of listResponse)'s localizedDescription() as text
438    log "エラーしました"
439    return false
440  end if
441  #ROOTエレメント
442  set ocidRootElement to ocidReadXMLDoc's rootElement()
443  #configCodeからモデル名を取得
444  set ocidConfigCode to (ocidRootElement's elementsForName:("configCode"))'s firstObject()
445  set ocidConfigCode to ocidConfigCode's stringValue()
446  return ocidConfigCode
447end doGetConfigCode
448
449##########################################
450#【3】system_profiler json 
451to doSPHardwareDataTypeJson(argKeyPath)
452  set strCommandText to ("/bin/zsh -c '/usr/sbin/system_profiler SPHardwareDataType -json'") as text
453  log strCommandText
454  set strResponse to (do shell script strCommandText) as text
455  set ocidJsonStrings to refMe's NSString's stringWithString:(strResponse)
456  set ocidJsonData to ocidJsonStrings's dataUsingEncoding:(refMe's NSUTF8StringEncoding)
457  set ocidOption to (refMe's NSJSONReadingMutableContainers)
458  set listResponse to (refMe's NSJSONSerialization's JSONObjectWithData:(ocidJsonData) options:(ocidOption) |error| :(reference))
459  if (item 2 of listResponse) = (missing value) then
460    log "正常処理"
461    set ocidJsonDict to (item 1 of listResponse)
462  else if (item 2 of listResponse) ≠ (missing value) then
463    log (item 2 of listResponse)'s code() as text
464    log (item 2 of listResponse)'s localizedDescription() as text
465    return "エラーしました"
466  end if
467  set ocidValue to (ocidJsonDict's valueForKeyPath:(argKeyPath))
468  return ocidValue
469end doSPHardwareDataTypeJson
470
471
472##########################################
473#テキストパスからバージョンを取得
474to doGetVersion(argFilePathStrings)
475  #パス
476  set strFilePath to (argFilePathStrings) as text
477  set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
478  set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
479  set ocidFilePathURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:(false)
480  #
481  set ocidAppBundle to refMe's NSBundle's bundleWithURL:(ocidFilePathURL)
482  set ocidInfoDict to ocidAppBundle's infoDictionary()
483  set ocidCFBundleVersion to (ocidInfoDict's valueForKey:("CFBundleVersion"))
484  return ocidCFBundleVersion
485end doGetVersion
486
487
488##########################################
489#plistから指定のキーの値を取得する
490to doGetPlistValue(argFilePathStrings, argKey)
491  #パス
492  set strFilePath to (argFilePathStrings) as text
493  set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
494  set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
495  set ocidFilePathURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:(false)
496  #レコードを読み込み
497  set listResponse to refMe's NSDictionary's alloc()'s initWithContentsOfURL:(ocidFilePathURL) |error| :(reference)
498  if (item 2 of listResponse) = (missing value) then
499    log "正常処理"
500    set ocidPlistDict to (item 1 of listResponse)
501  else if (item 2 of listResponse) ≠ (missing value) then
502    log (item 2 of listResponse)'s code() as text
503    log (item 2 of listResponse)'s localizedDescription() as text
504    log "エラーしました"
505    return false
506  end if
507  set ocidValue to ocidPlistDict's valueForKey:(argKey)
508  if ocidValue = (missing value) then
509    return false
510  else
511    return ocidValue
512  end if
513end doGetPlistValue
514
515
516
AppleScriptで生成しました

|

[ioreg]ロジックボード番号を取得する


あくまでも参考にしてください

【スクリプトエディタで開く】 |

サンプルソース(参考)
行番号ソース
001#! /usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003# バイナリーで戻り値があるロジックボード番号の取得
004# com.cocolog-nifty.quicktimer.icefloe
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.6"
007use framework "Foundation"
008use scripting additions
009
010property refMe : a reference to current application
011
012
013set appFileManager to refMe's NSFileManager's defaultManager()
014#####################################
015######ファイル保存先
016#####################################
017set ocidUserLibraryPathArray to (appFileManager's URLsForDirectory:(refMe's NSDocumentDirectory) inDomains:(refMe's NSUserDomainMask))
018set ocidFilePathURL to ocidUserLibraryPathArray's firstObject()
019set ocidSaveDirPathURL to ocidFilePathURL's URLByAppendingPathComponent:("Apple/IOreg") isDirectory:(true)
020############################
021###フォルダを作る
022set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
023ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
024set listDone to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference)
025if (item 1 of listDone) is true then
026  log "正常処理"
027else if (item 2 of listDone) ≠ (missing value) then
028  log (item 2 of listDone)'s code() as text
029  log (item 2 of listDone)'s localizedDescription() as text
030  return "フォルダ エラーしました"
031end if
032
033#####################################
034######PLISTパス
035#####################################
036set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:("IOPlatformExpertDevice.plist") isDirectory:(false)
037set strPlistFilePath to (ocidSaveFilePathURL's |path|()) as text
038###古いファイルはゴミ箱に
039set listDone to (appFileManager's trashItemAtURL:(ocidSaveFilePathURL) resultingItemURL:(ocidSaveFilePathURL) |error| :(reference))
040if (item 1 of listDone) is true then
041  log "正常処理"
042else if (item 2 of listDone) ≠ (missing value) then
043  log (item 2 of listDone)'s code() as text
044  log (item 2 of listDone)'s localizedDescription() as text
045  return "フォルダ エラーしました"
046end if
047#####################################
048set strCommandText to "/usr/sbin/ioreg -c IOPlatformExpertDevice -a " as text
049set strPlistData to (do shell script strCommandText) as text
050###戻り値をストリングに
051set ocidPlistStrings to refMe's NSString's stringWithString:(strPlistData)
052###NSDATAにして
053set ocidPlistData to ocidPlistStrings's dataUsingEncoding:(refMe's NSUTF8StringEncoding)
054###ファイルに書き込み(使い回し用)-->不要な場合は削除して
055set ocidOption to (refMe's NSDataWritingAtomic)
056set listDone to (ocidPlistData's writeToURL:(ocidSaveFilePathURL) options:(ocidOption) |error| :(reference))
057if (item 1 of listDone) is true then
058  log "正常処理"
059else if (item 2 of listDone) ≠ (missing value) then
060  log (item 2 of listDone)'s code() as text
061  log (item 2 of listDone)'s localizedDescription() as text
062  return "ファイル保存エラーしました"
063end if
064
065###PLIST初期化して
066set listResponse to refMe's NSPropertyListSerialization's propertyListWithData:(ocidPlistData) options:0 format:(refMe's NSPropertyListXMLFormat_v1_0) |error| :(reference)
067if (item 2 of listResponse) = (missing value) then
068  log "正常処理"
069  set ocidPlistDataArray to (item 1 of listResponse)
070else if (item 2 of listResponse) ≠ (missing value) then
071  log (item 2 of listResponse)'s code() as text
072  log (item 2 of listResponse)'s localizedDescription() as text
073  return "NSDATAエラーしました"
074end if
075####serial-number"
076set ocidObjectArray to ocidPlistDataArray's valueForKeyPath:("IORegistryEntryChildren.serial-number")
077set ocidValue to ocidObjectArray's firstObject()
078set ocidSerialNumber to refMe's NSString's alloc()'s initWithData:(ocidValue) encoding:(refMe's NSUTF8StringEncoding)
079####
080set ocidObjectArray to ocidPlistDataArray's valueForKeyPath:("IORegistryEntryChildren.mlb-serial-number")
081set ocidValue to ocidObjectArray's firstObject()
082set ocidMainLogicBoardSerialNumber to refMe's NSString's alloc()'s initWithData:(ocidValue) encoding:(refMe's NSUTF8StringEncoding)
083####
084set ocidObjectArray to ocidPlistDataArray's valueForKeyPath:("IORegistryEntryChildren.model")
085set ocidValue to ocidObjectArray's firstObject()
086set ocidModelName to refMe's NSString's alloc()'s initWithData:(ocidValue) encoding:(refMe's NSUTF8StringEncoding)
087####
088set ocidObjectArray to ocidPlistDataArray's valueForKeyPath:("IORegistryEntryChildren.model-number")
089set ocidValue to ocidObjectArray's firstObject()
090set ocidModelNO to refMe's NSString's alloc()'s initWithData:(ocidValue) encoding:(refMe's NSUTF8StringEncoding)
091####
092set ocidObjectArray to ocidPlistDataArray's valueForKeyPath:("IORegistryEntryChildren.regulatory-model-number")
093set ocidValue to ocidObjectArray's firstObject()
094set ocidRegModelNO to refMe's NSString's alloc()'s initWithData:(ocidValue) encoding:(refMe's NSUTF8StringEncoding)
095####
096set ocidObjectArray to ocidPlistDataArray's valueForKeyPath:("IORegistryEntryChildren.region-info")
097set ocidValue to ocidObjectArray's firstObject()
098set ocidRegionInfo to refMe's NSString's alloc()'s initWithData:(ocidValue) encoding:(refMe's NSUTF8StringEncoding)
099###各種値を取得する
100set ocidDeviceUUID to (ocidPlistDataArray's valueForKeyPath:"IORegistryEntryChildren.IOPlatformUUID")
101set ocidDeviceSerialNumber to (ocidPlistDataArray's valueForKeyPath:"IORegistryEntryChildren.IOPlatformSerialNumber")
102set ocidDeviceEntryName to (ocidPlistDataArray's valueForKeyPath:"IORegistryEntryChildren.IORegistryEntryName")
103###モデル名はNSDATAなのでテキストに解凍する
104set ocidModelArray to (ocidPlistDataArray's valueForKeyPath:("IORegistryEntryChildren.model"))
105set ocidModel to ocidModelArray's firstObject()
106###まぁエラーになるとは思えないが
107if (className() of ocidModel as text) is "NSNull" then
108  set strCommandText to ("/usr/sbin/sysctl -n hw.model") as text
109  set strModelStr to (do shell script strCommandText) as text
110else
111  set ocidModelStr to refMe's NSString's alloc()'s initWithData:(ocidModel) encoding:(refMe's NSUTF8StringEncoding)
112  set strModelStr to ocidModelStr as text
113end if
114###OSのバージョン
115set ocidSystemPathArray to (appFileManager's URLsForDirectory:(refMe's NSCoreServiceDirectory) inDomains:(refMe's NSSystemDomainMask))
116set ocidCoreServicePathURL to ocidSystemPathArray's firstObject()
117set ocidPlistFilePathURL to ocidCoreServicePathURL's URLByAppendingPathComponent:"SystemVersion.plist"
118set ocidPlistDict to refMe's NSMutableDictionary's alloc()'s initWithContentsOfURL:(ocidPlistFilePathURL)
119set strOSversion to (ocidPlistDict's valueForKey:("ProductVersion")) as text
120
121set strIconPath to "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/FinderIcon.icns" as text
122set aliasIconPath to POSIX file strIconPath as alias
123
124set strAns to ("デバイス型番:" & ocidDeviceEntryName & "\n") as text
125set strAns to (strAns & "モデル番号:" & strModelStr & "\n") as text
126set strAns to (strAns & "デバイスUUID:" & ocidDeviceUUID & "\n") as text
127set strAns to (strAns & "シリアル番号:" & ocidDeviceSerialNumber & "\n") as text
128set strAns to (strAns & "OSバージョン:" & strOSversion & "\n") as text
129set strAns to (strAns & "----------\n") as text
130set strAns to (strAns & "シリアル番号:" & ocidSerialNumber & "\n") as text
131set strAns to (strAns & "ロジックボード番号:" & ocidMainLogicBoardSerialNumber & "\n") as text
132set strAns to (strAns & "モデル名:" & ocidModelName & "\n") as text
133set strAns to (strAns & "モデル番号:" & ocidModelNO & "\n") as text
134set strAns to (strAns & "規制モデル番号:" & ocidRegModelNO & "\n") as text
135set strAns to (strAns & "対象国:" & ocidRegionInfo & "\n") as text
136
137
138#####ダイアログを前面に
139tell current application
140  set strName to name as text
141end tell
142####スクリプトメニューから実行したら
143if strName is "osascript" then
144  tell application "Finder" to activate
145else
146  tell current application to activate
147end if
148
149###ダイアログ
150set recordResult to (display dialog "ioreg 戻り値です" with title "モデル番号" default answer strAns buttons {"クリップボードにコピー", "キャンセル", "OK"} default button "OK" giving up after 20 with icon aliasIconPath without hidden answer)
151###クリップボードコピー
152if button returned of recordResult is "クリップボードにコピー" then
153  set strText to text returned of recordResult as text
154  ####ペーストボード宣言
155  set appPasteboard to refMe's NSPasteboard's generalPasteboard()
156  set ocidText to (refMe's NSString's stringWithString:(strText))
157  appPasteboard's clearContents()
158  appPasteboard's setString:(ocidText) forType:(refMe's NSPasteboardTypeString)
159end if
AppleScriptで生成しました

|

IORegistryExplorerを開く


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use framework "UniformTypeIdentifiers"
use scripting additions
property refMe : a reference to current application

set strBundleID to "com.apple.IORegistryExplorer" as text

set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
set ocidAppBundle to (refMe's NSBundle's bundleWithIdentifier:(strBundleID))
if ocidAppBundle ≠ (missing value) then
  set ocidAppPathURL to ocidAppBundle's bundleURL()
else if ocidAppBundle = (missing value) then
  set ocidAppPathURL to (appSharedWorkspace's URLForApplicationWithBundleIdentifier:(strBundleID))
end if
if ocidAppPathURL = (missing value) then
  tell application "Finder"
    try
      set aliasAppApth to (application file id strBundleID) as alias
    on error
      set aliasIconPath to POSIX file "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/AlertNoteIcon.icns"
      set strMes to ("https://developer.apple.com/download/all/?q=Additional%20Tools%20for%20Xcode") as text
      set recordResult to (display dialog "【エラー】アプリケーションが見つかりませんでした" with title "アプリケーションが見つかりませんでした\rダウンロードはデベロッパーサイトから" default answer strMes buttons {"リンクを開く", "終了"} default button "リンクを開く" cancel button "終了" giving up after 20 with icon aliasIconPath without hidden answer)
      if button returned of recordResult is "リンクを開く" then
tell application "Finder"
open location strMes
end tell
      end if
return "アプリケーションが見つかりませんでした"
    end try
  end tell
  set strAppPath to POSIX path of aliasAppApth as text
  set strAppPathStr to refMe's NSString's stringWithString:(strAppPath)
  set strAppPath to strAppPathStr's stringByStandardizingPath()
  set ocidAppPathURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:true
end if

set ocidOpenConfig to refMe's NSWorkspaceOpenConfiguration's configuration
(ocidOpenConfig's setActivates:(refMe's NSNumber's numberWithBool:true))
(appSharedWorkspace's openApplicationAtURL:(ocidAppPathURL) configuration:(ocidOpenConfig) completionHandler:(missing value))


|

scutilの情報を取得表示します


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use scripting additions

property refMe : a reference to current application

#####最初のリスト取得
set strSubKey to doListSelect()
#####最初のコマンド実行
doCommand(strSubKey)

#########################
##リスト 選択
#########################
to doListSelect()
  set strCommandText to ("/bin/echo list | /usr/sbin/scutil") as text
  log strCommandText
  set strResponse to (do shell script strCommandText) as text
  set listChooseList to {} as list
  
  set AppleScript's text item delimiters to "\r"
  set listResponse to every text item of strResponse
  set AppleScript's text item delimiters to ""
  
  repeat with itemResponse in listResponse
    set AppleScript's text item delimiters to "="
    set listTmpSubKey to every text item of itemResponse
    set AppleScript's text item delimiters to ""
    set strSubKey to (item 2 of listTmpSubKey) as text
    set end of listChooseList to strSubKey
  end repeat
  
  try
    ###ダイアログを前面に出す
    tell current application
      set strName to name as text
    end tell
    ####スクリプトメニューから実行したら
    if strName is "osascript" then
      tell application "Finder"
activate
      end tell
    else
      tell current application
activate
      end tell
    end if
    set listResponse to (choose from list listChooseList with title "選んでください" with prompt "設定値を表示します\r選んでください" default items (item 1 of listChooseList) OK button name "OK" cancel button name "キャンセル" without multiple selections allowed and empty selection allowed) as list
  on error
    log "エラーしました"
return "エラーしました"
  end try
  if (item 1 of listResponse) is false then
return "キャンセルしました"
  end if
  
  set theResponse to (item 1 of listResponse) as text
end doListSelect

#########################
##コマンド実行
#########################
to doCommand(argSubKey)
  set strCommandText to ("/bin/echo \"show" & argSubKey & "\" | /usr/sbin/scutil") as text
  log strCommandText
  set strResponse to (do shell script strCommandText) as text
  ###
doDialog(strResponse)
end doCommand

#########################
##戻り値表示
#########################
to doDialog(argResponse)
  tell current application
    set strName to name as text
  end tell
  ####スクリプトメニューから実行したら
  if strName is "osascript" then
    tell application "Finder"
      activate
    end tell
  else
    tell current application
      activate
    end tell
  end if
  set aliasIconPath to POSIX file "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/BookmarkIcon.icns" as alias
  try
    set recordResponse to (display dialog "設定内容" with title "設定内容確認" default answer argResponse buttons {"クリップボードにコピー", "終了", "もう一度"} default button "終了" cancel button "終了" with icon aliasIconPath giving up after 20 without hidden answer)
    
  on error
    log "エラーしました"
return "エラーしました"
  end try
  if true is equal to (gave up of recordResponse) then
return "時間切れですやりなおしてください"
  end if
  if "終了" is equal to (button returned of recordResponse) then
    set strResponse to (text returned of recordResponse) as text
return strResponse
  else if button returned of recordResponse is "クリップボードにコピー" then
    set strText to text returned of recordResponse as text
    ####ペーストボード宣言
    set appPasteboard to refMe's NSPasteboard's generalPasteboard()
    ##結果をペーストボードにテキストで入れる
    set ocidText to (refMe's NSString's stringWithString:(strText))
appPasteboard's clearContents()
appPasteboard's setString:(ocidText) forType:(refMe's NSPasteboardTypeString)
return strText
  else if button returned of recordResponse is "もう一度" then
    set strSubKey to doListSelect()
doCommand(strSubKey)
  else
    log "キャンセルしました"
return "キャンセルしました"
  end if
return
end doDialog



|

[nettop]接続中のネットワークサービスの一覧を出力する(修正)


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions


property refMe : a reference to current application


set strCommandText to "/usr/bin/nettop -x -n" as text

tell application "Terminal"
  launch
  activate
  set objTabWindows to do script "\n\n"
  tell objTabWindows
    activate
  end tell
  tell front window
    activate
    set numWidowID to id as integer
  end tell
  
  tell window id numWidowID
    set size to {720, 270}
    set position to {360, 25}
    set origin to {360, 500}
    set frame to {360, 500, 1080, 875}
    set bounds to {360, 25, 1080, 295}
  end tell
  tell objTabWindows
    activate
do script strCommandText in objTabWindows
  end tell
end tell



set strCommandText to "/usr/bin/nettop -m tcp" as text

tell application "Terminal"
  launch
  activate
  set objTabWindows to do script "\n\n"
  tell objTabWindows
    activate
  end tell
  tell front window
    activate
    set numWidowID to id as integer
  end tell
  
  tell window id numWidowID
    set size to {720, 300}
    set position to {360, 300}
    set origin to {360, 300}
    set frame to {360, 300, 1080, 600}
    set bounds to {360, 300, 1080, 600}
  end tell
  tell objTabWindows
    activate
do script strCommandText in objTabWindows
  end tell
end tell
set strCommandText to "/usr/bin/nettop -t wifi" as text

tell application "Terminal"
  launch
  activate
  set objTabWindows to do script "\n\n"
  tell objTabWindows
    activate
  end tell
  tell front window
    activate
    set numWidowID to id as integer
  end tell
  
  tell window id numWidowID
    set size to {720, 300}
    set position to {360, 600}
    set origin to {360, 0}
    set frame to {360, 0, 1080, 300}
    set bounds to {360, 600, 1080, 900}
  end tell
  tell objTabWindows
    activate
do script strCommandText in objTabWindows
  end tell
end tell


set strCommandText to "/usr/bin/man -a nettop"

tell application "Terminal"
  set objTabWindows to do script "\n\n"
  tell front window
    activate
    set numWidowID to id as integer
  end tell
  tell window id numWidowID
    activate
    set size to {360, 870}
    set position to {0, 25}
    set origin to {0, 0}
    set frame to {0, 0, 360, 875}
    set bounds to {0, 25, 360, 900}
  end tell
  tell objTabWindows
    activate
do script strCommandText in objTabWindows
  end tell
end tell
return


|

IPアドレス取得(汎用)


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use scripting additions

property refMe : a reference to current application


####################################
######Macアドレス取得
###コマンド生成 実行
set strCommandText to "/usr/sbin/networksetup -listallnetworkservices"
set strResults to (do shell script strCommandText) as text
###戻り値を改行でリストに
set ocidListallnetworkservices to refMe's NSString's stringWithString:(strResults)
set ocidChrSet to refMe's NSCharacterSet's characterSetWithCharactersInString:("\r")
set ocidNetworkNameArray to ocidListallnetworkservices's componentsSeparatedByCharactersInSet:(ocidChrSet)
(ocidNetworkNameArray's removeObjectAtIndex:(0))
set strMacAdd to "" as text
repeat with itemNetworkName in ocidNetworkNameArray
  set strServiceName to itemNetworkName as text
  ###コマンド生成 実行
  set strCommandText to "/usr/sbin/networksetup -getinfo \"" & strServiceName & "\"" as text
  set strResponse to (do shell script strCommandText) as text
  ###戻り値を改行でリストに
  set ocidResponse to (refMe's NSString's stringWithString:(strResponse))
  set ocidChrSet to (refMe's NSCharacterSet's characterSetWithCharactersInString:("\r"))
  set ocidResponseArray to (ocidResponse's componentsSeparatedByCharactersInSet:(ocidChrSet))
  repeat with itemResponse in ocidResponseArray
    set strResponse to itemResponse as text
    if strResponse contains "Wi-Fi ID" then
      set strMacAdd to strServiceName & ":" & strResponse & "\r" & strMacAdd as text
    else if strResponse contains "Ethernet Address" then
      set strMacAdd to strServiceName & ":" & strResponse & "\r" & strMacAdd as text
    end if
  end repeat
end repeat

####################################
###### IPアドレス取得
set strURL to "https://www.cloudflare.com/cdn-cgi/trace?json" as text
set ocidURL to refMe's NSURL's URLWithString:(strURL)
###URLをリクエスト
set listContents to refMe's NSString's stringWithContentsOfURL:(ocidURL) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
set ocidContents to item 1 of listContents
###改行で
set ocidCharacterSet to refMe's NSCharacterSet's newlineCharacterSet
###リスト化して
set ocidStringArray to ocidContents's componentsSeparatedByCharactersInSet:(ocidCharacterSet)
###IPアドレスを取得
repeat with itemStringArray in ocidStringArray
  if (itemStringArray as text) starts with "ip" then
    set ocidIPArray to (itemStringArray's componentsSeparatedByString:"=")
    set ocidIPAdd to (ocidIPArray's objectAtIndex:1)
  end if
end repeat
###正順 IPアドレス
set strIPAdd to ocidIPAdd as text
set ocidIpAddArray to ocidIPAdd's componentsSeparatedByString:(".")
set ocidIpAddArrayRev to (ocidIpAddArray's reverseObjectEnumerator())'s allObjects()
###逆順 IPアドレス
set strIPAddRev to (ocidIpAddArrayRev's componentsJoinedByString:(".")) as text
####################################
###### URL部分
set strURLrev to ("https://cloudflare-dns.com/dns-query?name=" & strIPAddRev & ".in-addr.arpa&type=PTR") as text
set ocidURLrevStr to refMe's NSString's stringWithString:(strURLrev)
set ocidURLrevURL to refMe's NSURL's URLWithString:(ocidURLrevStr)
####################################
###### URLRequest部分
set ocidURLRequest to refMe's NSMutableURLRequest's alloc()'s init()
ocidURLRequest's setHTTPMethod:("GET")
ocidURLRequest's setURL:(ocidURLrevURL)
ocidURLRequest's addValue:("application/json") forHTTPHeaderField:("Content-Type")
ocidURLRequest's addValue:("application/dns-json") forHTTPHeaderField:("accept")
################################################
repeat 5 times
  ###### データ取得
  set listServerResponse to refMe's NSURLConnection's sendSynchronousRequest:(ocidURLRequest) returningResponse:(missing value) |error|:(reference)
  ###取得JSONデータ
  set ocidJsonResponse to (item 1 of listServerResponse)
  ####取得データをJSONで確定
  set listJsonData to refMe's NSJSONSerialization's JSONObjectWithData:ocidJsonResponse options:(refMe's NSJSONReadingMutableContainers) |error|:(reference)
  set ocidJsonData to (item 1 of listJsonData)
  ####レコードに格納
  set ocidJsonDict to refMe's NSDictionary's alloc()'s initWithDictionary:(ocidJsonData)
  set numStatus to (ocidJsonDict's valueForKey:("Status")) as integer
  if numStatus = 0 then
    set ocidRevHost to (ocidJsonDict's valueForKey:("Question"))'s valueForKey:("name")
    set strRevHost to ocidRevHost as text
    exit repeat
  else
    delay 1
  end if
end repeat
if numStatus ≠ 0 then
  display alert "データの取得に失敗しました" giving up after 3
return "データの取得に失敗しました"
end if
###ホスト名解決
set strCommandText to ("/usr/bin/dig -x " & strIPAdd & " +short")
set strHostName to (do shell script strCommandText) as text

set strCommandText to ("/sbin/ifconfig | grep \"inet.*broadcast\" | awk '{print $2}'") as text
set strLocalIP to (do shell script strCommandText) as text

set strAns to ("ホスト名:" & strHostName & "\rグローバルIP:" & strIPAdd & "\r逆引き:" & strRevHost & "\rローカルIP:" & strLocalIP & "\r" & strMacAdd) as text
##############################
#####ダイアログを前面に出す
##############################
tell current application
  set strName to name as text
end tell
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder"
    activate
  end tell
else
  tell current application
    activate
  end tell
end if
################################
######ダイアログ
################################
set aliasIconPath to POSIX file "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/BookmarkIcon.icns" as alias
try
  set recordResponse to (display dialog strAns with title "IPアドレス" default answer strAns buttons {"クリップボードにコピー", "OK", "キャンセル"} default button "OK" cancel button "キャンセル" with icon aliasIconPath giving up after 20 without hidden answer)
on error
  log "エラーしました"
return "エラーしました"
end try
if true is equal to (gave up of recordResponse) then
return "時間切れですやりなおしてください"
end if
if "OK" is equal to (button returned of recordResponse) then
  set strResponse to (text returned of recordResponse) as text
else if button returned of recordResponse is "クリップボードにコピー" then
  set strText to text returned of recordResponse as text
  ####ペーストボード宣言
  set appPasteboard to refMe's NSPasteboard's generalPasteboard()
  ##結果をペーストボードにテキストで入れる
  set ocidText to (refMe's NSString's stringWithString:(strText))
appPasteboard's clearContents()
appPasteboard's setString:(ocidText) forType:(refMe's NSPasteboardTypeString)
return strText
else
  log "キャンセルしました"
return "キャンセルしました" & strText
end if





|

その他のカテゴリー

Accessibility Acrobat Acrobat 2020 Acrobat AddOn Acrobat Annotation Acrobat ARMDC Acrobat AV2 Acrobat BookMark Acrobat Classic Acrobat DC Acrobat Dialog Acrobat Distiller Acrobat Form Acrobat JS Acrobat Manifest Acrobat Menu Acrobat Open Acrobat Plugin Acrobat Preferences Acrobat Preflight Acrobat python Acrobat Reader Acrobat SCA Acrobat SCA Updater Acrobat Sequ Acrobat Sign Acrobat Stamps Acrobat Watermark Acrobat Windows Acrobat Windows Reader Admin Admin Account Admin Apachectl Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Mobileconfig Admin Permission Admin Pkg Admin Power Management Admin Printer Admin SetUp Admin SMB Admin Support Admin System Information Admin Tools Admin Users Admin Volumes Adobe Adobe FDKO Adobe RemoteUpdateManager AppKit Apple AppleScript AppleScript do shell script AppleScript List AppleScript ObjC AppleScript Osax AppleScript PDF AppleScript Pictures AppleScript record AppleScript Script Editor AppleScript Script Menu AppleScript Shortcuts AppleScript Shortcuts Events AppleScript System Events AppleScript System Events Plist AppleScript Video Applications AppStore Archive Attributes Automator BackUp Barcode Barcode QR Barcode QR Decode Bash Basic Basic Path Bluetooth BOX Browser Calendar CD/DVD Choose Chrome CIImage CityCode CloudStorage Color com.apple.LaunchServices.OpenWith Console Contacts CotEditor CURL current application Date&Time delimiters Desktop Device Diff Disk Dock DropBox Droplet eMail Encode % Encode Decode Encode UTF8 Error EXIFData ffmpeg File Finder Firefox Folder FolderAction Fonts GIF github Guide HTML HTML Entity Icon Illustrator Image Events Image2PDF ImageOptim iPhone iWork Javascript Jedit Json Label Leading Zero List locationd LRC lsappinfo LSSharedFileList m3u8 Mail MakePDF Map Math Media Media AVAsset Media AVconvert Media AVFoundation Media AVURLAsset Media Movie Media Music Memo Messages Microsoft Microsoft Edge Microsoft Excel Mouse Music NetWork Notes NSArray NSArray Sort NSBezierPath NSBitmapImageRep NSBundle NSCFBoolean NSCharacterSet NSColor NSColorList NSData NSDecimalNumber NSDictionary NSError NSEvent NSFileAttributes NSFileManager NSFileManager enumeratorAtURL NSFont NSFontManager NSGraphicsContext NSImage NSIndex NSKeyedArchiver NSKeyedUnarchiver NSLocale NSMutableArray NSMutableDictionary NSMutableString NSNotFound NSNumber NSOpenPanel NSPasteboard NSpoint NSPredicate NSPrintOperation NSRange NSRect NSRegularExpression NSRunningApplication NSScreen NSSize NSString NSString stringByApplyingTransform NSStringCompareOptions NSTask NSTimeZone NSURL NSURL File NSURLBookmark NSURLComponents NSURLResourceKey NSURLSession NSUserDefaults NSUUID NSView NSWorkspace Numbers OAuth OneDrive PDF PDFAnnotation PDFAnnotationWidget PDFContext PDFDisplayBox PDFDocumentPermissions PDFImageRep PDFKit PDFnUP PDFOutline perl Photoshop PlistBuddy pluginkit postalcode PostScript prefPane Preview Python QuickLook QuickTime ReadMe Regular Expression Reminders ReName Repeat RTF Safari SaveFile ScreenCapture ScreenSaver SF Symbols character id SF Symbols Entity sips Skype Slack Sound Spotlight sqlite SRT StandardAdditions Swift System Settings TCC TemporaryItems Terminal Text Text CSV Text MD Text TSV TextEdit Tools Translate Trash Twitter Typography UI Unit Conversion UTType valueForKeyPath Video VisionKit Visual Studio Code Wacom webarchive webp Wifi Windows XML XML EPUB XML OPML XML Plist XML RSS XML savedSearch XML SVG XML TTML XML webloc XML XMP YouTube zoom