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

Linux 使用脚本将批量命令从文件发送到防火墙,linux,bash,expect,send,Linux,Bash,Expect,Send,下面是我的脚本,它在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/I

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

expect
echo
read
是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
#/usr/bin/expect-f
设置用户名$env(用户)
#从用户处读取主机名
send_user“输入主机名:”
预期\u用户-re“(.*)\n”
设置主机名$expect\u out(1,字符串)
#从用户处读取密码,无需回显屏幕
stty-echo
发送用户--“$username@$hostname的密码:”
预期\u用户-re“(.*)\n”
发送\u用户“\n”
短回声
设置密码$expect\u out(1,字符串)
#宣布我们正在使用的设备和时间
发送\u用户“\n”

send_user“>>>>>使用$hostname@[timestamp-format”%a%b%d%Y,%T“]谢谢你的回复Glenn,我会检查这个,如果有任何问题,我会回来。我根据防火墙输出测试了一些小的调整,效果很好!!再次感谢!看看你可以用哪些方法只使用shell代码编写Expect脚本。