ssh_互信 简洁实例__代码

ssh连接远程主机时候询问密码,跟su、sudo命令的默认行为一样,是不从stdin读入数据的,据称是为安全考虑,但是有时候在脚本当中确实需要无人守值的登陆
简介简单的方式写一段代码,描述思路;

参见create_ssh.sh脚本实例:

#!/bin/bash 
# Destription: Creating a trust relationship between the host1-to-host2
# parameters : sh create_ssh.sh 128.128.128.1 Password
# Auther : xxxxxxx
# Date : 2015-5-13

remote_ip=$1
remote_Password=$2
ping_total=$(ping -c 2 $remote_ip | grep -c "64 bytes from";)
if [ $# -ne 2 ]; then
    echo "Usage:"
    echo "$0 remote_ip remote_Password "
    exit 1
fi

#===========================key
function make_ssh_key()
{
  echo  y|ssh-keygen  -t  rsa -P '' -f /root/.ssh/id_rsa   >/dev/null 2>&1;
  echo -e "\\033[1;32m `date +%Y-%m-%d\ %H:%M:%S` Now runing make_ssh_key \\033[1;37m"
}

#===========================scp
function copy_key()
{
  if [ $ping_total == 2 ]; then
   expect -c " set timeout 2 spawn ssh-copy-id -i /root/.ssh/id_rsa $remote_ip expect { \"*Password*\" { send \"$remote_Password\r\" } } set timeout 3 expect eof " 
        echo -e "\\033[1;32m `date +%Y-%m-%d\ %H:%M:%S` successfully to ssh $remote_ip \\033[1;37m"
      else
        echo -e "\\033[1;32m `date +%Y-%m-%d\ %H:%M:%S` Destination Host Unreachable $remote_ip \\033[1;37m"
        exit 1
     fi
}

#===========================ssh
function ssh_Test()
{
   if [ $ping_total == 2 ]; then
     ssh -i /root/.ssh/id_rsa $remote_ip
    else
        echo -e "\\033[1;32m `date +%Y-%m-%d\ %H:%M:%S` connect to host $remote_ip port 22: No route to host \\033[1;37m"
        exit 1
     fi
}

make_ssh_key $@
copy_key $@
ssh_Test $@
exit 0

你可能感兴趣的:(linux)