Skip to content

Instantly share code, notes, and snippets.

@pd12bbf7608ae1
Created May 7, 2022 03:00
Show Gist options
  • Save pd12bbf7608ae1/02c655bea5edec583fad4687a7732220 to your computer and use it in GitHub Desktop.
Save pd12bbf7608ae1/02c655bea5edec583fad4687a7732220 to your computer and use it in GitHub Desktop.
get port info from switch
#!/bin/bash
ip='192.168.1.1'
username='admin'
password='123456789'
# curl -w "\nCode:%{response_code}\n" "http://${ip}" # 获取登录状态
# curl 'http://192.168.1.1/logon.cgi' --data-raw 'username=admin&password=123456789&logon=%E7%99%BB%E5%BD%95' # 登录
# curl 'http://192.168.1.1/logon.cgi' -d "username=admin" -d "password=123456789" -d "logon=%E7%99%BB%E5%BD%95" # 登录
# curl 'http://192.168.1.1/Logout.htm' # 登出
# curl 'http://192.168.1.1/PortStatisticsRpm.htm' # 获取信息
# cat info_sg2008.html | grep 'var max_port_num' | cut -d '=' -f 2 | sed -n -e 's/[[:blank:]]*\([0-9]\+\).*/\1/p' # 总端口数目
# cat info_sg2008.html | grep "^state" | cut -d ':' -f 2 | sed -e 's/.*\[//g' -e 's/\].*//g' | tr ',' ' ' # 获取端口链路状态 (数组)
# cat info_sg2008.html | grep "^link_status" | cut -d ':' -f 2 | sed -e 's/.*\[//g' -e 's/\].*//g' | tr ',' ' ' # 获取端口链路状态 (数组)
curlInfo=$(curl -s --max-time 5 -X "GET" -w "\nCode:%{response_code}\n" "http://${ip}/PortStatisticsRpm.htm")
curlCode="$?"
if [[ "${curlCode}" -ne "0" ]]; then # curl出错
echo "curl Error!" 1>&2
echo "curlCode:${curlCode}" 1>&2
exit 1
fi
httpCode=$(echo "${curlInfo}" | tail -1 | cut -d ':' -f 2)
# echo $httpCode
if [[ "${httpCode}" -eq "401" ]]; then # 没有登录
echo "login..." 1>&2
curlInfo=$(curl -s --max-time 5 -X "POST" -d "username=${username}" -d "password=${password}" -d "logon=%E7%99%BB%E5%BD%95" -w "\nCode:%{response_code}\n" "http://${ip}/logon.cgi") # 登录
curlInfo=$(curl -s --max-time 5 -X "GET" -w "\nCode:%{response_code}\n" "http://${ip}/PortStatisticsRpm.htm")
curlCode="$?"
if [[ "${curlCode}" -ne "0" ]]; then # curl出错
echo "curl Error!" 1>&2
echo "curlCode:${curlCode}" 1>&2
exit 1
fi
httpCode=$(echo "${curlInfo}" | tail -1 | cut -d ':' -f 2)
fi
if [[ "${httpCode}" -ne "200" ]]; then # 其他情况
echo "api Error!" 1>&2
echo "httpCode:${httpCode}" 1>&2
exit 1
fi
portNumber="$(echo "${curlInfo}" | grep 'var max_port_num' | cut -d '=' -f 2 | sed -n -e 's/[[:blank:]]*\([0-9]\+\).*/\1/p')"
# portStatus=($(echo "${curlInfo}" | grep "^state" | cut -d ':' -f 2 | sed -e 's/.*\[//g' -e 's/\].*//g' | tr ',' ' '))
linkStatus=($(echo "${curlInfo}" | grep "^link_status" | cut -d ':' -f 2 | sed -e 's/.*\[//g' -e 's/\].*//g' | tr ',' ' '))
for ((i = 0; i < ${portNumber} ; i++)); do
printf "端口$((i+1))\t"
case "${linkStatus[i]}" in
0 )
printf "断开"
;;
1 )
printf "自动"
;;
2 )
printf "10M半双工"
;;
3 )
printf "10M全双工"
;;
4 )
printf "100M半双工"
;;
5 )
printf "100M全双工"
;;
6 )
printf "1000M全双工"
;;
*)
printf "未知"
;;
esac
printf "\n"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment