gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:06:58 25 4
gpt4 key购买 nike

下面是我的脚本,它在 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 循环有同样的问题。

您可以简单地使用 expect 来完成整个任务,而不是混合使用 shell 和 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

关于linux - 使用脚本将批量命令从文件发送到防火墙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51877457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com