shell腳本實現ssh自動登陸遠程服務器示例: java
#!/usr/bin/expect spawn ssh root@192.168.22.194 expect "*password:" send "123\r" expect "*#" interact
Expect是一個用來處理交互的命令。藉助Expect,咱們能夠將交互過程寫在一個腳本上,使之自動化完成。形象的說,ssh登陸,ftp登陸等都符合交互的定義。下文咱們首先提出一個問題,而後介紹基礎知四個命令,最後提出解決方法。 正則表達式
問題: shell
如何從機器A上ssh到機器B上,而後執行機器B上的命令?如何使之自動化完成? 服務器
Expect中最關鍵的四個命令是send,expect,spawn,interact。 ssh
send:用於向進程發送字符串 expect:從進程接收字符串 spawn:啓動新的進程 interact:容許用戶交互
send命令接收一個字符串參數,並將該參數發送到進程。 spa
expect1.1> send "hello world\n" hello world
expect "hi\n" send "hello there!\n"
expect "hi\n" send "you typed <$expect_out(buffer)>" send "but I only expected <$expect_out(0,string)>"
test hi
you typed: test hi I only expect: hi
expect "hi" {send "You said hi"}
expect "hi" { send "You said hi\n" } \ "hello" { send "Hello yourself\n" } \ "bye" { send "That was unexpected\n" }
expect { "hi" { send "You said hi\n"} "hello" { send "Hello yourself\n"} "bye" { send "That was unexpected\n"} }
set timeout -1 spawn ftp ftp.test.com //打開新的進程,該進程用戶鏈接遠程ftp服務器 expect "Name" //進程返回Name時 send "user\r" //向進程輸入anonymous\r expect "Password:" //進程返回Password:時 send "123456\r" //向進程輸入don@libes.com\r expect "ftp> " //進程返回ftp>時 send "binary\r" //向進程輸入binary\r expect "ftp> " //進程返回ftp>時 send "get test.tar.gz\r" //向進程輸入get test.tar.gz\r
spawn ftp ftp.test.com expect "Name" send "user\r" expect "Password:" send "123456\r" interact
#!/home/tools/bin/64/expect -f set timeout -1 spawn ssh $BUser@$BHost expect "*password:" { send "$password\r" } expect "$*" { send "pwd\r" } interact