mac terminal cheat

Home

1 ip address commands

ifconfig
ifconfig  | grep 192.168
ifconfig  | grep inet

ipconfig getifaddr en0
ipconfig getifaddr en1

You can also see your public IP address in Terminal:

curl ifconfig.me~ and your public IP will pop up.

curl https://whatismyip.com

curl https://api.myip.com

1.1 dhcp lease renewal

sudo ipconfig set en0 BOOTP
sudo ipconfig set en0 DHCP

2 netstat

The ubiquitous netstat -nr also gives you your ip address.

3 public ip address

A very simple and effective web site will show you your public ip address:

curl ifconfig.me
curl ipecho.net/plain
curl whatismyip.org
# google https://whatismyipaddress.com/
curl -s http://checkip.dyndns.org/ | sed 's/[a-zA-Z<>/ :]//g'

# the sed 's/[a-zA-Z<>/ :]//g' simply removes any alphabetic characters.
# otherwise you would get:
<html><head><title>Current IP Check</title></head><body>Current IP Address: 74.127.203.173</body></html>
74.127.203.173

google.com search for ip

4 Adding ip commands to mac

You can use brew to install iproute2mac. It's actually a Python wrapper that provides a very similar API that you'll likely find very familiar to the ip tool included with iproute2 on Linux.

Installation
$ brew install iproute2mac
==> Installing iproute2mac from brona/homebrew-iproute2mac
==> Downloading https://github.com/brona/iproute2mac/archive/v1.0.3.zip
######################################################################## 100.0%
🍺  /usr/local/Cellar/iproute2mac/1.0.3: 4 files,  24K, built in 2 seconds
  • ip addr show en0
  • ip link show en1

5 Other related network commands

  • networksetup -setbootp <network service name>
  • networksetup -setdhcp <network service name>
  • networksetup -listnetworkserviceorder

flush your DNS cache by running:

#: sudo dscacheutil -flushcache

5.1 Open ports

There are several useful commands, similar to *nix commands for checking wht ports are open

# lsof = list open files
lsof -i -P | grep -i "listen"

lsof -nP +c 15 | grep LISTEN
- n for numeric ip addresses (i.e. do not resolve DNS names)
- P for numeric port numbers
- +c 15 limit output to 15 character wide column

lsof -h   # to list all available options for lsof

lsof -PiTCP -sTCP:LISTEN

lsof -nP -i4 | grep LISTEN
- i4  to list only ipv4 addresses

netstat -tuln  (p option for linux hosts, but not for mac osx)
netstat -anv
netstat -anv | grep 69

netstat -Watnlv  # gives lots of output. so:
netstat -Watnlv | 

5.2 scutils

scutil --dns | grep 'nameserver\[[0-9]*\]' at the command line. Should give you a list of DNS servers configured on your system.

6 Applications (install/uninstall) and misc.

6.1 Locations of apps and libraries.

Typically local apps are in /usr/local as well as a few others

  • ~/.local
  • /Applications/
  • /Library/
  • ~/Library

Sometimes you may get an error trying to remove a applications from /Applications/ directory. You might have to sudo chflags and set the noschg flag on the /Applicsaitons/xyz.app file before you can sudo rm xyz.app

See man chflags.

7 Time Machine utils

This might come in handy if you are having issues with time machine. Especially as it seems like those hidden Time Machine snapshots are stored in different locations due to the system partition change.

  • tmutil listlocalsnapshots /
  • tmutil listlocalsnapshots /System/Volumes/Data

Delete them using

  • tmutil deletelocalsnapshots <snapshot_date>
  • tmutil deletelocalsnapshots 2020-05-25-204347

8 sftp and scp server

To setup your macbook as an sftp or scp server, you first have to enable ssh. That is done through System Preferences / Sharing / Remote Login

But also, man 8 sshd gives detailed descriptions on running sshd from the command line.

If you haven't already, you can generate ssh keys pairs just like in Linux:

  • ssh-keygen

8.1 Listing keys:

All keys are in ~/.ssh but those are for the ssh client. For sshd you use the same keys. ?

The command $ ssh-add -L gave me an error The agent has no identities. But it is intended to list the keys. Same error for ssh-add -l

ls -al ~~/.ssh should show you al your keys. The remote keys are stored in known_hosts, your pubic key is id_rsa.pub and your private key is id_rsa

8.2 scp server as destination for cisco router configs

Once your macbook is running the scp/sftp daemon, you can use that as the destination for a copy command from a cisco router

On the router:

#copy running-config scp://username:password123G@10.128.16.125//running-config.txt
#copy running-config scp://zintis:######@192.168.11.54/r0-running-config

Or you can skip alot of the command line values and let the router prompt you for:

  • remote address
  • destination username
  • destination filename
  • password # this is actually prompted by the scp server when the scp connection is opened.

In which case you enter just #copy running-config scp: Either way works well.

8.3 Cisco router as scp server

Yes you can config a router to act as an scp server as well. Follow these steps:

1. enable
2. configure terminal
3. aaa new-model
4. aaa authentication login {default | list-name} method1[method2...]
5. aaa authorization {network | exec | commands level | reverse-access | configuration} {default | list-name} [method1 [method2...]]
6. username name [privilege level]{password encryption-type encrypted-password}
7. ip scp server enable   

9 sysctl

Macs do not have systemctl but do have sysctl that does not do the same thing anyway, but can be used to get info about your Mac kernel.

sysctl -a | grep machdep.cpu
sysctl -a | grep machdep.cpu.brand
sysctl -a | grep machdep.cpu.brand
sysctl -a | grep machdep.cpu.brand

10 Daemons on Mac OSX

10.1 launchctl

You can start and stop services using launchctl. For example to start tftp daemon, do this:

sudo launchctl load -F /System/Library/LaunchDaemons/tftp.plist

-F specifies the plist file to load. the plist file for tftp on my mac is:

 <?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
   <plist version="1.0">
   <dict>
           <key>Disabled</key>
           <true/>
           <key>Label</key>
           <string>com.apple.tftpd</string>
           <key>ProgramArguments</key>
           <array>
                   <string>/usr/libexec/tftpd</string>
                   <string>-i</string>
                   <string>/private/tftpboot</string>
           </array>
           <key>inetdCompatibility</key>
           <dict>
                   <key>Wait</key>
                   <true/>
           </dict>
           <key>InitGroups</key>
           <true/>
           <key>Sockets</key>
           <dict>
                   <key>Listeners</key>
                   <dict>
                           <key>SockServiceName</key>
                           <string>tftp</string>
                           <key>SockType</key>
                           <string>dgram</string>
                   </dict>
           </dict>
   </dict>
   </plist>

/System/Library/LaunchDaemo

11 Misc Mac Terminal commands and tidbits

11.1 say

say "It is 12 o'clock.  Do you know where your parents are?"

11.2 security

security is the command line interface to keychains and the security framework. Some useful commnds are:

Show me all my wifi passwords

security find-generic-pssword -wa Wifi
#+END_SRC~

Here is a list of all the security commands available (see ~man security~)

|------------------------+--------------------------------------------|
| list-keychains         | display or manipulate keychain search list |
|------------------------+--------------------------------------------|
| set-keychain-password  | useful when you changed your login passwd  |
|                        | and want your keychain passwed to match    |
|------------------------+--------------------------------------------|
| show-keychain-info     | obvious                                    |
|------------------------+--------------------------------------------|
| show-keychain-info     | obvious                                    |
|------------------------+--------------------------------------------|
| add-generic-pasword    | to keychain?  where does it add to?        |
|------------------------+--------------------------------------------|
| find-generic-password  | good to look up keychain entries quickly   |
|------------------------+--------------------------------------------|
| find-internet-password | ditto                                      |
|------------------------+--------------------------------------------|

For example, to show you what the wifi password for an SSID, try this:
#+BEGIN_SRC python
security find-generic-password -wa "Thunders"

(you will be prompted to enter a userid/password obviously)

See man security find-generic-password

11.3 curl wttr.in

To get weather in your terminal.

curl wttr.in
curl wttr.in/YYZ
curl wttr.in/Ottawa
curl wttr.in/Smiths-Falls
curl wttr.in/moon

11.4 curl qrenco.de (for QR Encode)

To encode any text into a qrcode, so you can then easily open that long text in a smartphone, without having to cut and paste etc.

curl qrenco.de
echo "There are only 60 and 67 days til deer and moose season openers." | curl -F-=\<- qrenco.de 

11.5 curl rate.sx (for currency trading)

curl rate.sx      # cryptocurrency rate for today
curl rate.sx/btc  # bit coin rate for today
curl rate.sx/btc@20w  # bit coin rate for past 20 weeks

11.6 curl cht.sh (for stackoverflow)

curl cht.sh/python/write+json+file
curl cht.sh/python/write+json+file\?Q   # same thing without comment lines.

curl cht.sh/python/write+yaml\?Q   # same thing without comment lines.
    curl cht.sh/python/write+json+file
  # queries "write json file" in python under stackoverflow website

  # got me this output:
  $ (U! master) curl cht.sh/python/write+json+file
#  You forgot the actual JSON part - `data` is a dictionary and not yet
#  JSON-encoded. Write it [like this][1] for maximum compatibility
#  (Python 2 and 3):

 import json
 with open('data.json', 'w') as f:
     json.dump(data, f)

#  On a modern system (i.e. Python 3 and UTF-8 support), you can write a
#  nicer file with

 import json
 with open('data.json', 'w', encoding='utf-8') as f:
     json.dump(data, f, ensure_ascii=False, indent=4)

  #  [1]: https://docs.python.org/3/library/json.html
#  
#  [phihag] [so/q/12309269] [cc by-sa 3.0]

11.7 curl cheat.sh (for cheat sheets)

First pick a language, say python, then a topic, say lambda

curl cheat.sh/pyhton/lamda

11.8 pbcopy (and weather on the command line)

Can take STDIN and stores it to your clipboard. for example, to copy the local weather from the Wego online utility to your clipboard:

curl wttr.in | pbcopy
# or just plain
curl wttr.in/YYZ
curl wttr.in/Ottawa
curl wttr.in/Smiths-Falls
curl wttr.in/moon

After piping to pbcopy you can paste that into notes or anywhere, like messages…

Obviously included in this example is curl wttr.in which shows local weather.

11.9 copy without formatting. Cmd-Option-Shift-V

(usually Cmd-v that pastes with all the formatting included)

11.10 change defaults with write

For example to change the default screen capture file name you can:

defaults write com.apple.screencapture name "capture-"

Then you will see screencaptures savad as capture 2023-08-02 at 5.13.39 PM

11.11 downloads database

Everything you downloaded is in a sql lite database on your mac.

To see it enter:

sqlite3 ~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV* 'select LSQuarantineDataURLString from LSQuarantineEvent'

# convenient to remove blank lines with
sed "/^$/d ; /^ *#/d"

# and count the lines with
wc -l

# in two steps, via a file called "junk"

sqlite3 ~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV* \
  'select LSQuarantineDataURLString from LSQuarantineEvent' > junk

sed "/^$/d ; /^ *#/d" junk | wc -l

To clear the downloads list:

sqlite3 ~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV* \
   'delete from LSQuarantineEvent'

11.12 flush your DNS cache

sudo killall -HUP mDNSResponder; sudo killall mDNSResponderHelper; sudo dscacheutil -flushcache 

11.13 quick look qlmanag

To get a quick look of a file use:

qlmanage -p ~/Desktop/capture-my-file.png

11.14 leave and alarm

To set a timer or alarm on the terminal to when you want to leave, use:

leave 13:25

11.15 bypass Mac gatekeeper

When installing from a trusted source, that is not yet registered as a trusted source , you can kill the gatekeeper with:

sudo spctl --master-disable

11.16 brew install cmatrix

11.17 toilet like figlet

Just bigger, but both do the same ascii art from text.

11.18 python web server to share files

It is very easy to run a web server using python3:

python3 -m http.server

C-c to shutdown the server

Then a local user can browse to http://[::]:8000 and see & download your files.

11.19 use mac touchid as sudo passwd

11.20 brew search casks

brew search discord brew cask install discord brew cask upgrade

THis must first be set up by editing the config file: /etc/pam.d/sudo Then add this line to the top of the other auth lines:

auth sufficient pam_tid.so

11.21 brew install htop

11.22 brew install speedtest-cli

speedtest-cli

11.23 youtube-dl

After you install it with brew install youtube-dl or upgrade with brew upgrade youtube-dl you can run this:

  • youtube-dl -f bestvideo+bestaudio ...

12 Home