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