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