(5.3)Expect实现ssh非交互登录
原创
©著作权归作者所有:来自51CTO博客作者喜欢打篮球的普通人的原创作品,请联系作者获取转载授权,否则将追究法律责任
文章目录
- 1.ssh 192.168.122.52出现:The fingerprint for the ECDSA key sent by the remote host的相关错误
- 2.Expect解决交互问题
1.ssh 192.168.122.52出现:The fingerprint for the ECDSA key sent by the remote host的相关错误
- vim /root/.ssh/know_hosts,删除192.168.122.52那行,直接输入dd就删除了
2.Expect解决交互问题
- 需要安装:yum install -y expect
- eg1:每走一步,都要写清楚
##指定解释器为expect
#!/usr/bin/expect
spawn ssh root@192.168.222.52 ##开启一个会话
##期望
expect {
"yes/no" { send "yes\r"; exp_continue } ##出现yes/no,\r表示换行,没出现yes/no,也可以exp_continue继续
"password:" { send "centos\r" }; ##出现password怎么做
}
interact##交互,停在对方那边
执行:./expect1.sh 或者expect expect1.sh,这种方式麻烦
一定不是bash执行,若bash执行,会出现以下的错误
#!/usr/bin/expect
##set设置变量
set ip 192.168.122.52
set user root
set password centos
set timeout 5
spawn ssh $user@$ip ##开启一个会话
##期望
expect {
"yes/no"{ send "yes\r"; exp_continue } ##出现yes/no
"password:" { send "$password\r" }; ##出现password怎么做
}
interact##交互,留在登录后的ip终端
==============================================================================
##写成类似shell的位置变量
#!/usr/bin/expect
##set设置变量
set ip [Lindex $argv 0]##相当于$1
set user [Lindex $argv 1]
set password centos
set timeout 5
spawn ssh $user@$ip ##开启一个会话
##期望
expect {
“yes/no”{ send "yes\r"; exp_continue } ##出现yes/no
"password:" { send "$password\r" }; ##出现password怎么做
}
##在远程服务器上执行一些指令
send "useradd yngyang\r" ###\r表示回车
send "pwd\r"
send "exit\r"
expect eof##结束,留在连接ssh的地方
##写成类似shell的位置变量
#!/usr/bin/expect
##set设置变量
set ip [Lindex $argv 0]##相当于$1
set user [Lindex $argv 1]
set password centos
set timeout 5
spawn scp -r /etc/hosts $user@$ip:/tmp ##开启一个会话
##期望
expect {
“yes/no”{ send "yes\r"; exp_continue } ##出现yes/no
"password:" { send "$password\r" }; ##出现password怎么做
}
expect eof##结束,留在连接ssh的地方
#!/bin/bash
##清一下ip,txt文件
>ip.txt
password=centos
##判断expect是否装了
rpm -qa expect &>/dev/null
if [ $? -ne 0];then
yum -y install expect &>/dev/null
fi
##判断密钥对
if [ ! -f ~/.ssh/id_rsa]
ssh-keygen -P "" -f ~/.ssh/id_rsa ## ssh-keygen -P "" -f :-P指定密码为空, -f指定私钥位置
fi
for i in {2..254}
do
{
ip=1.1.2.$i
ping -c1 -W1 $ip &>dev/null
if [ $? -eq 0 ];then
echo "$ip" >>ip.txt
/usr/bin/expect <<-EOF ##一定是tab
set timeout 10
spawn ssh-copy-id $ip
{
“yes/no”{ send "yes\r"; exp_continue } ##出现yes/no
"password:" { send "$password\r" }; ##出现password怎么做
}
expect eof
EOF
fi
}&
done
wait
echo "finish."
执行:sh get_ip1.sh
#!/bin/bash
host_usr=root
host_ip="1.1.1.1"
host_pwd="XXXXXXX"
script_dir="/root/abc_`date +%F`"
expect -c "
spawn scp "scp_test_2021-01-06" ${host_usr}@${host_ip}:/home/wangji
set timeout 5
expect {
\"yes/no\" { send \"yes\r\"; exp_continue}
\"password: \" { send \"${host_pwd}\r\" }
timeout {exit 1}
eof {exit 0}
}
##send \"mkdir -p ${script_dir}\r\"
##send \"exit\r\"
expect eof "