我需要迭代一系列服务器(许多类型的服务器,每种类型的服务器存储在单独的文件中),在它们上运行一些命令(根据服务器类型存储在不同的文件中)并将输出记录在本地机器,使用带密码的ssh。由于sshpass,ssh密钥身份验证不适用于我的情况,请不要推荐它们。
这是我的代码:
#!/usr/local/bin/expect -f
#Set path to nodes files
NODES=nodes/*
#Set path to commands files
CMD=commands/*
for fn in $NODES
do
echo "Working in $fn"
for fc in $CMD
do
echo "Working in $fc"
if [ ${fn:6:3} = ${fc:9:3} ]
then
# read Nodes from file
while read fn_line; do
#extracting substrings of user, host, password separated by comma
IFS=', ' read -a uhp <<< $fn_line
#establish ssh session to the node
eval spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no ${uhp[0]}@${uhp[1]}
echo ${uhp[0]} ${uhp[1]} ${uhp[2]}
#use correct prompt
set prompt "assword:*"
interact -o -nobuffer -re $prompt return
send "${uhp[2]}\r"
set prompt ":|#|\\\$"
interact -o -nobuffer -re $prompt return
#execute and logging HC commands on the node
while read fc_line; do
#set prompt ":|#|\\\$"
#interact -o -nobuffer -re $prompt return
echo "$fc_line\r" >> logs/${fn:6:3}.log
$fc_line\r >> logs/${fn:6:3}.log
#interact -o -nobuffer -re $prompt return
done < $fc
done < $fn
fi
#cat $f
done
done
我知道在我的代码中,问题是bash和expect解释器的组合。请帮助我只在期待风格中做或者告诉我如何将bash与期望结合起来。其他问题是在建立ssh连接之后的时间,但我认为可以通过将其先前存储在数组中并在建立ssh连接后循环遍历来解决。
答案 0 :(得分:2)
如何编写一个小实用程序,期望生成ssh命令:
#!/usr/bin/expect
set HOST [lindex $argv 0]
set PORT [lindex $argv 1]
set USER [lindex $argv 2]
set PASSWORD [lindex $argv 3]
set COMMAND [join [lrange $argv 4 end] " "]
spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no -p $PORT $USER@$HOST $COMMAND
expect "assword:"
send "$PASSWORD\r"
expect eof
exit
并在像这样的Bash脚本中使用它:
ssh-util <host> <port> <user> <pass> <command>
e.g.
ssh-util 10.0.0.10 22 root s3cr3t ls -la