问题描述
我想获得一个随机未使用的端口,以便可以wait_for
使用它。最好是在动态端口范围内,但在这一点上,我并不挑剔。我使用的是Linux,并且不必与Windows或Mac兼容。
虽然此问题被标记为已回答,但如果有人可以简化此过程且对shell的调用较少,请在下面将其发布。我不在乎这个问题是否已有四岁了。
解决方法
如评论中所述,您不想wait_for
端口,而是打开一个端口并等待ping操作。
我不知道获得随机端口的简单方法,因此我编写了一个小shell脚本来查找一个端口:
- hosts: all
tasks:
- name: find port
shell: |
PORT=5000
while true; do
ss -tulpen | grep ":${PORT}" &> /dev/null
if [[ "$?" == "1" ]]; then
echo "${PORT}"
exit
fi
((PORT++))
done
args:
executable: /bin/bash
register: port
- name: print port
debug:
msg: "{{ port.stdout }}"
- name: wait for ping
shell: nc -l "{{ port.stdout }}"
- name: debug
debug:
msg: "Ping received"
这将查找端口,将其打印给您,然后打开该端口,并使用netcat
等待ping。收到ping后,它会显示一条消息。
在Ubuntu上测试过。您可能需要为netcat
(或此处为nc
)使用不同的参数,因为不同的发行版会提供不同的版本。
编辑:
将ping发送到端口后,您需要关闭TCP连接,因为netcat
仅在关闭连接后退出。