Mac配置和使用iterm2

iTerm2 是 mac 上优秀的ssh 工具,但它的开箱即用并不算很友好,需要我们自己打造一下。

Mac配置和使用iterm2

iTerm2 安装

iTerm2 下载并安装。

或者使用 brew 安装:

brew install iterm2

如果初次使用mac,可能需要安装Homebrew(网络条件好才行)。

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

iTerm2 入门配置

  • 设置 iTerm2 为默认终端
    (菜单栏)iTerm2 -> Make iTerm2 Default Term

  • 全局热键启动和关闭 iTerm2
    偏好设置 preferences -> Keys -> Hotkey,勾选Show/hide iTerm2 with a system-wide hotkey,将热键设置为 command+i

  • 修改Terminal中的主机名
    sudo scutil --set HostName MacBookPro

  • 透明度
    偏好设置 preferences -> Profiles,右侧找到window选项卡,拖动Transparency调整。

  • 导入主题(配色方案)
    个人比较喜欢 Dracula 系列,因此选择了 Dracula 的 iTerm 2 主题,按照安装步骤下载并导入。
    然后在 iTerm2 > Preferences > Profiles > Colors 中选择该主题,并将其设置问默认。
    iterm2 有诸多配色方案,除了上面我使用的,还有这些选择:

这个时候打开 iterm2,终端并不会显示为彩色,还需要设置 bash(zsh见后面)。

iTerm2 高级配置

在 Windows 上使用过 Mobaxterm 的人应该知道它有多好用 -- 仅仅是关键字高亮这一项就足够吸引人。尤其是大堆输出的日志中夹杂 Warn/Error/Fatal/Panic 这类信息的时候,简直是眼瞎救星。

因此,当我从 Win 切换到 Mac 的时候,我开始使用 iTerm2,并试图引入这一功能。

我们先看下别人的配置:

这一功能通过 iTerm2 的触发器实现,配置路径为:
Preferences -- Advanced -- Trigger,edit。

  • 高亮 ip 地址

    • [x] Action: Highlight Text
    • [x] Colors: Text 紫色, Background 无色
    • [x] Pattern: \b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b
  • 高亮 MAC 地址

    • [x] Action: Highlight Text
    • [x] Colors: Text 淡紫色, Background 无色
    • [x] Pattern: ([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})
  • 高亮错误关键字

    • [x] Action: Highlight Text
    • [x] Colors: Text 红色, Background 无色
    • [x] Pattern: (?i)error|err|panic|fatal
  • 高亮警告关键字

    • [x] Action: Highlight Text
    • [x] Colors: Text 黄色, Background 无色
    • [x] Pattern: (?i)warn|unknown|disabled|stoped|exited
  • 高亮提示关键字

    • [x] Action: Highlight Text
    • [x] Colors: Text 绿色, Background 无色
    • [x] Pattern: (?i)Info|activated|enabled|started|running
  • 高亮 uuid

    • [x] Action: Highlight Text
    • [x] Colors: Text 黑色, Background 天蓝
    • [x] Pattern: [0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}
  • 高亮疑似 base64 字串

    • [x] Action: Highlight Text
    • [x] Colors: Text 蓝色, Background 浅绿
    • [x] Pattern: [0-9A-Za-z]{6}==
  • 高亮疑似 LM or NTLM 哈希串:

    • [x] Action: Highlight Text
    • [x] Colors: Yellow Text, Black Background
    • [x] Pattern: [0-9A-Za-z]{32}

其他警告类设置,参考:https://bneg.io/2018/01/15/iterm2-customizations-for-hackers

配置 bash

Mac 是使用的 bash 配置文件是 ~/.bash_profile, 而不是 linux 下常用的 ~/.bashrc 文件。当然,也可以使用在文件中加载任意文件:
[ -r ~/.bashrc ] && source ~/.bashrc

编辑 .bash_profile 文件,添加如下内容:

# .bashrc

# User specific aliases and functions
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
alias ls='ls -G'
alias ll='ls -lt'
alias vi='vim'

# Source global definitions
if [ -f /etc/bashrc ]; then
    . /etc/bashrc
fi

if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

# add timestamp into history
HISTTIMEFORMAT="%F %T "

# export customer PS1 variables
export TERM=xterm-256color
export GREP_OPTIONS='--color=auto' GREP_COLOR='1;32'
export CLICOLOR=1
export LSCOLORS=ExFxCxDxBxegedabagacad

export COLOR_NC='\e[0m' # No Color
export COLOR_BROWN='\e[0;33m'
export COLOR_WHITE='\e[1;37m'
export COLOR_BLACK='\e[0;30m'
export COLOR_YELLOW='\e[1;33m'
export COLOR_GREEN='\e[0;32m'
export COLOR_LIGHT_GREEN='\e[1;32m'
export COLOR_RED='\e[0;31m'
export COLOR_LIGHT_RED='\e[1;31m'
export COLOR_BLUE='\e[0;34m'
export COLOR_LIGHT_BLUE='\e[1;34m'
export COLOR_CYAN='\e[0;36m'
export COLOR_LIGHT_CYAN='\e[1;36m'
export COLOR_PURPLE='\e[0;35m'
export COLOR_LIGHT_PURPLE='\e[1;35m'
export COLOR_GRAY='\e[0;30m'
export COLOR_LIGHT_GRAY='\e[0;37m'

PS1="[\[${COLOR_BROWN}\]\[email protected]\[${COLOR_PURPLE}\]\h:\[${COLOR_LIGHT_BLUE}\]\${PWD}]\[${COLOR_GREEN}\] \[${COLOR_NC}\]\$ "

export HOMEBREW_NO_AUTO_UPDATE=1

然后加载一下配置:
source .bash_profile

如果想要 manpage 也是彩色的,需要安装这个工具:

brew install most

#增加如下配置
vim .bashrc
export MANPAGER='most -s'

zsh 配置及使用

MacOSX 默认安装了 zsh,但需要手动启用

chsh -s /bin/zsh
zsh --version

但是原生 zsh 不够好用,我们使用oh-my-zsh框架来扩展它的功能。

sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"

然后启用 oh-my-zsh 两大特色功能:

  • 代码高亮
    下载并启用 zsh-syntax-highlighting
cd ~/.oh-my-zsh/custom/plugins
git clone git://github.com/zsh-users/zsh-syntax-highlighting.git

vim  ~/.zshrc
#在末尾添加代码
source ~/.oh-my-zsh/custom/plugins/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
plugins=(zsh-syntax-highlighting)

#保存并导入配置
source ~/.zshrc
  • 自动提示

下载并启用 zsh-autosuggestions

cd ~/.oh-my-zsh/custom/plugins
git clone git://github.com/zsh-users/zsh-autosuggestions

#编辑文件 ~/.zshrc,添加一下内容并保存
source ~/.oh-my-zsh/custom/plugins/zsh-autosuggestions/zsh-autosuggestions.zsh
plugins=(zsh-autosuggestions)

cd ~/.oh-my-zsh/custom/plugins/zsh-autosuggestions
vim zsh-autosuggestions.zsh 
#将fg=8 修改 fg=10 
ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE='fg=10' 

#保存并导入配置
source ~/.zshrc
  • default.profile

安装 dracula 主题

配置iTerm2主题为 Dracula,可以参考 Dracula

下载主题文件

git clone https://github.com/dracula/iterm.git

激活主题

 1、iTerm2 > Preferences > Profiles > Colors Tab
 2、Open the Color Presets... drop-down in the bottom right corner
 3、Select Import... from the list
 4、Select the Dracula.itermcolors file
 5、Select the Dracula from Color Presets...

参考文档

工具篇:iTerm与Zsh
Mac下美化iterm2使用oh-my-zsh
iTerm2 Customizations for Hackers
iTerm2 trigger case insensitive

附录(Mobaxterm的高亮配置)

不得不说商业的就是强大啊。

  • ok/error
# underline
[^A-Za-z_&-](http(s)?://[A-Za-z0-9_./&?=%~#{}()@+-]+)[^A-Za-z0-9_-]

# Red
([^A-Za-z_&-]((bad|wrong|incorrect|improper|invalid|unsupported|bad)( file| memory)? (descriptor|alloc(ation)?|addr(ess)?|owner(ship)?|arg(ument)?|param(eter)?|setting|length|filename)|not properly|improperly|(operation |connection |authentication |access |permission )?(denied|disallowed|not allowed|refused|problem|failed|failure|not permitted)|no [A-Za-z]+( [A-Za-z]+)? found|invalid|unsupported|not supported|seg(mentation )?fault|corruption|corrupted|corrupt|overflow|underrun|not ok|unimplemented|unsuccessfull|not implemented|permerrors?|fehlers?|errore|errors?|erreurs?|fejl|virhe|gre歬a|erro|fel|\(ee\)|\(ni\))[^A-Za-z_-]|[=>"':.,;({\[][ ]*(false|no|ko)[ ]*[]=>"':.,;)} ])

# Green
([^A-Za-z_&-](accepted|allowed|enabled|connected|erfolgreich|exitoso|successo|sucedido|framg錸gsrik|successfully|successful|succeeded|success)[^A-Za-z_-]|[=>"':.,;({\[][ ]*(true|yes|ok)[ ]*[]=>"':.,;)} ])

# Yellow
[^A-Za-z_&-](\[\-w[A-Za-z-]+\]|caught signal [0-9]+|cannot|(connection (to (remote host|[a-z0-9.]+) )?)?(closed|terminated|stopped|not responding)|exited|no more [A-Za-z] available|unexpected|(command |binary |file )?not found|(o)+ps|out of (space|memory)|low (memory|disk)|unknown|disabled|disconnected|deprecated|refused|disconnect(ion)?|advertencia|avvertimento|attention|warnings?|achtung|exclamation|alerts?|warnungs?|advarsel|pedwarn|aviso|varoitus|upozorenje|peringatan|uyari|varning|avertissement|\(ww\)|\(\?\?\)|could not|unable to)[^A-Za-z_-]

# Blue
# 无

# Magenta
[^0-9A-Za-z_&-](localhost|([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])\.[0-9]+\.[0-9]+\.[0-9]+|null|none)[^0-9A-Za-z_-]

# Cyan
[^A-Za-z_&-](last (failed )?login:|launching|checking|loading|creating|building|important|booting|starting|notice|informational|informationen|informazioni|informa玢o|oplysninger|informations?|info|informaci|informasi|note|\(ii\)|\(\!\!\))[^A-Za-z_-]

# Blinking
# 无
  • Shell
# underline
# 无

# Red
[^\](\$\([^(\))]+\)|`[^ `][^`]+`)[^╙

# Green
(? *)?#[^╙+)+

# Yellow
[^\](\$[\[email protected]\$][^╙|\$\(\([^(\))]+\)\)[^╙|\$\{[^\}]+\}[^╙|\$\[[^]]+\][^╙|\$[A-Za-z_0-9]+[^A-Za-z_0-9])

# Blue
[^\](\\(033|e|E)\[(1;)?(0|30|31|32|33|34|35|36)m|/dev/null|\|\||\&\&)[^╙

# Magenta
[ ;╘(](for(each)?|while|done|if|then|else|elif|fi|case|esac|endif)[ ;╘)]

# Cyan
[ ;╙(builtin )?(setenv|export|unset|ulimit|builtin|shopt|unalias|alias|function|echo|printf)[ ;╙

# Blinking
# 无
  • Network
# underline
# 无

# Red
(? *)?no | down |[^A-Za-z0-9](disabled|unknown|fault|shutdown|disconnected|error|failed|denied|not permitted|disallowed|not allowed|refused|problem|failure|not permitted|notconnect)[^A-Za-z0-9])

# Green
([^A-Za-z0-9](enabled|connected|up|yes|ok)[^A-Za-z0-9]|? *)?(description|(host)?name(if)?|version) [^╙+)

# Yellow
[^A-Za-z0-9](localhost|([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])\.[0-9]+\.[0-9]+\.[0-9]+|vlan[0-9]+|([a-z]+thernet|gi)[0-9]+(\/[0-9]+)*)[^A-Za-z0-9]

# Blue
(? *)?\![^╙+)+

# Magenta
[^A-Za-z0-9](policy-map|class|global|logging( event)?|(allocate-)?interface|failover|static|security-level|service(-policy)?|spanning-tree|switchport)[^A-Za-z0-9]

# Cyan
[^A-Za-z0-9](\%link-[0-9]+-updown|(allowed )?(private-)?vlan(-range)?|route|access-(list|group)|port-forward|mtu|show|encapsulation|rate-limit|speed|duplex|autoneg|snmp-server|media-type|ip( address)?|monitor( session)?)[^A-Za-z0-9]

# Blinking
# 无
  • sql
# underline
# 无

# Red
error,warning,cancel,disable,drop,abort,after,asc,attach,before,begin,cascade,cluster,conflict,copy,cross,database,deferred,delimiters,desc,detach,each,end,explain,fail,for,full,ignore,immediate,initially,inner,instead,key,left,match,natural,of,offset,outer,pragma,raise,replace,restrict,right,row,statement,temp,temporary,trigger,vacuum,view,cancelled

# Green
enable,mysql,postgresql,postgre,oracle,server,database,db,ok,successful,success

# Yellow
lock,unlock,databases,dump,echo,exit,explain,header,help,indices,mode,mode insert,nullvalue,output,output stdout,prompt,quit,read,separator,show,schema,tables,timeout,width,default,notnull,not null,null,not,auto_increment

# Blue
# 无

# Magenta
charset,engine,table,dumping,dropping,_rowid_,main,oid,rowid,sqlite_master,sqlite_temp_master

# Cyan
if exists,inner join,alter,all,and,as,between,by,case,collate,commit,constraint,create,deferrable,delete,distinct,else,except,foreign,from,glob,group,having,check,in,index,insert,intersect,into,is,isnull,join,like,limit,on,or,order,primary,references,rollback,select,set,then,transaction,union,unique,update,using,values,when,where

# Blinking
# 无
  • perl

不用,懒得贴了。