ssh-copy-id 是Linux 一个标准的命令行程序,用来时,实现公钥认证的ssh登陆。
在Linux下使用ssh-copy-id 可以轻松地实现本机到远程主机的公钥认证的ssh登录;
ssh-copy-id remote-host
这次是密码登录,执行完成后,会将本机公钥注入到远程主机remote-host的.ssh/authorized_keys 中。
以后,就可以直接,
ssh remote-host
无密码登录;
最近,刚刚使用mac, 希望在mac上通过ssh-copy-id 打通到测试环境的机器的公钥认证登录机制;
可是在mac上找不到ssh-copy-id这个脚本, 发现在Linux 下ssh-copy-id只是一个shell脚本,
借助了ssh相关工具集。
其内容如下:
ssh-copy-id:
#!/bin/sh
# Shell script to install your identity.pub on a remote machine
# Takes the remote machine name as an argument.
# Obviously, the remote machine must accept password authentication,
# or one of the other keys in your ssh-agent, for this to work.
ID_FILE="${HOME}/.ssh/identity.pub"
if [ "-i" = "$1" ]; then
shift
# check if we have 2 parameters left, if so the first is the new ID file
if [ -n "$2" ]; then
if expr "$1" : ".*\.pub" ; then
ID_FILE="$1"
else
ID_FILE="$1.pub"
fi
shift # and this should leave $1 as the target name
fi
else
if [ x$SSH_AUTH_SOCK != x ] ; then
GET_ID="$GET_ID ssh-add -L"
fi
fi
if [ -z "`eval $GET_ID`" ] && [ -r "${ID_FILE}" ] ; then
GET_ID="cat ${ID_FILE}"
fi
if [ -z "`eval $GET_ID`" ]; then
echo "$0: ERROR: No identities found" >&2
exit 1
fi
if [ "$#" -lt 1 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
echo "Usage: $0 [-i [identity_file]] [user@]machine" >&2
exit 1
fi
{ eval "$GET_ID" ; } | ssh $1 "umask 077; test -d .ssh || mkdir .ssh ; cat >> .ssh/authorized_keys" || exit 1
cat <<EOF
Now try logging into the machine, with "ssh '$1'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.
EOF
见其源码,其实现机制并不复杂,核心逻辑是:
{ eval "$GET_ID" ; } | ssh $1 "umask 077; test -d .ssh || mkdir .ssh ; cat >> .ssh/authorized_keys" || exit 1
再看使用帮助如下:
[zhongbo.wzb@scala ~]$ ssh-copy-id
Usage: /usr/local/bin/ssh-copy-id [-i [identity_file]] [user@]machine
[zhongbo.wzb@scala ~]$ cd ~/.ssh
[zhongbo.wzb@scala ~/.ssh]$ ls
. .. config id_rsa id_rsa.pub identity.pub known_hosts
[zhongbo.wzb@scala ~/.ssh]$
1. 将文件ssh-copy-id shell script 拷贝到mac的/usr/local/bin/ssh-copy-id
2. 查看~/.ssh/目录下是否有identity.pub 文件, 如果存在可以直接执行:
ssh-copy-id remote-host
来打通ssh 到remote-host的公钥认证登录;
如果不存在identity.pub 文件,存在id_rsa.pub文件,
可以直接执行:
ssh-copy-id -i ~/.ssh/id_rsa.pub remote-host
通过公钥id_rsa.pub来打通到remote-host的公钥认证;
如果,id_rsa.pub也不存在,可以通过如下方法生成id_rsa.pub
如:
ssh-keygen -t rsa
一路回车,就可以生生成id_rsa.pub
再按如上方法执行。