1. 程式人生 > >expect寫腳本

expect寫腳本

expect

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 root@$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
[root@localhost 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
[root@apenglinux-002 ~]#

expect遠程登錄另外一臺機器並執行命令

vim expect-login-exec.sh 
#! /usr/bin/expect
set host "192.168.221.20"
set passwd "root"
spawn ssh root@$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"

[root@localhost expect]# chmod +x expect-login-exec.sh 
[root@localhost 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
[root@apenglinux-002 ~]# touch /tmp/expect.txt
[root@apenglinux-002 ~]# echo expect > /tmp/expect.txt
[root@apenglinux-002 ~]# [root@localhost expect]

expect寫腳本