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

时间:2017-05-22 08:34:23

标签: macos cocoa console-application macos-sierra

我试图通过运行控制台应用程序来获取系统安装日期。 我知道如何执行此操作的唯一方法是将/var/log/install.log文件解析为包含OSInstaller&的最新字符串。 Install Complete个项目。

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

2 个答案:

答案 0 :(得分:1)

作为探索的建议

您可以尝试查看文件/System/Library/Receipts

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

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

HTH,快乐狩猎!

答案 1 :(得分:-1)

所以万一有人认为这很有用。

Swift 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的{​​{1}}字段:

/System/Library/Receipts/com.apple.pkg.BaseSystemResources.plist