mac上获取ip信息的脚本:
#!/bin/bash
# 检查是否提供了接口名称
if [ -z "$1" ]; then
echo "Please provide a network interface (e.g., en0, en1)."
exit 1
fi
# 获取参数
interface=$1
# 获取 IP 地址
ip_address=$(ifconfig $interface | grep "inet " | awk '{print $2}')
# 获取子网掩码(十六进制转十进制)
subnet_mask_hex=$(ifconfig $interface | grep "netmask" | awk '{print $4}')
# 确保十六进制值没有前导的0x
subnet_mask_hex="${subnet_mask_hex#0x}"
# 将十六进制转换为十进制
subnet_mask_decimal=$(printf "%d.%d.%d.%d\n" $((16#${subnet_mask_hex:0:2})) $((16#${subnet_mask_hex:2:2})) $((16#${subnet_mask_hex:4:2})) $((16#${subnet_mask_hex:6:2})))
# 获取网关
gateway=$(netstat -nr | grep -w default | grep $interface | awk '{print $2}' | head -n 1)
# 获取 DNS(可能有多个DNS,所以使用换行符连接它们)
dns_servers=$(scutil --dns | grep 'nameserver\[[0-9]*\]' | awk '{print $3}' | tr '\n' ' ')
# 输出结果
echo "Interface: $interface"
echo "IP Address: $ip_address"
echo "Subnet Mask (Decimal): $subnet_mask_decimal"
echo "Gateway: $gateway"
echo "DNS: $dns_servers"
发表评论 取消回复