使用脚本将批量命令从文件发送到防火墙

Send bulk commands from a file to firewall using a script

下面是我的脚本,在command.txt中有命令,使用spawn对防火墙进行ssh,无法执行echo命令输入防火墙名称,不明白是什么问题。

!/bin/bash

expect <<'END'

# Set variables

set username $env(USER)
set password [lindex $argv 1]

echo 'Please enter FQDN/IP address of the FW'

read -p 'Firewall FQDN/IP: ' hostname

# Announce which device we are working on and at what time
send_user "\n"
send_user ">>>>>  Working on $hostname @ [exec date] <<<<<\n"
send_user "\n"

# Don't check keys
spawn ssh -o StrictHostKeyChecking=no $username\@$hostname

# send bulk commands to hostname from a file commands.txt
for commands in `cat $commands.txt`; do
    send "$commands";
done
send -- "exit\n"

END

echoread 是 shell 命令,但您在 expect 代码中有它们。你的 for 循环有同样的问题。

无需混合使用 shell 和 expect 代码,您可以简单地使用 expect 完成整个任务:我还让用户输入密码,而不是在命令行上提供密码。

#!/usr/bin/expect -f

set username $env(USER)

# read the hostname from the user
send_user "Enter the hostname: "
expect_user -re "(.*)\n"
set hostname $expect_out(1,string)

# read the password from the user, without echoing to the screen
stty -echo
send_user -- "Password for $username@$hostname: "
expect_user -re "(.*)\n"
send_user "\n"
stty echo
set password $expect_out(1,string)

# Announce which device we are working on and at what time
send_user "\n"
send_user ">>>>>  Working on $hostname @ [timestamp -format "%a %b %d %Y, %T"] <<<<<\n"
send_user "\n"

# Don't check keys
spawn ssh -o StrictHostKeyChecking=no $username@$hostname

expect {
    "assword:" {send -- "$password\r"}
    timeout    {error "Did not see password prompt in $timeout seconds"}
}

set fh [open commands.txt r]
while {[gets $fh command] != -1} {
    # Here, waiting for your prompt. 
    # If it does not end with dollar and space, change this pattern
    expect -re {$ $}           
    send "$command\r";
}
close $fh

expect -re {$ $}           
send -- "exit\n"
expect eof