expect写脚本
~/.ssh/know_hosts文件 [远程ip:公钥]
当我们使用公钥去ssh连接一台远程主机时,系统默认会把访问过的主机的公钥都记录在 ~/.ssh/know_hosts
cat ~/.ssh/known_hosts
192.168.221.20 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBHzi7l7PDXCUwFW6Xy6Ipg7FwTwHT9oiEfpHSqTTm1pBc0abAGgBjh8KwqkhmP+Au4D4+1k8XiZGvo0TYhSTi+c=
expect远程登录另外一台机器
yum install expect -y
vim /usr/local/sbin/expect/expect-login.sh
#! /usr/bin/expect //注意与“#!/bin/bash”区分开来
set host "192.168.221.20" //设置2个变量host,passwd
set passwd "root"
spawn ssh [email protected]$host
expect {
"yes/no" { send "yes\r"; exp_continue}
"password:" { send "$passwd\r" }
}
interact //停留在远程机器上不退出来 expect eof 停留在远程机器上一会儿再退出
chmod +x /usr/local/sbin/expect/expect-login.sh
[[email protected] expect]# ./expect-login.sh //特别注意不能用bash去执行
spawn ssh [email protected]
[email protected]‘s password:
Last login: Sun Mar 18 10:33:33 2018 from 192.168.221.10
[[email protected] ~]#
expect远程登录另外一台机器并执行命令
vim expect-login-exec.sh
#! /usr/bin/expect
set host "192.168.221.20"
set passwd "root"
spawn ssh [email protected]$host
expect {
"yes/no" { send "yes\r"; exp_continue}
"password:" { send "$passwd\r" }
}
expect "]*"
send "touch /tmp/expect.txt\r"
expect "]*"
send "echo expect > /tmp/expect.txt\r"
expect "]*"
send "exit\r"
[[email protected] expect]# chmod +x expect-login-exec.sh
[[email protected] expect]# ./expect-login-exec.sh
spawn ssh [email protected]
[email protected]‘s password:
Last login: Sun Mar 18 11:14:46 2018 from 192.168.221.10
[[email protected] ~]# touch /tmp/expect.txt
[[email protected] ~]# echo expect > /tmp/expect.txt
[[email protected] ~]# [[email protected] expect]
原文地址:http://blog.51cto.com/13480443/2088099
时间: 2024-10-10 11:00:34