有时候我们需要批量发送ssh命令给服务器,但是有可能有些服务器是新加入的,还没有配置ssh免密,这个时候就会提示我们输入yes/no 或者password等,expect脚本命令就是用于在提示这些的时候,自动为我们输入相应的文字
先看一段shell脚本,实现了ssh自动连接
- #!/usr/bin/expect
- spawn ssh 192.168.1.241
- expect "password"
- send "123456\r"
- expect "]#" {send "ls -la\r"}
- interact
注意第一行使用的是#!/usr/bin/expect而不是普通的bash脚本那样
,注意\r代表换行,跟我们输入完一个命令换行是一个道理。
上面的这种expect属于单一分支模式,代表就匹配这一种,如果匹配的不是,那么就要自己输入了,但是我们有可能在第一次有不同的提示,这个时候就需要使用多分支语法
expect 只要匹配到aaa 或者password其中的一种就会输出。
- #!/usr/bin/expect
- spawn ssh 192.168.1.241
- expect {
- "aaa" {send "bbb\r"}
- "password" { send "nf123456\r"}
- }
- expect "]#" {send "ls -la\r"}
- interact
上面的expect脚本功能可能都达到了,为了避免有很多expect脚本,我更推荐使用expect命令
- # ! /bin/bash
- SERVER = "192.168.1.241"PASSWD = nf123456
- expect - c "
- set timeout -1;
- spawn ssh $SERVER;
- expect {
- \"yes/no\" { send \"yes\r\" ;exp_contine; }
- \"password:\" { send \"$PASSWD\r\"; }
- };
- expect \"]#\" { send \"ls -la \r\" };
- expect \"]#\" { send \"exit \r\" };
- expect eof;
- "
上面的shell功能和expect脚本实现的功能一致,都是通过ssh登录进去后输入,ls -la 命令
- #!/bin/bash
- SERVERS="192.168.1.241 192.168.1.242"
- PASSWD="123456"
- function sshcopyid
- {
- expect -c "
- set timeout -1;
- spawn ssh-copy-id $1;
- expect {
- \"yes/no\" { send \"yes\r\" ;exp_contine; }
- \"password:\" { send \"$PASSWD\r\";exp_continue; }
- };
- expect eof;
- "
- }
- for server in $SERVERS
- do
- sshcopyid $server
- done
来源: http://www.cnblogs.com/nfcm/p/7899831.html