Skip to content

Commit e9d7d18

Browse files
committed
make code easy to use and add notes
1 parent ded0441 commit e9d7d18

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

projects/LinuxSystemOps/Security/ssh/allow-access-port-on-remote-host.py

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,17 @@
1818
2. construct the cmd: remove old rule, add new rule
1919
3. execute the command on remote host via SSH protocol
2020
21+
Other IP APIs:
22+
http://ping.pe/
23+
https://www.ipip.net/ip.html
24+
https://ip138.com/
25+
https://ipinfo.io/
26+
https://ifconfig.me/
27+
https://httpbin.org/ip
28+
http://cip.cc
29+
https://ip.cn
30+
https://ident.me
31+
2132
References: projects/others/aliyun/ECS/SecurityGroup/add-Internet-IP-to-aliyun-ecs-security-group.py
2233
Prerequisites: pip install requests
2334
pip install paramiko
@@ -34,15 +45,17 @@
3445

3546
import requests
3647

48+
# TODO(DingGuodong) known issue: the(some) api will return IPv6 address which is not wanted.
3749
IP_QUERY_API_S1 = "https://ifconfig.co/ip"
38-
IP_QUERY_API_S2 = "https://api.ip.sb/ip"
50+
IP_QUERY_API_S2 = "https://api-ipv4.ip.sb/ip"
3951

4052

4153
def get_public_ip_from_api(api):
42-
query_ip_api_url = api
54+
query_ip_api_url = api.strip()
4355

4456
headers = {
4557
'Cache-Control': "no-cache",
58+
"User-Agent": "curl/7.55.1",
4659
}
4760

4861
data = ""
@@ -51,6 +64,8 @@ def get_public_ip_from_api(api):
5164
response = requests.request("GET", query_ip_api_url, headers=headers, timeout=(10, 5))
5265
if response.ok:
5366
data = response.text.strip()
67+
else:
68+
print("API {api} status code: {code}".format(api=api, code=response.status_code))
5469
except Exception as _:
5570
del _
5671

@@ -59,7 +74,10 @@ def get_public_ip_from_api(api):
5974

6075
def get_public_ip():
6176
ip1, ip2 = map(get_public_ip_from_api, (IP_QUERY_API_S1, IP_QUERY_API_S2))
62-
return ip1 if ip1 != "" else ip2
77+
ip = ip1 if ip1 != "" and ":" not in ip1 else ip2
78+
if ip == "":
79+
raise AssertionError("can NOT get IP from APIs, terminated.")
80+
return ip
6381

6482

6583
def execute_commands_on_remote_host(host, command, **kwargs):
@@ -93,6 +111,7 @@ def execute_commands_on_remote_host(host, command, **kwargs):
93111

94112
if __name__ == '__main__':
95113
internet_ip = get_public_ip()
114+
print("Current public IP address is {}".format(internet_ip))
96115

97116
# Tips: `| awk '$1=$1'` 或 `| awk 'NF--'` 去除字符串两端的(多个)空格,
98117
# Decrementing NF causes the values of fields past the new value to be lost,

0 commit comments

Comments
 (0)