Linux命令ssh-copy-id

当然回到工作环境中,如果两台服务器需要建立互信关系,那么需要做的就是拷贝秘钥信息,这个工作就得手工来完成,有时候感觉真是麻烦,但是又无可奈何。

一般建立单向信任关系的步骤如下:

1)检查是否有秘钥生成,如果没有则使用ssh-keygen -t rsa来生成即可。

2)拷贝id_rsa.pub的信息,稍后使用。

3)  ssh连接到目标服务器,然后到.ssh/authorized_keys文件中添加拷贝的id_rsa.pub的内容即可

4)退出当前窗口,重新登录验证,是否可以无密码通信

最近还是看到ssh-copy-id这个神器,看完之后有一种全然一新的感觉,感觉我们之前的处理似乎还是有些老套了。ssh-copy-id可以直接运行这一个命令即可完成上面的步骤,所以这个命令确实是个好东西,难得的是这个命令本身是个shell脚本,所以索性拿来学学。

脚本的内容如下:

#!/bin/sh

# Shell script to install your public key 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/id_rsa.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" > /dev/null ; 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 && (test -x /sbin/restorecon && /sbin/restorecon ~/.ssh ~/.ssh/authorized_keys >/dev/null 2>&1 || true)" || 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

其实看完之后,发现里面确实有不少的内容,命令格式,新的命令都值得学习。

shift是个蛮有意思的命令,可以在不知道位置变量个数的情况下,还能逐个把参数一一处理。
restorecon命令用来恢复SELinux文件属性即恢复文件的安全上下文。

整个脚本中花了大篇幅来处理输入参数,可以手工指定秘钥文件,还有扩展名补全的功能。比如调用脚本的方式如下:
ssh-copy-id -i aaa  [email protected]
这种情况下,脚本会把aaa自动补全扩展名,脚本就会查找aaa.pub的秘钥文件。
 里面最核心的是下面的一句,运行后会提示输入密码。
$ { eval "$GET_ID" ; } |  ssh 10.127.133.125 "umask 077;test -d ~/.ssh || mkdir ~/.ssh ; cat >> ~/.ssh/authorized_keys && (test -x /sbin/restorecon && /sbin/restorecon ~/.ssh ~/.ssh/authorized_keys >/dev/null 2>&1 || true)" || exit 1
 [email protected]'s password:
可以看到整个脚本有很多需要考虑的细节,值得玩味。
 当然大道至简,这个脚本的本质就是传输id_rsa.pub并不会自动帮你去生成id_rsa.pub,最核心的功能就是把秘钥信息写入.ssh/authorized_keys中。
 所以整个过程的简化版思路就是下面的一个类似的命令形式。
$ echo "aaaaa"|ssh 10.127.133.125 "cat"
 [email protected]'s password:
 aaaaa
 echo "aaaaa"会输出秘钥信息,然后通过管道作为ssh到目标端的参数值调用
 所以这个过程也完全可以自己定义命令来完成。
 明白了这些,很多工具就会脱离开神圣的外衣,而对于我们来说,明白了核心的部分,就需要学习哪些场景没有考虑周到,不断去补充,不断完善。

猜你喜欢

转载自www.linuxidc.com/Linux/2016-09/135532.htm