想在ssh中,让一个host通过不同的hostname连接:
- 在学校网段,则通过教育网ip连接
- 否则,通过tunnel连接
方案:Match关键字。
Match originalhost example-host exec "python checkipthu.py"
HostName 203.0.113.1
Port 22
User your-username
Host example-host
# use tunnel
HostName 192.0.2.1
User your-username
Port 12345注意两个设置的先后顺序,会先尝试match前面的。
checkipthu.py是一个判断ip网段的python脚本:
import requests
import ipaddress
# 清华的网段列表
tsinghua_networks = [
"166.111.0.0/16",
"101.5.0.0/16",
"101.6.0.0/16",
"59.66.0.0/16",
"183.172.0.0/16",
"183.173.0.0/16",
"118.229.0.0/20"
]
# 获取当前IPv4地址
def get_public_ip():
try:
response = requests.get('https://ipv4.icanhazip.com', timeout=5)
response.raise_for_status()
return response.text.strip()
except requests.RequestException as e:
print(f"Error fetching IP address: {e}")
return None
# 判断IP是否在清华的网段内
def is_in_tsinghua_network(ip):
ip_address = ipaddress.ip_address(ip)
for network in tsinghua_networks:
if ip_address in ipaddress.ip_network(network):
return True
return False
# 主函数
def main():
ip = get_public_ip()
if ip is None:
print("Failed to get IP.")
exit(-1)
if is_in_tsinghua_network(ip):
print(f"IP {ip} is in Tsinghua network.")
exit(0)
else:
print(f"IP {ip} is NOT in Tsinghua network.")
exit(1)
if __name__ == "__main__":
main()