我在 Azure 上创建了一个 Ubuntu 16.04LTS VM,我需要访问其面向公众的 IP 以配置我试图在服务器上运行的 docker 容器。但是,当我从 VM 中的终端执行以下命令时:
ip addr show
我只取回私有本地 IP 而不是面向公众的 IP。从 VM 的终端访问公共 IP 需要采取哪些步骤?
我希望能够编写获取公共 IP 的脚本的原因是我们正在 VM 上运行一个 docker 容器(我们正在创建多个 VM,这是我们在 JMeter 中开发的负载测试框架的一部分)并且如果我们可以编写脚本获取 IP 并将其传递给服务器启动脚本中的 docker 容器,然后我们将能够自动启动服务器,以便在我们从 Azure 门户按下启动服务器时,jmeter-server 使用正确的 IP 正常运行。如果无法从 bash 脚本访问公共 IP,我们将不得不手动通过 SSH 连接到每台机器并运行 docker 并将公共 IP 作为参数传递给 docker 以启动每个 jmeter 服务器,这将耗费更多时间。
AWS 和 Azure 中都有这个VM 元数据 东西:
https://azure.microsoft.com/en-us/blog/what-just-happened-to-my-vm-in-vm-metadata-service/
但目前该提要返回的信息很少:
UbuntuInJapan:~$ curl -s http://169.254.169.254/metadata/latest/InstanceInfo
{"ID":"_UbuntuInJapan","UD":"0","FD":"0"}
...只是升级和故障域,对您的努力毫无用处。
对于公共 IP,这是我通常做的:
#!/bin/bash
PUBLIC_IP=$(curl -s http://checkip.amazonaws.com || printf "0.0.0.0")
# Then you either get the public IP address in the variable or you get 0.0.0.0
# which means you could not make the call to Amazon or Amazon is under DDoS.
# amirite?
# Uncomment to echo (AKA debug mode)
echo $PUBLIC_IP
您可以链接多个 我的 IP 是多少? 服务以增加您的 SLA。 即:
# First one that works wins.
# You can improve this by regex checking the output.
#
# Something like:
#
# if [[ $PUBLIC_IP =~ [[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\/ ]]
# then echo 'Good. Valid IPv4. Continue.'
# else echo 'Bad. Stop.'
# fi
UbuntuInJapan:~$ curl -s http://checkip.amazonaws.FAILS || curl -s http://canihazip.com/s
13.78.92.21
如果您与它们交谈 IPv6,某些服务将返回 IPv6,请确保您将地址族显式传递给
curl
:
$ curl -4 http://l2.io/ip
13.78.92.21
$ curl -6 http://l2.io/ip
2a02:2f0b:4xxx:fxxx:4xxx:xxxx:xxxx:1072
为了将来参考,以下作品:
curl -s -H Metadata:true \
http://169.254.169.254/metadata/instance?api-version=2017-04-02 \
| jq -r .network.interface[].ipv4.ipAddress[].publicIpAddress
以下不需要jq
curl -s -H Metadata:true --noproxy "*" \
"http://169.254.169.254/metadata/instance?api-version=2021-02-01" | \
grep -oP --regexp='"publicIpAddress":"\K([[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3})'