我想编写一个以root身份检查几个目录的litte程序。 我使用以下代码:
func execute(sudoCommands: String) -> String {
return(execute(command: "osascript -e \"do shell script \\\"" + sudoCommands + "\\\" with administrator privileges\""))
}
func execute(command: String) -> String {
var arguments:[String] = []
arguments.append("-c")
arguments.append( command )
let task = Process()
task.launchPath = "/bin/sh"
task.arguments = arguments
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.launch()
task.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
return(NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String)
}
func getSize(path: String, asRoot: Bool = false) -> String {
var result: String!
if(asRoot){
result = execute(sudoCommands: "sudo du -shm " + path)
} else {
result = execute(command: "du -shm " + path)
}
var sizesMB = 0
for dirResult in result.components(separatedBy: "\n") where dirResult != "" {
let currentDirSize = dirResult.components(separatedBy: "\t")[0]
sizesMB = sizesMB + Int(currentDirSize)!
}
return( "\(sizesMB) MB")
}
但是,如果我连续多次运行getSize("/Library/Caches/", asRoot: True)
,它(osascript)将一次又一次地询问我的密码......
是否有某种方式(这是安全的)以root身份执行命令而不提示输入密码? 我可以要求输入密码,将其保存在变量中并在必要时使用它,但这确实不安全或不安全我宁愿让Apple为我处理这个...