您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
yum install expect -y
#先安装expect
#!/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 :注意匹配为模糊匹配,可以不用写全,写个关键字即可
实战脚本
yum install expect -y
fsip=192.168.0.25
password=yxy7714707@
expect <<EOF
set timeout 10
spawn scp /etc/hosts $fsip:/etc/hosts
expect {
"connecting (yes/no)?" { send "yes\n";exp_continue }
#保存对方的密码指纹
"password:" { send "$password\n" }
#输入密码
}
expect eof
EOF
#脚本用途,传送本地的hosts文件给 对方
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。