ssh连接远程主机时候询问密码,跟su、sudo命令的默认行为一样,是不从stdin读入数据的,据称是为安全考虑,但是有时候在脚本当中确实需要无人守值的登陆
参见auto_ssh.sh脚本实例:
#!/bin/bash
# Destription: Creating a trust relationship between the host1-to-host2
# parameters : sh auto_ssh.sh 10.71.115.155 Password
# Auther : xxxxxxx
# Date : 2015-2-2
remote_ip=$1
remote_Password=$2
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
}
#===========================scp
function copy_key()
{
expect -c "
set timeout 2
spawn scp -o StrictHostKeyChecking=no -r /root/.ssh/id_rsa.pub $remote_ip:/root/.ssh/$remote_ip
expect {
\"*Password*\" { send \"$remote_Password\r\" }
}
set timeout 3
expect eof
"
}
#===========================ssh
function authorized_keys()
{
expect -c "
set timeout 2
spawn ssh -o StrictHostKeyChecking=no $remote_ip
expect {
\"*Password*\" { send \"$remote_Password\r\" }
}
set timeout 3
expect \"*:~*#\"
send \"cat /root/.ssh/$remote_ip >> /root/.ssh/authorized_keys\r\"
send \"rm /root/.ssh/$remote_ip\r\"
send \"exec /usr/bin/ssh-agent $SHELL;ssh-add\r\"
set timeout 2
expect eof
"
}
# 正式开始运行脚本
#----------------------------------------------
if [ $# -le 1 ];then
usage;
exit 1;
fi
echo -e "\\033[1;32m `date +%Y-%m-%d\ %H:%M:%S` Now runing make_ssh_key \\033[1;37m"
make_ssh_key >/dev/null 2>&1;
echo -e "\\033[1;32m `date +%Y-%m-%d\ %H:%M:%S` Now runing copy_key \\033[1;37m"
copy_key >/dev/null 2>&1;
echo -e "\\033[1;32m `date +%Y-%m-%d\ %H:%M:%S` Now runing authorized_keys \\033[1;37m"
authorized_keys >/dev/null 2>&1;
echo -e "\\033[1;32m =====================>Please ssh $remote_ip \\033[1;37m"