8. macOS(12 Monterey 及以上 · Intel / Apple Silicon)

定位:与 Linux 同属 Unix 家族,但没有 systemd、没有 apt/dnf/pacman、没有 GNU 工具集。 记住四个替换关系:systemctl → launchctl、apt → brew、netplan/interfaces → networksetup、lsblk/mkfs → diskutil。

8.1 系统与硬件信息

命令用途 / 说明  
sw_vers产品名、版本号、Build 号  
sw_vers -productVersion只输出版本号(如 14.5)  
uname -aDarwin 内核版本 + 架构  
arch架构:arm64(Apple Silicon)/ i386(Intel 机器也显示 i386)  
system_profiler SPHardwareDataType机型、芯片、内存、序列号  
system_profiler SPSoftwareDataType系统版本与启动信息  
sysctl -n hw.ncpu逻辑核心数  
sysctl -n hw.memsize物理内存字节数  
sysctl -n machdep.cpu.brand_stringCPU / 芯片型号名称  
scutil --get ComputerName计算机名(共享列表显示用)  
scutil --get LocalHostName本地主机名(Bonjour 用)  
pmset -g batt电池电量与充电状态(笔记本)  
`ioreg -r -c AppleSmartBatterygrep -E 'CycleCountCapacity'`电池循环次数与健康度
sudo powermetrics --samplers smc -n 1温度 风扇 功耗(部分 Apple Silicon 机型支持)  
csrutil statusSIP(系统完整性保护)状态  
spctl --statusGatekeeper 状态  

8.2 包管理 Homebrew

命令用途 / 说明  
xcode-select --install安装命令行工具(git / clang,Homebrew 的前置依赖)  
xcode-select -p查看命令行工具安装路径  
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"安装 Homebrew  
brew --prefix安装前缀:Apple Silicon 为 /opt/homebrew,Intel 为 /usr/local  
brew install pkg安装命令行工具  
brew install --cask app安装图形界面应用(如 --cask google-chrome)  
brew update更新 Homebrew 自身与公式索引  
brew outdated列出可升级的包  
brew upgrade / brew upgrade pkg升级全部 / 升级单个  
brew list / brew list --cask已安装清单(命令行 / 图形应用)  
brew search kw / brew info pkg搜索 / 查看详情  
brew uninstall pkg卸载(cask 应用加 --cask)  
brew services list后台服务列表(底层是 launchd)  
`brew services startstoprestart pkg`启动 停止 重启服务
brew cleanup清理旧版本与缓存  
brew doctor环境自检(任何报错先跑它)  
brew deps --tree pkg依赖树  
brew bundle dump / brew bundle导出 / 按 Brewfile 重建整套环境  
brew install coreutils findutils gnu-sed grep装 GNU 版工具,命令带 g 前缀:gls、gsed、gdate、gfind  
sudo port install pkgMacPorts(另一套包管理,不要与 Homebrew 混用)  

8.3 服务管理 launchd(替代 systemd)

命令用途 / 说明 
launchctl list当前已加载的服务(列 PID、退出码、标签) 
`launchctl listgrep keyword`过滤某个服务
launchctl print gui/$(id -u)/com.example.app查看用户级服务详情(新式命令) 
launchctl print system/com.example.daemon查看系统级守护详情 
launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.example.plist加载用户级服务(取代旧 load) 
launchctl bootout gui/$(id -u) ~/Library/LaunchAgents/com.example.plist卸载服务 
launchctl kickstart -k gui/$(id -u)/com.example.app立即重启该服务(-k 先杀再启) 
`launchctl enabledisable gui/$(id -u)/com.example.app`启用 / 禁用(禁用后 bootout 也不启动)
sudo launchctl bootstrap system /Library/LaunchDaemons/com.example.plist加载系统级守护(root 身份运行) 
launchctl load -w ~/Library/LaunchAgents/x.plist旧式加载写法(仍可用,-w 持久化) 
plutil -lint ~/Library/LaunchAgents/x.plist校验 plist 语法(改完必须先跑这个) 
ls ~/Library/LaunchAgents用户级自启目录 
ls /Library/LaunchAgents全用户级自启目录 
ls /Library/LaunchDaemons系统级守护目录(开机即启,无需登录) 
ls /System/Library/LaunchDaemons系统自带守护(不要动) 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!-- 文件:~/Library/LaunchAgents/com.myapp.backup.plist
     说明:每天 03:30 执行备份脚本,等价于 cron 条目,但支持“休眠错过补跑”以外的登录加载 -->
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>com.myapp.backup</string>
  <key>ProgramArguments</key>
  <array>
    <string>/bin/bash</string>
    <string>/Users/me/bin/backup.sh</string>
  </array>
  <key>StartCalendarInterval</key>
  <dict>
    <key>Hour</key><integer>3</integer>
    <key>Minute</key><integer>30</integer>
  </dict>
  <key>StandardOutPath</key><string>/tmp/backup.out</string>
  <key>StandardErrorPath</key><string>/tmp/backup.err</string>
  <key>RunAtLoad</key><false/>
</dict>
</plist>
# 加载流程(四步,顺序不能乱)
plutil -lint ~/Library/LaunchAgents/com.myapp.backup.plist      # 1. 校验语法
launchctl bootout gui/$(id -u) ~/Library/LaunchAgents/com.myapp.backup.plist 2>/dev/null  # 2. 先卸载旧的
launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.myapp.backup.plist             # 3. 加载新的
launchctl print gui/$(id -u)/com.myapp.backup | head -20                                   # 4. 验证
# 注意:launchd 不会热读 plist,改完必须 bootout + bootstrap 重新加载

8.4 网络配置 networksetup / scutil

命令用途 / 说明 
ipconfig getifaddr en0当前 IP(en0 通常为 Wi-Fi 或主以太网) 
networksetup -listallnetworkservices列出网络服务名(Wi-Fi、Ethernet、Thunderbolt Bridge) 
networksetup -getinfo "Wi-Fi"该服务的当前配置 
sudo networksetup -setmanual "Wi-Fi" 192.168.1.50 255.255.255.0 192.168.1.1设置静态 IP(顺序:IP、掩码、网关) 
sudo networksetup -setdhcp "Wi-Fi"改回 DHCP 
sudo networksetup -setdnsservers "Wi-Fi" 223.5.5.5 8.8.8.8设置 DNS 
networksetup -getdnsservers "Wi-Fi"查看 DNS 
scutil --dns完整解析器链路(排查 DNS 走错服务器) 
sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder刷新 DNS 缓存(两条都要执行) 
ifconfig en0BSD 风格网卡详情 
route -n get default默认路由 
sudo route add -net 10.0.0.0/8 192.168.1.1添加静态路由(重启失效) 
networksetup -setairportnetwork en0 "SSID" "password"命令行连接 Wi-Fi 
sudo networksetup -setairportpower en0 off关闭 Wi-Fi(on 开启) 
networksetup -listpreferredwirelessnetworks en0已保存的 Wi-Fi 列表 
sudo lsof -iTCP -sTCP:LISTEN -n -P监听端口与进程(macOS 没有 ss) 
`netstat -angrep LISTEN`传统方式查监听
nc -vz host 22端口连通性测试 
sudo ifconfig en0 down / up禁用 / 启用网卡 

8.5 防火墙(socketfilterfw + pf)

命令用途 / 说明
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate应用防火墙是否开启
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate on开启应用防火墙
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --listapps已授权放行的应用清单
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add /Applications/xx.app添加应用到防火墙清单
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --unblockapp /Applications/xx.app放行该应用
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setstealthmode on隐身模式(不响应 ping、不回探测)
sudo pfctl -s infopf(包过滤)运行状态
sudo pfctl -e / sudo pfctl -d启用 / 停止 pf
sudo pfctl -s rules查看当前规则
sudo pfctl -f /etc/pf.conf加载 pf 配置
sudo pfctl -sn查看 NAT / 端口转发规则
# pf 端口转发(示例:本机 8080 → 内网 192.168.1.10:80)
# 1) /etc/pf.anchors/myforward 写入:
#    rdr pass inet proto tcp from any to any port 8080 -> 192.168.1.10 port 80
# 2) /etc/pf.conf 引用 anchor:
#    rdr-anchor "myforward"
#    load anchor "myforward" from "/etc/pf.anchors/myforward"
# 3) 生效
sudo pfctl -f /etc/pf.conf && sudo pfctl -e

8.6 磁盘、APFS 与备份

命令用途 / 说明
diskutil list列出全部磁盘与分区(/dev/disk0、disk2s1…)
diskutil list disk2只看某块盘的分区结构
diskutil info /dev/disk2磁盘详细信息
diskutil unmount /Volumes/NAME卸载卷(U 盘拔不出时用)
diskutil mount /dev/disk2s1挂载
diskutil eraseDisk APFS "DATA" /dev/disk2⚠️ 抹掉整盘并建 APFS
diskutil apfs listAPFS 容器 卷 快照结构
diskutil apfs addVolume disk1 APFS DATA在现有容器内新建 APFS 卷(共享空间)
diskutil apfs resizeContainer disk1 0把 APFS 容器扩到整盘(换大盘或分区被扩后)
diskutil verifyVolume /校验卷(修复须进恢复模式)
diskutil repairVolume /修复卷(恢复模式下执行)
diskutil resetUserPermissions / $(id -u)修复主目录权限(家目录权限错乱)
df -h / df -i容量 / inode(APFS 空间由容器共享)
sudo du -xhd1 /逐层定位占用最大的目录
tmutil listlocalsnapshots /列出 APFS 本地快照
tmutil localsnapshot立即创建本地快照(无需 Time Machine,秒级)
sudo tmutil deletelocalsnapshots <日期>删除指定本地快照(磁盘紧张时释放空间)
tmutil statusTime Machine 备份进度
tmutil startbackup / tmutil stopbackup开始 / 停止备份
tmutil listbackups备份清单
tmutil destinationinfo备份目标盘信息
sudo tmutil setdestination /Volumes/Backup指定备份目标
mdutil -sa / sudo mdutil -E /Spotlight 索引状态 / 重建索引
sudo periodic daily weekly monthly旧版系统维护脚本(新版 macOS 已由系统任务接管,命令可能不存在)

8.7 日志与排障(统一日志 Unified Log)

命令用途 / 说明  
log show --last 1h查看最近 1 小时统一日志(排障第一站)  
log show --predicate 'process == "nginx"' --last 30m按进程过滤  
log show --predicate 'eventMessage CONTAINS "error"' --last 1h按关键字过滤  
log show --predicate 'subsystem == "com.apple.network"' --last 1h按子系统过滤(网络问题)  
log stream --level debug实时流式输出(对应 Linux 的 journalctl -f)  
log stream --predicate 'process == "sshd"'实时跟踪某进程  
sudo log collect --last 1h --output ~/Desktop/sys.logarchive收集日志归档(给他人分析)  
sudo sysdiagnose -f ~/Desktop一键生成系统诊断包(提工单/求助必备)  
open -a Console打开 Console.app 图形化查日志  
tail -f /var/log/system.log传统系统日志(部分内容已迁入统一日志)  
ls ~/Library/Logs / ls /Library/Logs用户级 / 全局应用日志目录  
sudo dmesg内核日志(macOS 上受限,内容比 Linux 少)  
top -o mem按内存排序的资源监视(top -o cpu 按 CPU)  
vm_stat内存分页统计(替代 Linux 的 free)  
sysctl vm.swapusageswap 使用量  
memory_pressure内存压力评估(free percentage)  
sudo purge清文件缓存(释放 inactive memory,短时卡顿后恢复)  
`ps auxsort -k3 -nrhead`CPU 占用 Top
sudo lsof -i :8080端口被谁占用  
sample <pid> 10采样进程调用栈(卡死/卡顿定位)  
sudo powermetrics -n 1 --samplers cpu_power功耗与能耗排行(查“谁在偷偷耗电”)  
pmset -g / pmset -a sleep 0查看 / 修改休眠策略  
caffeinate -dimsu运行期间阻止休眠(长任务、远程会话)  
sudo pkill -f "app name" / killall App按名结束进程  

8.8 用户、权限与应用安全

命令用途 / 说明
dscl . -list /Users本地用户清单
dscl . -read /Users/$(whoami) UserShell当前用户的默认 shell
sudo dseditgroup -o edit -a me -t user admin把用户加入 admin 组(等价 Linux 的 sudo 组)
sudo dseditgroup -o edit -d me -t user admin从 admin 组移除
whoami / id当前用户与所属组
sudo -i切换到 root shell
chmod 755 file / chown -R me:staff dir权限(BSD 版参数与 Linux 兼容)
chflags hidden file / chflags nohidden fileBSD 文件标志:隐藏 / 取消隐藏
xattr -l /Applications/xx.app查看扩展属性
xattr -d com.apple.quarantine /Applications/xx.app去掉隔离属性(解决“已损坏,无法打开”)
spctl --statusGatekeeper 是否启用
sudo spctl --master-disable⚠️ 全局关闭 Gatekeeper(不建议)
codesign -dv --verbose=4 /Applications/xx.app查看应用签名信息
csrutil statusSIP 状态(需在恢复模式才能 disable/enable)
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --getstealthmode隐身模式状态

8.9 GNU 与 BSD / zsh 的命令差异(Linux 用户最常踩的坑)

场景Linux(GNU / bash)macOS(BSD / zsh) 
默认 shellbashzsh 
改默认 shellchsh -s /bin/bashchsh -s /bin/zsh(命令相同,默认值不同) 
sed 原地替换sed -i 's/a/b/g' fsed -i '' 's/a/b/g' f(必须给空串参数) 
日期偏移date -d "-1 day"date -v-1d(BSD 的 -v 语法) 
stat 取文件大小stat -c %s fstat -f %z f 
查内存free -hvm_stat / memory_pressure 
查服务systemctl status svc`launchctl listgrep svc / brew services list`
装包apt dnf pacmanbrew 
网卡与 IPip addrifconfig en0 / networksetup -getinfo 
监听端口ss -tulnplsof -iTCP -sTCP:LISTEN -n -P 
打开文件/网址xdg-open fopen f(open -a Safari https://…) 
剪贴板xclip / xselpbcopy / pbpaste 
语音播报完成—say "备份完成" 
全盘文件搜索find / locatemdfind -name kw(Spotlight,秒级) 
文件元数据statmdls file 
解压 zipunzipunzip(同名但 BSD 版参数少) 
定时任务cron / systemd timerlaunchd(cron 仍可用但受权限限制) 
完整 GNU 工具系统自带brew install coreutils → 用 gls/gsed/gdate/gfind 

💡 跨 Linux/macOS 通用脚本:优先用可移植写法($()、[[ ]]、少用 sed -i 差异语法);确实需要时按 uname -s 分支处理:

# 文件:判断系统后统一 sed 原地替换的写法
# 说明:Linux 的 sed -i 直接跟表达式,BSD/macOS 的 sed -i 必须先给一个空串参数
case "$(uname -s)" in
  Linux)  SED_INPLACE=(-i) ;;          # GNU sed
  Darwin) SED_INPLACE=(-i '') ;;       # BSD sed(macOS)
esac
sed "${SED_INPLACE[@]}" 's/a/b/g' file

8.10 Linux ↔ macOS 功能对应总表

功能LinuxmacOS
系统版本cat /etc/os-releasesw_vers / system_profiler SPSoftwareDataType
内核uname -runame -a(Darwin 版本)
装包apt dnf pacman / apkbrew install
升级全部apt full-upgradebrew update && brew upgrade
服务启停systemctl restart svclaunchctl kickstart -k gui/$UID/label / brew services restart svc
服务自启systemctl enable svclaunchctl bootstrap + RunAtLoad / brew services start
服务日志journalctl -u svclog show --predicate 'process == "svc"'
系统错误日志journalctl -p errlog show --last 1h --predicate 'eventMessage CONTAINS "error"'
静态 IPnetplan interfaces nmclinetworksetup -setmanual
DNS 刷新resolvectl flush-cachesdscacheutil -flushcache + killall -HUP mDNSResponder
防火墙ufw firewalld nftablessocketfilterfw + pfctl
磁盘列表lsblk -fdiskutil list
格式化mkfs.ext4 / mkfs.xfsdiskutil eraseDisk APFS
快照btrfs subvolume snapshot / LVM 快照tmutil localsnapshot(APFS 快照)
备份rsync borg resticTime Machine(tmutil)+ rsync
扩容lvextend + resize2fs / xfs_growfsdiskutil apfs resizeContainer
温度sensors / /sys/class/thermalsudo powermetrics --samplers smc
资源监视top htop iotoptop -o mem 活动监视器 powermetrics
端口占用ss -tulnplsof -iTCP -sTCP:LISTEN -n -P
内存查看free -hvm_stat / memory_pressure
开机自启目录/etc/systemd/system/Library/LaunchDaemons、~/Library/LaunchAgents

8.11 macOS 运维要点

场景正确做法
服务改配置不生效launchd 不热读 plist:必须 bootout 再 bootstrap,改前用 plutil -lint 校验
下载的 App 打不开(“已损坏”)xattr -d com.apple.quarantine /Applications/xx.app,不要关 Gatekeeper
磁盘空间莫名被吃tmutil listlocalsnapshots / 查本地快照,sudo tmutil deletelocalsnapshots <日期> 清理;再查 ~/Library/Caches、~/Library/Developer/Xcode(若装 Xcode)
装了 Xcode/模拟器空间爆~/Library/Developer/Xcode/DerivedData、iOS DeviceSupport、CoreSimulator 可安全清理
Apple Silicon 要跑 x86 工具softwareupdate --install-rosetta;个别场景 arch -x86_64 zsh
Homebrew 装的东西找不到确认 brew --prefix 在 PATH 里:/opt/homebrew/bin(ARM)或 /usr/local/bin(Intel)
排障需求收集先 sudo log collect 或 sudo sysdiagnose -f ~/Desktop 留证据,再看日志
长期维护定期 brew cleanup、diskutil verifyVolume /(恢复模式)、Time Machine 定期校验恢复
脚本里混合系统uname -s 分支处理 sed -i、stat、date 差异(见 8.9 的示例)

⚠️ 不建议做的事:关闭 SIP(csrutil disable)、全局关闭 Gatekeeper(spctl --master-disable)、用 root 跑日常操作、手动改 /System 下的东西(新版系统为只读签名卷,改了会启动异常)。


共 10 篇 Linux /macOS 运维命令 / 8.macOS 0 字 0 行 admin
创建 2026-11-18T08:44:23.323330123Z 更新 2026-11-18T08:55:20.094582296Z