我正在尝试使用来自hosts文件特定部分的shell脚本从属性文件(ansible hosts文件)中获取值。
所以我有这个主机文件:
[windows]
myd-vm14945.company.net
myd-vm01431.company.net
[windows-web]
vmpweb314.company.net
[linux]
myd-vm11409.company.net
myd-vm14296.company.net
myd-vm20125.company.net
mydvm0091.company.net
我希望运行此脚本,当 Linux 部分下的每个服务器都应该替换shell脚本中的参数 $ {REMOTE_SERVER} 时:
#add remote server to ansible host known_host file
ssh-keyscan ${REMOTE_SERVER}>> /root/.ssh/known_hosts
#remmber password
sshpass -p ROOT_PASSWORD ssh root@${REMOTE_SERVER}
这样最终结果就是这样:
#add remote server to ansible host known_host file
ssh-keyscan myd-vm11409.company.net >> /root/.ssh/known_hosts
ssh-keyscan myd-vm14296.company.net>> /root/.ssh/known_hosts
#remmber password
sshpass -p ROOT_PASSWORD ssh root@myd-vm11409.company.net
sshpass -p ROOT_PASSWORD ssh root@myd-vm14296.company.net
等等......对于Linux下的所有值。
答案 0 :(得分:1)
如果您真的想通过bash进行此操作,请参阅以下awk
魔法,部分取自Read certain key from certain section of ini file (sed/awk ?)
因此,您可以创建以下脚本,调整您的库存文件和部分并运行它!
<强> addkeys.sh 强>
#!/bin/bash
INVENTORY="inventory.ini"
SECTION="[linux]"
I_HOSTS="$(awk -v section="$SECTION" ' # Enable a flag when the line is like your section
$0==section{ f=1; next } # For any lines with [ disable the flag
/\[/{ f=0; next } # If flag is set - print the line
f && $0' "$INVENTORY")"
for I_HOST in $I_HOSTS
do
#add remote server to ansible host known_host file
echo "ssh-keyscan "$I_HOST" >> /root/.ssh/known_hosts"
#remmber password
echo "sshpass -p ROOT_PASSWORD ssh "root@$I_HOST""
done
使用echo sshpass和keyscan commads的结果:
ssh-keyscan myd-vm11409.company.net >> /root/.ssh/known_hosts
sshpass -p ROOT_PASSWORD ssh root@myd-vm11409.company.net
ssh-keyscan myd-vm14296.company.net >> /root/.ssh/known_hosts
sshpass -p ROOT_PASSWORD ssh root@myd-vm14296.company.net
ssh-keyscan myd-vm20125.company.net >> /root/.ssh/known_hosts
sshpass -p ROOT_PASSWORD ssh root@myd-vm20125.company.net
ssh-keyscan mydvm0091.company.net >> /root/.ssh/known_hosts
sshpass -p ROOT_PASSWORD ssh root@mydvm0091.company.net