[译]Mac OS X的命令行技巧


=Start=

用Mac有半年多了,对工作中常用到的一些软件还比较熟悉,其中以图形界面的操作居多,对Mac系统下的命令行操作不甚熟悉,一方面没有那么强烈的需求,另一方面也是因为没有碰到好的教程。前阵子在GitHub上看到了 “Awesome OS X Command Line” 觉得非常有用,于是将其中自己用的比较多的部分命令进行了翻译,内容如下:

##透明度
#降低透明度
defaults write com.apple.universalaccess reduceTransparency -bool true
#恢复默认透明度
defaults write com.apple.universalaccess reduceTransparency -bool false


##应用程序
#列出所有从AppStore下载的应用
find /Applications -path '*Contents/_MASReceipt/receipt' -maxdepth 4 -print |\sed 's#.app/Contents/_MASReceipt/receipt#.app#g; s#/Applications/##'


##Safari浏览器
#打开「开发模式菜单」和「Web调试器」
defaults write com.apple.Safari IncludeInternalDebugMenu -bool true && \
defaults write com.apple.Safari IncludeDevelopMenu -bool true && \
defaults write com.apple.Safari WebKitDeveloperExtrasEnabledPreferenceKey -bool true && \
defaults write com.apple.Safari com.apple.Safari.ContentPageGroupIdentifier.WebKit2DeveloperExtrasEnabled -bool true && \
defaults write NSGlobalDomain WebKitDeveloperExtras -bool true

#获取Safari浏览器当前打开页面的URL
osascript -e 'tell application "Safari" to get URL of current tab of front window'


##Xcode
#安装Xcode
xcode-select --install


##文件系统
#弹出挂载的所有磁盘/分区
osascript -e 'tell application "Finder" to eject (every disk whose ejectable is true)'

#查看所有挂载的磁盘/分区
diskutil list

#显示文件系统的使用情况
sudo fs_usage

#挂载/卸载磁盘镜像
hdiutil attach /path/to/diskimage.dmg
hdiutil detach /dev/disk2s1


##文本操作
#将(plain text, rich text and doc/docx)文件转换成HTML格式
textutil -convert html file.ext


##Finder
#将文件夹在Finder中设置成不可见
chflags hidden /path/to/folder/

#显示所有文件的扩展名
defaults write NSGlobalDomain AppleShowAllExtensions -bool true

#显示所有的隐藏文件
defaults write com.apple.finder AppleShowAllFiles true

#恢复默认的文件可见性设置
defaults write com.apple.finder AppleShowAllFiles false

#在Finder中显示用户的Library目录
chflags nohidden ~/Library

#设置Finder的默认开启路径
defaults write com.apple.finder NewWindowTarget -string "PfLo" && \
defaults write com.apple.finder NewWindowTargetPath -string "file://${HOME}"

#在网络卷上不要自动创建 .DS_Store 这样的文件
defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool true

#在USB设备上不要自动创建 .DS_Store 这样的文件
defaults write com.apple.desktopservices DSDontWriteUSBStores -bool true


##打开
#在终端上(默认)用Safari浏览器打开URL
open http://www.github.com

#打开文件
open README.md

#打开应用(-a选项)
open -a "Google Chrome" http://www.github.com

#打开目录
open /path/to/folder/

#在Finder中打开当前目录
open .


##硬件信息
#查看所有硬件端口
networksetup -listallhardwareports

#查看剩余电量百分比
pmset -g batt | egrep "([0-9]+\%).*" -o --colour=auto | cut -f1 -d';'

#查看剩余电量可用时间
pmset -g batt | egrep "([0-9]+\%).*" -o --colour=auto | cut -f3 -d';'

#查看连接设备的UDID
system_profiler SPUSBDataType | sed -n -e '/iPad/,/Serial/p' -e '/iPhone/,/Serial/p'

#查看当前屏幕分辨率
system_profiler SPDisplaysDataType | grep Resolution

#禁至系统(在1小时内)休眠
caffeinate -u -t 3600

#查看所有的电源管理设置
sudo pmset -g

#在系统死机时自动重启
sudo systemsetup -setrestartfreeze on

#将音频文件转换成iPhone铃声的格式
afconvert input.mp3 ringtone.m4r -f m4af

#从文本文件中创建音频内容
say -v Alex -f file.txt -o "output.m4a"

#静音设置
osascript -e 'set volume output muted true'

#朗读
say 'All your base are belong to us!'

#查看dhcp信息
ipconfig getpacket en0

#清除DNS缓存
sudo dscacheutil -flushcache && sudo killall -HUP mDNSResponder

#查看有哪些应用在使用80端口
sudo lsof -i :80

#查看本机IP
ipconfig getifaddr en0

#查看本机的外部IP
dig +short myip.opendns.com @resolver1.opendns.com

#加入Wifi网络
networksetup -setairportnetwork en0 WIFI_SSID WIFI_PASSWORD

#扫描所有的无线接入点
sudo ln -s /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport /usr/local/bin/airport
airport -s

#查看当前的SSID
/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I | awk '/ SSID/ {print substr($0, index($0, $2))}'

#显示Wifi连接历史
defaults read /Library/Preferences/SystemConfiguration/com.apple.airport.preferences | grep LastConnected -A 7

#包管理器
Homebrew
Fink
MacPorts

#文件/目录(安全)删除
srm /path/to/file
srm -r /path/to/folder/
srm -rf /path/to/complete/destruction

#执行AppleScript
osascript /path/to/script.scpt

#查看系统信息
sw_vers

#查看系统已开机时间
uptime

#剪贴板
pbcopy
pbpaste

#查看内存使用情况
vm_stat
vm_stat -c 10 1


##截屏
#延时截屏
screencapture -T 3 -t jpg -P delayedpic.jpg

#设置截屏文件的保存路径
defaults write com.apple.screencapture location ~/Desktop && \
killall SystemUIServer


##软件更新
sudo softwareupdate -ia
sudo softwareupdate -l

再次感谢「awesome-osx-command-line」!

=END=

, ,

《“[译]Mac OS X的命令行技巧”》 有 32 条评论

  1. Mac上的homebrew在遇到问题时可以尝试使用下面的命令进行解决:
    `
    brew doctor
    brew update && brew upgrade
    `

  2. 哥们,关于那个osacript -e的命令,我注意到原文中是osascript -e ‘tell application “Finder” to set desktop picture to POSIX file “/path/to/picture.jpg”‘
    你是不是在检查一下?

  3. https://apple.stackexchange.com/questions/64455/is-the-cellar-folder-only-used-for-homebrew
    https://github.com/Homebrew/legacy-homebrew/issues/41561
    Mac下用Homebrew安装的软件基本上都放在了 /usr/local/Cellar/ 目录下,且有的软件(比如:MySQL)安装了多个版本,如果不需要的话就删掉吧,减少一些空间占用:
    `
    $ du -sh /usr/local/Cellar/
    20G /usr/local/Cellar/
    $ brew –prefix
    /usr/local
    $
    $ du -sh /usr/local/Cellar/mysql/*
    339M /usr/local/Cellar/mysql/5.6.26
    465M /usr/local/Cellar/mysql/5.7.10
    467M /usr/local/Cellar/mysql/5.7.11
    479M /usr/local/Cellar/mysql/5.7.12
    480M /usr/local/Cellar/mysql/5.7.13
    481M /usr/local/Cellar/mysql/5.7.14
    473M /usr/local/Cellar/mysql/5.7.16
    480M /usr/local/Cellar/mysql/5.7.17
    234M /usr/local/Cellar/mysql/5.7.19
    234M /usr/local/Cellar/mysql/5.7.20
    $ du -sh /usr/local/Cellar/* | sort -hr
    `

  4. Mac下如何打印当前设备的序列号?
    https://stackoverflow.com/questions/5740390/printing-my-macs-serial-number-in-java-using-unix-commands/
    https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man8/ioreg.8.html
    http://www.manpages.info/macosx/ioreg.8.html
    `
    $ ioreg -l | awk ‘/IOPlatformSerialNumber/ { print $4;}’
    `

    用终端命令定制你的 OS X 通知中心:Today Scripts 体验详解
    https://sspai.com/post/27662

    cocoa获取系统序列号,uuid及Mac地址
    http://blog.csdn.net/lipingqingqing/article/details/8843606

  5. mac 下的 top 命令
    https://www.cnblogs.com/LiLihongqiang/p/5933185.html
    http://blog.sina.com.cn/s/blog_4adc4b090102w795.html
    `
    以前只是在 linux 机器上使用 top 命令。常用的快键键是:
    p 键 – 按 cpu 使用率排序
    m 键 – 按内存使用量排序

    这 2 个快捷键在 mac 上都不一样。对应的是,先输入 o,然后输入 cpu 则按 cpu 使用量排序,输入 rsize 则按内存使用量排序。

    如果记不清了,可以在 top 的界面上按 ?,在弹出的帮助界面中即可看到。
    `

  6. 如何查看Mac上的Wifi连接历史?
    http://osxdaily.com/2012/12/21/list-wi-fi-networks-mac-has-connected-to-before/
    http://osxdaily.com/2015/06/03/find-detailed-wifi-connection-history-mac-os-x/
    `
    defaults read /Library/Preferences/SystemConfiguration/com.apple.airport.preferences > ~/wifi_history.log

    defaults read /Library/Preferences/SystemConfiguration/com.apple.airport.preferences | grep LastConnected -A 9
    `
    https://superuser.com/questions/215033/does-mac-os-x-keep-a-log-of-network-connection-addresses-and-dates-times
    https://apple.stackexchange.com/questions/345654/specific-wifi-network-connection-history-in-osx

  7. Mac中的环境变量 PATH 到底是在哪设置的?
    Where is the default terminal $PATH located on Mac?
    https://stackoverflow.com/questions/9832770/where-is-the-default-terminal-path-located-on-mac
    `
    # Mac中的环境变量$PATH是由文件/etc/paths和目录/etc/paths.d/中的文件共同拼接组成的。
    /etc/paths
    /etc/paths.d/

    $ man path_helper
    `

    Add to the PATH on Mac OS X 10.8 Mountain Lion and up
    https://www.architectryan.com/2012/10/02/add-to-the-path-on-mac-os-x-mountain-lion/

    Where does $PATH get set in OS X 10.6 Snow Leopard?
    https://superuser.com/questions/69130/where-does-path-get-set-in-os-x-10-6-snow-leopard

  8. macOS使用Homebrew的经验分享
    https://segmentfault.com/a/1190000020712263
    https://wsgzao.github.io/post/homebrew/
    `
    目录
    前言
    更新历史
    Homebrew简介
    为什么需要Homebrew
    Homebrew快速入门
      Homebrew安装
      安装
      基础功能
      名词解释
    Homebrew进阶用法
      Tap
      Services
      Cask
      Bundle
    Homebrew扩展用法
      提交Formula
      自建Tap
      私有Tap
    Homebrew Tips
      禁用自动升级
      直接安装 Formula
    安装旧版软件
    Homebrew常见问题
    参考文章
    `

  9. 基于AppleScript的利用技术
    http://noahblog.360.cn/applescript_attack/
    `
    在恶意网络活动研究领域,针对个人终端的攻击Windows总是独占鳌头,但近年来MacOS的终端数上涨,让很多攻击团伙也开始聚焦针对MacOS的恶意软件利用,但即便针对MacOS的攻击,对手也倾向使用python/shell类脚本,恶意文档扩展一类的控制方案或入口利用。而AppleScript这一MacOS的内置脚本语言至今已沿用接近27年,却在安全研究领域鲜有人提及。我们在日常的研究工作中对基于AppleScript的恶意软件利用技术进行了适当总结和狩猎回顾,并提出一个依托AppleScript独有特性的攻击方法。

    # AppleScript特点
    AppleScript是MacOS的特有脚本语言,甚至在iOS或者iPadOS上都不能使用,且作为一门脚本语言AppleScript花里胡哨的”自然语言”古怪设计思路也常被开发者诟病,AppleScript试图以humanized的方式书写但又强硬规定了语法,导致代码及其冗长且背离自然语言书写思路。

    此外,由于AppleScript底层需要通过事件管理器(Apple Event Manager)进行构造和发送Apple事件,他的执行效率也极低,所以在实际场景中无论是用户还是管理员,都极少使用AppleScript。

    从AppleScript调用Apple Event Manager能看出来,其核心是为了进行MacOS之间应用通信和自动化工作,所以通过0用户交互进行应用通信成为AppleScript的最大特点,只要脚本语言中设置好节点内容,可以再无人工参与的情况下进行任何MacOS下的基本操作和图形交互。

    自动化应用通信加上用户免交互,二者叠加可以说是为攻击者提供了天然的鱼叉投递和后渗透土壤,没有任何”漏洞利用”能比”合法”使用任意流行应用进行无受害者参与的攻击路径更有效,所以虽然AppleScript在开发者,用户侧并不受待见,但在攻击侧,通过合理使用AppleScript往往能无往不利,而且不幸的是,Apple对于AppleScript安全的态度也很疲软。
    `
    https://github.com/hackedteam/core-macos/blob/master/core/RCSMCore.m
    https://attack.mitre.org/techniques/T1155/
    https://objective-see.com/blog.html#blogEntry6

  10. `
    #显示Wifi连接历史(macOS Catalina 10.15.6)
    defaults read /Library/Preferences/SystemConfiguration/com.apple.airport.preferences | grep “Last.*JoinAt” -A 12

    SSIDString = “WIFI名称”;

    SecurityType = “安全性”; 取值范围有:
    Open – 无需密码
    WPA2/WPA3 Personal -WPA2/WPA3个人级
    WPA2 Enterprise – WPA2企业级
    `

  11. `
    点击「屏幕左上角的苹果图标 」-「系统偏好设置」-「网络」-「Wi-Fi」-「高级…」

    在「Wi-Fi」-「首选网络:」这里能看到本机电脑上连接过的网络名称(需要【记住这台电脑所加入的网络】被勾选了才行,默认是勾选的)。
    `

  12. Specific Wifi network connection history in OSX
    https://apple.stackexchange.com/questions/345654/specific-wifi-network-connection-history-in-osx
    `
    log show –predicate ‘(processImagePath contains “configd”) && (eventMessage contains “en0: SSID {enteryours} “)’ –style syslog –last 1d
    `

    Find Detailed Wi-Fi Connection History from Command Line of Mac OS X
    https://osxdaily.com/2015/06/03/find-detailed-wifi-connection-history-mac-os-x/
    `
    log show
    –predicate ‘(processImagePath contains “configd”) && (eventMessage contains “en0: SSID {enter your SSID name} “)’
    –style syslog
    –last 1d
    `

  13. Mac 命令行终端里获得视频文件的长度
    https://blog.est.im/202104/stdout-004
    `
    记录一下,MacOSX 10.6.8 或更高版本:

    mdls -name kMDItemDurationSeconds -name kMDItemFSName 1.mp4
    或者在 Finder 里新建一个叫 Movies 的文件夹,把视频文件放进去,然后列表展示,表头右键,就可以选择显示长度。。

    同理,建立一个叫 Pictures 的文件夹,可以列表展示图片尺寸。。
    `
    https://superuser.com/questions/1024894/how-can-i-make-finder-display-video-file-duration

  14. 公开一个macOS命令执行技巧
    https://mp.weixin.qq.com/s/GZ5eS_lHiBBb7jHNu6PUgg
    `
    最近在研究mac上的一些命令注入问题,看着看着觉得蛮有意思就先记录一下。这里主要围绕比较常见的open命令展开。顺便说一句我的mac是 macOS Big Sur 11.4

    0x01 open的基础使用
    open -h

    0x02 奇妙的细节
    前面看了-a和不-a都可以打开计算器,那么这两者有什么区别呢?其实还是有一些细微的区别的。
    * -a参数是指打开某个application
    * 不带-a参数的时候会根据后缀等进行自动判断使用什么app进行打开

    0x03 执行二进制
    前面我们都是在打开app,我们能不能执行二进制呢?是可以的 我们正常来使用open执行一个二进制会怎么样?

    0x04 结尾
    上面这些要想完全应用到实际场景中可能还需要各位开动小脑筋,不过至少可以说明一些事情了。很多命令在实际使用的时候并不会像他们说明文档里说的那样简单纯粹。我把这个问题汇总了一下,用我蹩脚的英文把这个当作漏洞反馈给了apple官方了,至于他接不接受,我才不care!
    `
    https://scriptingosx.com/2017/02/the-macos-open-command/

  15. macOS系统上如何从终端中获取某个文件的创建/修改时间
    OSX – How to get the creation & modification time of a file from the command line
    https://stackoverflow.com/questions/34123076/osx-how-to-get-the-creation-modification-time-of-a-file-from-the-command-lin
    `
    $ GetFileInfo -d .bash_profile
    $ stat -x my_file.py

    # Access (atime)
    stat -f “%Sa” file.txt
    # Modify (mtime)
    stat -f “%Sm” file.txt
    # Change (ctime)
    stat -f “%Sc” file.txt
    # Birth (Btime)
    stat -f “%SB” file.txt
    # all in one
    stat -f “Access (atime): %Sa%nModify (mtime): %Sm%nChange (ctime): %Sc%nBirth (Btime): %SB” file.txt
    `

  16. How to find out macOS version information from Terminal command prompt
    https://www.cyberciti.biz/faq/mac-osx-find-tell-operating-system-version-from-bash-prompt/
    `
    system_profiler command – Show Apple hardware and software configuration.
    sw_vers command – Show Mac OS X operating system version.

    $ sw_vers
    ProductName: macOS
    ProductVersion: 12.3.1
    BuildVersion: 21E258
    $
    $ sw_vers -productVersion
    12.3.1
    $
    `
    https://superuser.com/questions/75166/how-to-find-out-mac-os-x-version-from-terminal
    https://coderwall.com/p/4yz8dq/determine-os-x-version-from-the-command-line

  17. How does file access time updating work on macOS?
    https://apple.stackexchange.com/questions/441754/how-does-file-access-time-updating-work-on-macos
    `
    # stat -x ~/.ssh/id_rsa

    APFS has slightly different default semantics on access timestamps than you might expect. In particular, by default the access timestamp of a file is only updated on read if the currently stored access timestamp is prior to the file’s modification timestamp.

    APFS在默认情况下,如果当前存储的访问时间戳(atime)先于文件的修改时间戳(mtime),则文件的访问时间戳仅在读取时更新。

    You can change that to get the traditional behavior by setting the feature flag APFS_FEATURE_STRICTATIME on the volume. This is not something an ordinary user should have to do, so I would recommend against going for that option unless you have very specific requirements.
    需要在卷上设置特性标志 APFS_FEATURE_STRICTATIME 来更改它以获得传统的行为,但除非必要,不建议这么干。
    `

  18. AppleScript脚本入门
    https://segmentfault.com/a/1190000011273388

    iOS 程序员效率提升利器之 AppleScript
    https://mp.weixin.qq.com/s/y_yAmuIN264wcSAPd0mF9g
    `
    在开始之前,先简单概括下 AppleScript 的应用环境。我们的 Mac 系统从应用的角度来看,其实就是一堆 App 的集合,系统自带的 App(Mail,Safari,Terminal 等)和安装的第三方 App(Firefox,Chrome,Outlook,iTerm 等),这些主流的 App 其实都向系统暴露了一些实用接口,用来将一些高频操作自动化。谁来调用这些接口呢?AppleScript。AppleScript 可以将这些 App 和 App 内部的数据,都当作对象来访问,甚至可以将不同 App 串联,自动化之后形成一个 workflow。

    如何编写 AppleScript 呢?Mac 自带脚本编辑和运行工具,通过 Spotlight Search 搜索 Script Editor 即可。运行 Script Editor 之后,通过菜单 File -> Open Dictionary 即可打开如下图所示一个文档,里面列出来所有支持 AppleScript 的 App,以及各个 App 所支持的接口调用。

    AppleScript 的应用场景很广泛,且很容易上手。一些 Mac App 的核心功能甚至都是利用 AppleScript 来编写的。比如 Mac 上的剪贴板工具,就是通过 AppleScript 来操作其他应用的当前编辑文本,来实现历史查找和插入功能。工具的强大与否在于使用之人如何用之,工具都是越用越称手。
    `

    AppleScript探索MacOS自动化
    https://mp.weixin.qq.com/s/wNSqgLEVSFqwlzjV1rOdMQ

    AppleScript 入门:探索 macOS 自动化
    https://sspai.com/post/46912

    AppleScript初窥
    https://mp.weixin.qq.com/s/T3vD3Oyqv9OKF4exlcFVRg

    Mac 自动填充验证码的探索
    https://sspai.com/post/73072

  19. awesome-macos-command-line
    https://git.herrbischoff.com/awesome-macos-command-line/about/
    `
    * Appearance
    ____* Alert Dialog Style
    ____* Dark Mode
    ____* Proxy Icon
    ____* Subpixel Anti-Aliasing
    ____* Transparency
    ____* Wallpaper

    * Applications
    ____* App Store
    ____* Apple Remote Desktop
    ____* Contacts
    ____* Google
    ____* iTunes
    ____* Mail
    ____* Safari
    ____* Sketch
    ____* Skim
    ____* Terminal
    ____* TextEdit
    ____* Visual Studio Code

    * Backup
    ____* Time Machine

    * Developer
    ____* Vim
    ____* Xcode

    * Dock

    * Documents

    * Files, Disks and Volumes
    ____* APFS
    ____* Disk Images

    * Finder
    ____* Desktop
    ____* Files and Folders
    ____* Layout
    ____* Metadata Files
    ____* Opening Things

    * Fonts

    * Functions

    * Hardware
    ____* Bluetooth
    ____* Harddisks
    ____* Hardware Information
    ____* Infrared Receiver
    ____* Power Management

    * Input Devices
    ____* Keyboard

    * Launchpad

    * Media
    ____* Audio
    ____* Video

    * Networking
    ____* Bonjour
    ____* DHCP
    ____* DNS
    ____* Hostname
    ____* Network Preferences
    ____* Networking Tools
    ____* SSH
    ____* TCP/IP
    ____* TFTP
    ____* Wi-Fi

    * Package Managers

    * Printing

    * Security
    ____* Application Firewall
    ____* Gatekeeper
    ____* Passwords
    ____* Physical Access
    ____* Privacy Database
    ____* Wiping Data

    * Search
    ____* Find
    ____* Locate

    * System
    ____* AirDrop
    ____* AppleScript
    ____* Basics
    ____* Clipboard
    ____* Date and Time
    ____* FileVault
    ____* iCloud
    ____* Information/Reports
    ____* Installation
    ____* Kernel Extensions
    ____* LaunchAgents
    ____* LaunchServices
    ____* Login Window
    ____* Memory Management
    ____* Notification Center
    ____* QuickLook
    ____* Remote Management
    ____* Root User
    ____* Safe Mode Boot
    ____* Save Dialogs
    ____* Screenshots
    ____* Sidecar
    ____* Software Installation
    ____* Software Update
    ____* Software Version
    ____* Spell Checking
    ____* Spotlight
    ____* System Integrity Protection

    * Terminal
    ____* Alternative Terminals
    ____* Shells
    ____* Terminal Fonts

    * Glossary
    ____* Mac OS X, OS X, and macOS Version Information
    `

回复 hi 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注