liunx之expect操作详解( 二 )


2.expect脚本实现ssh自动登录远程服务器(通用脚本,手动输入参数)
#!/usr/bin/expectif {$argc < 3} {    puts "Usage:cmd <host> <username> <password>"    exit 1}set timeout -1set host [ lindex $argv 0 ]set username [ lindex $argv 1 ]set password [ lindex $argv 2 ]spawn ssh  $username@$hostexpect "*password*" {send "$password\r"}interact./expect_demo2.sh 192.168.37.9 mrswhite  test20221007  执行查看运行结果:

liunx之expect操作详解

文章插图
 3.在shell 中嵌套expect
通过expect嵌套shell使用语句在shell内直接执行,任何这样可以实现更多的功能
#!/bin/bashuser="mrswhite"host="192.168.37.9"password="test20221007"/usr/bin/expect << EOFset time 20spawn ssh $user@$hostexpect {"*yes/no" { send "yes\r"; exp_continue }"*password:" { send "$password\r" }}expect "*#"send "pwd\r"expect "*#"send "df -h\r"expect "*#"send "exit\r"interactexpect eofEOF
liunx之expect操作详解

文章插图
 五、expect相关错误处理
1.invalid command name "/usr/bin/expect"
liunx之expect操作详解

文章插图
解决方案:此时是使用bash脚本嵌套了expect代码,所以执行采用以下两种方式都可以
./expect_demo3.shsh expect_demo3.sh
liunx之expect操作详解

文章插图
2.invalid command name ":" 转义问题
liunx之expect操作详解

文章插图
解决方案:send里面的内容中的括号[]有问题,不能使用[],将其去除或者添加转义字符
send "cat 20221007.txt | awk -F : '{print $2}'"send "cat 20221007.txt | awk -F \[:\] '{print $2}'\r"
liunx之expect操作详解

文章插图
【liunx之expect操作详解】

经验总结扩展阅读