当前存在一个脚本名为 test.sh

但是在执行过程中需要输入密码,该场景可通过expect解决

假设密码是123456 并且在输入密码时出现Passport提示,则可通过以下脚本实现

#!/usr/bin/expect -f

# 设置超时时间为30秒
set timeout 60

# 启动要执行的脚本
spawn ./test.sh

# 等待出现密码提示字符串,这里以常见的"Password:"为例
expect {
    "*Password:*" {
        send "123456\r"
        exp_continue
    }
}

如果是多次输入则

#!/usr/bin/expect -f

# 设置超时时间为30秒
set timeout 60

# 启动要执行的脚本
spawn ./test.sh

# 等待出现密码提示字符串,这里以常见的"Password:"为例
expect {
    "*Password:*" {
        send "123456\r"
        exp_continue
    }
    "*Option>:*" {
        send "3\r"
        exp_continue
    }
}

则 遇到Password输入123456 遇到 Option输入 3

参数

#!/usr/bin/expect -f

# 检查是否传递了至少一个参数
if {[llength $argv] < 1} {
    puts "至少需要传递一个参数"
    exit 1
}

set target [lindex $argv 0]

# 设置超时时间为30秒
set timeout 60

# 启动要执行的脚本
spawn ./sshdd.sh

# 等待出现密码提示字符串,这里以常见的"password:"为例
expect {
    "*Password*" {
        send "xxxxxx\r"
        exp_continue
    }

    "*Option>:*" {
        send "3\r"
        exp_continue
    }
    "*op-sven-opsec01.gz01*" {
        send "dssh $target\r"
        exp_continue
    }
}

以上脚本实现 自动登陆某个ip服务器功能

上面的操作,执行后,在60s后会退出,如果需要长时间停留在后面的页面,则需要interact

脚本执行完指定的交互操作后自动退出,可能是因为没有将控制权交还给用户,导致脚本执行结束后整个进程退出。这通常发生在没有使用 interact 命令的情况下

#!/usr/bin/expect -f

# 检查是否传递了至少一个参数
if {[llength $argv] < 1} {
    puts "至少需要传递一个参数"
    exit 1
}

set target [lindex $argv 0]

# 设置超时时间为30秒
set timeout 60

# 启动要执行的脚本
spawn ./sshdd.sh

# 等待出现密码提示字符串,这里以常见的"password:"为例
expect {
    "*Password*" {
        send "xxxxxx\r"
        exp_continue
    }

    "*Option>:*" {
        send "3\r"
        exp_continue
    }
    "*op-sven-opsec01.gz01*" {
        send "dssh $target\r"
        exp_continue
    }
}

interact

这样的话 是在等待60s无后续操作后,会将操作权交还给用户,如果想在某个操作后,如op-sven-opsec01.gz01之后立即将操作权交还,则可用下面的方式

#!/usr/bin/expect -f

# 检查是否传递了至少一个参数
if {[llength $argv] < 1} {
    puts "至少需要传递一个参数"
    exit 1
}

set target [lindex $argv 0]

# 设置超时时间为30秒
set timeout 60

# 启动要执行的脚本
spawn ./sshdd.sh

# 等待出现密码提示字符串,这里以常见的"password:"为例
expect {
    "*Password*" {
        send "xxxxxx\r"
        exp_continue
    }

    "*Option>:*" {
        send "3\r"
        exp_continue
    }
    "*op-sven-opsec01.gz01*" {
        send "dssh $target\r"
        # 发送命令后等待30秒
        after 30000
        interact
    }
}

interact