您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。