linux - 使用脚本将批量命令从文件发送到防火墙
问题描述
下面是我的脚本,它在 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
解决方案
echo
和read
是 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
推荐阅读
- php - 如何在搜索后先进行完全匹配,然后再进行部分匹配
- x86 - x86:切换页面目录后调用指令出现三重错误
- javascript - 如何使用 HTML 按钮暂停一个简单的画布游戏?
- gtsummary - 为什么函数“round”不适用于 p 值的数字?以及如何使用“gtsummary”调整汇总表中的百分比数字?
- arrays - YAML 将多个数组合并为一个
- spring-boot - 我可以向 cognito 访问令牌端点发送多少并发请求 - POST /oauth2/token
- python - 在 PyQt5 中的选项卡右侧添加图标
- angular - 在 ngx dropzone 中显示来自服务器的图像
- python - 同一图像的分类给出不同的结果
- safari - Safari - createMediaElementSource 不起作用?