yum install expect -y
#先安装expectbash
#!/usr/bin/expect #解释语言,这边运行要以./运行,bash运行会报错 spawn ssh root@192.168.0.14 #启动新的进程 expect "*password:" #进程接收字符串,匹配 send "yxy7714707@\r" #前面匹配到了就输入 “ ” 里的内容 expect "*#" send "ifconfig>>123.txt\r" send "exit\r" interact
#!/bin/bash ip=$1 #传递参数 user=$2 password=$3 expect <<EOF set timeout 10 spawn ssh $user@$ip expect { "yes/no" { send "yes\n";exp_continue } "password" { send "$password\n" } } #一个交互用一个expect{} 括起来,这个交互就是登录的 expect "]#" { send "date>>123.txt\n" } expect "]#" { send "exit\n" } #退出 expect eof EOF
#!/bin/bash x=`cat .ssh/id_rsa.pub` ip=$1 password=$2 if [ ! -f "/root/.ssh/id_rsa.pub" ];then echo "文件不存在" expect <<EOF set timeout -1 spawn ssh-keygen -t rsa expect { "Enter file in which to save the key (/root/.ssh/id_rsa):" { send "\r"; exp_continue} #简写 "*(/root/.ssh/id_rsa):" { send "\r"; exp_continue} "Enter passphrase (empty for no passphrase):" { send "\r"; exp_continue} "Enter same passphrase again:" { send "\r"; exp_continue} } #生成私钥 公钥文件(.ssh里的 id_rsa id_rsa.pub的两个文件) expect eof EOF fi expect <<EOF set timeout 10 spawn ssh-copy-id $ip expect { "connecting (yes/no)?" { send "yes\n";exp_continue } #保存对方的密码指纹 "password:" { send "$password\n" } #输入密码 } expect eof EOF
#!/bin/bash expect <<EOF set timeout 10 spawn bash /root/***.sh #打开某个脚本 expect "请输入数字" { send "14\n" } expect "默认:" { send "6\n" } expect eof EOF
PS :注意匹配为模糊匹配,能够不用写全,写个关键字便可ssh