以编程方式获取系统安装日期

问题描述 投票:0回答:3

我正在尝试通过运行控制台应用程序来获取系统安装日期。 我知道如何执行此操作的唯一方法是解析

/var/log/install.log
文件以获取包含
OSInstaller
Install Complete
项目的最新字符串。

我缺少一个方便的系统 API 吗?

macos cocoa console-application macos-sierra
3个回答
1
投票

仅作为探索建议

您可以尝试查看文件

/System/Library/Receipts

您可能会看到一个

com.apple.pkg.BaseSystemResources.plist
文件,它的修改日期可能会告诉您操作系统的安装时间。

还有

com.apple.pkg.update.os.*.plist
文件用于更新,再次查看修改日期,如果您可以确定命名约定,也许可以解析通配符 (
*
) 位。

HTH,狩猎快乐!


0
投票
system_profiler SPInstallHistoryDataType | grep macOS -A 4

-1
投票

以防万一,有人发现这很有用。

斯威夫特3.0

解决方案1

最初我解析

/var/log/install.log
文件以获取日期字符串:

    // To get OS installation date we'll need to check system log file and find entry which contains installation date
var systemDates : String? = nil
do {
    let fullSystemLog = try NSString(contentsOf: URL(fileURLWithPath: "/var/log/install.log"), encoding: String.Encoding.utf8.rawValue)
    let entries = fullSystemLog.components(separatedBy: "\n")
    //Filter to get only entries about OS installation
    let filtered = entries.filter{ entry in
        return entry.contains("OSInstaller") && entry.contains("Install Complete") //Markers telling that OS was installed
    }

    var latestMention = ""
    if filtered.count > 0 {
        //If 1 or more entries found we'll pick last one
        latestMention = filtered.last!
    }
    else if entries.count > 0 {
        //If there are 0 mentions of OS installation - we'll use first entry in logs
        latestMention = entries.first!
    }

    //parse picked entry for date
    do {
        let regex = try NSRegularExpression(pattern: ".+:[0-9]{2}", options: [])
        let nsString = latestMention as NSString
        let results = regex.matches(in: latestMention,
                                    options: [], range: NSMakeRange(0, nsString.length))
        let actualDateSubstrings = results.map { nsString.substring(with: $0.range)}

        if let dateStringFromMention = actualDateSubstrings.first {

            systemDates = dateStringFromMention
        }
        else {
            systemDates = "<Error: no date results>"
        }

    } catch let error as NSError {
        systemDates = "<Error: invalid regex: \(error.localizedDescription)>"
    }
} 
catch {
    systemDates = "<Error: system log file not found>"
}

print("\tSYSTEM INSTALLED: \(systemDates)")

解决方案2

第二种解决方案看起来简单得多。查看

InstallDate
/System/Library/Receipts/com.apple.pkg.BaseSystemResources.plist
字段:

let systemDates = NSDictionary(contentsOfFile: "/System/Library/Receipts/com.apple.pkg.BaseSystemResources.plist")

print("\tSYSTEM INSTALLED: \(systemDates?["InstallDate"])")
© www.soinside.com 2019 - 2024. All rights reserved.