免输入密码登录

不需要iterm和zoc等第三方软件,alias(纯终端)和shuttle(有UI)两种方式使用密码(不需要手动输入)登录目标机器

准备工具

sshpass,shuttle

密码配置文件

密码文件(明文存储,若考虑强安全问题,请绕道) 格式:hostname(已在系统hosts文件定义), user, password, ssh_port

$ cat /Users/zhang/zhangsan/work/secure 
vm-001 root 123456 1122
vm-002 root 123456 22

脚本

  1. 核心脚本
$ cat /Users/zhang/zhangsan/work/ssh.sh 
#!/bin/sh
WORK_DIR=$(dirname $0)
cd $WORK_DIR

HOST=$1;
USER=$2;
if [ "x${HOST}" == "x" -o "x${USER}" == "x" ]; then
    exit 2
fi
PASS_PORT=$(grep -E "^$HOST\s+$USER\s+" secure)
PASS=$(echo $PASS_PORT | awk '{print $3}')
PORT=$(echo $PASS_PORT | awk '{print $4}')
if [ "x${PASS}" == "x" -o "x${PORT}" == "x" ]; then
    exit 2
fi
exec sshpass -p $PASS ssh -p $PORT $USER@$HOST

更新逻辑脚本存储至~/.bash_profile, 用户每次登录会根据secure重新生成alias和shuttle所需的配置文件

  1. alias 在~/.bash_profile中添加以下脚本后,更新alias
while read LINE
do
    if [ "x${LINE}" == "x" ]; then
        continue
    fi
    SSH_HOST=$(echo "$LINE" | awk '{print $1}')
    SSH_USER=$(echo "$LINE" | awk '{print $2}')
    alias "$SSH_HOST$SSH_USER"="sh /Users/zhang/zhangsan/work/ssh.sh $SSH_HOST $SSH_USER"
done < /Users/zhang/zhangsan/work/secure
  1. shuttle 生成shuttle配置的python脚本
$ cat /Users/zhang/zhangsan/work/shuttle.py 
import json
shuttle = {
  "editor": "default",
  "launch_at_login": True,
  "terminal": "Terminal.app",
  "iTerm_version": "nightly",
  "default_theme": "Default",
  "open_in": "tab",  
  "show_ssh_config_hosts": False,
  "ssh_config_ignore_hosts": [],
  "ssh_config_ignore_keywords": [],
  "hosts": []
}

with open("/Users/zhang/zhangsan/work/secure", "r") as f:
    while True:
        line = f.readline()
        if not line:
            break
        HOST_PORT = line.split()
        if len(HOST_PORT) >= 3:
            HOST, PORT = HOST_PORT[0], HOST_PORT[1]
            shuttle["hosts"].append({"cmd": "sh /Users/zhang/zhangsan/work/ssh.sh {HOST} {PORT}".format(HOST=HOST, PORT=PORT) , "name": "{HOST} {PORT}".format(HOST=HOST, PORT=PORT)})

with open("/Users/zhang/.shuttle.json", "w") as f:
    json.dump(shuttle, f, indent=2)

在~/.bash_profile中添加python /Users/zhang/zhangsan/work/shuttle.py,生成shuttle配置文件

备注

如果输入alias中的vm-001root不能登录,有可能是~/.ssh/known_hosts中没有目标节点,先执行下ssh vm-001将其添加至列表中即可

mac下的zoc本来也是简单好用的一款ssh客户端,但已崩溃多次(正版会不会好点)

参考链接

下载shuttle 安装sshpass