首页 > 解决方案 > 使用脚本将批量命令从文件发送到防火墙

问题描述

下面是我的脚本,它在 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

标签: linuxbashexpectsend

解决方案


echoread是 shell 命令,但你在期望代码中有它们。你的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

推荐阅读