swift - 如何检查程序是否在 Swift 中以管理员权限运行
问题描述
我正在尝试在 Swift 中为我的程序制作安装脚本(这也是在 Swift 中制作的)。
它所做的只是在其中创建一个新文件夹,Library/
然后在其中克隆 GitHub 存储库。
问题是,做任何事情都Library/
需要管理员权限。这就是为什么我想检查程序是否以管理员权限运行,所以如果没有,抛出一个错误,告诉用户使用sudo
.
我的代码:
import Foundation
import Darwin
@discardableResult
func shell(_ args: String...) -> Int32 {
let task = Process()
task.launchPath = "/usr/bin/env"
task.arguments = args
task.launch()
task.waitUntilExit()
return task.terminationStatus
}
func Main() {
if CommandLine.arguments[0] == "sudo" { //I tried by using this, but it seems that sudo doesn't appear in CommandLine.arguments
print("Welcome to the MoonFish installation... This will install MoonFish on /Library/MoonFish/ using 59.37 MB")
shell("mkdir", "/Library/MoonFish")
shell("git", "clone https://github.com/iAlex11/MoonFish.git /Library/MoonFish/") //clones MoonFish repo
} else {
print("\u{001B}[1;31mError:\u{001B}[0;0m Please run this program using sudo. Example: sudo ./install")
exit(0)
}
}
Main()
解决方案
Apple 不允许通过Process
.
我推荐使用 AppleScript。
- 启动脚本编辑器。
复制并粘贴此代码。
try display dialog "Welcome to the MoonFish installation... This will install MoonFish on /Library/MoonFish/ using 59.37 MB" buttons {"Cancel", "Install"} default button 2 do shell script "/bin/mkdir /Library/MoonFish" with administrator privileges do shell script "/usr/bin/git clone https://github.com/iAlex11/MoonFish.git /Library/MoonFish/" with administrator privileges on error quit end try
按enter。
- 从菜单中
File
选择Export
。 - 在对话框中检查
Run Only
并Application
从File Format
弹出窗口中选择。 - 指定文件名和位置,然后按Save。
您甚至可以使用自定义图标。替换./Contents/Resources/applet.icns
为另一个applet.icns
文件。
推荐阅读
- javascript - 如何在 Next.js 的 pages 文件夹中获取动态路由路径?
- windows - 如何找到单词 A 和单词 B 之间的字符串?
- android - 如何在 ModalDrawer (Jetpack compose) 中更改抽屉尺寸?
- jquery - 使用 laravel 8 在刀片视图中未定义的变量
- vb.net - 如何在 vb.net 中显示应用程序的版本号?
- git - 尽管已添加到 gitignore,但文件仍显示在 github 中
- asp.net-mvc - 在 ASP.NET 项目的视图中使用其他地方构建的 Vue 3 组件的最佳方式是什么?
- javascript - 当应用程序在后台打开时,Angular/Ionic WebApp 中有没有办法读取 FCM 消息数据?
- php - 在 Laravel 中仅将选定的行导出到 csv
- azure - 本地 Azure DevOps 上的受限访问用户可以添加/删除文件夹