简体   繁体   中英

How to check whether if I'm running the code on a GCP / AWS instance?

is there a way to perform a check to indicate on which platform I am? what I mean by that is not that I want to check whether it's Linux or Darwin I mean I need to check whether I am on a cloud instance, I use GCP and AWS so I need some accurate way.

The only answers I found are in some very old post which checks using os.environ() for a SERVER_NAME which I tried and it does not work. I may hardcode a check for my ip address maybe or anything that works only for me but I think there is a clean solution.

为了可靠的方式,我会查询外部 IP 地址(前提是实例具有互联网连接),例如使用https://ifconfig.me/ ,然后检查答案是否在 AWS/GCP 中IP 地址范围(对于 AWS: https : //docs.aws.amazon.com/general/latest/gr/aws-ip-ranges.html ,我不了解 GCP)。

As long as the hostnames are set for both hosts, you could get the current hostname of the machine the code is running on by using sockets :

import socket
print(socket.gethostname())

Both AWS and GCP use the same URL for instance metadata: http://169.254.169.254

However, the contents that is returned is different. So, you can use that information to determine whether code is running on a cloud system, and which one.

This might change over years, But around 2022 i use below method to check who is the service provider.

ipinfo provides a json result of server basic details. then you can identify using hostname or org

curl ipinfo.io

"hostname": "x.x.x.x.bc.googleusercontent.com",
"hostname": "ec2-x-x-x-x.compute-1.amazonaws.com"
"org": "x Microsoft Corporation"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM