Posted By

alemani on 04/26/10


Tagged

Bash network speed


Versions (?)

Calculate network speed


 / Published in: Bash
 

This script calculates the network speed up/down

  1. #!/bin/bash
  2.  
  3. # This shell script shows the network speed, both received and transmitted.
  4.  
  5. # Usage: net_speed.sh interface
  6. # e.g: net_speed.sh eth0
  7.  
  8. # Global variables
  9. interface=$1
  10. received_bytes=""
  11. old_received_bytes=""
  12. transmitted_bytes=""
  13. old_transmitted_bytes=""
  14.  
  15. # This function parses /proc/net/dev file searching for a line containing $interface data.
  16. # Within that line, the first and ninth numbers after ':' are respectively the received and transmited bytes.
  17. get_bytes()
  18. {
  19. line=$(cat /proc/net/dev | grep $interface | cut -d ':' -f 2 | awk '{print "received_bytes="$1, "transmitted_bytes="$9}')
  20. eval $line
  21. }
  22.  
  23. # Function which calculates the speed using actual and old byte number.
  24. # Speed is shown in KByte per second when greater or equal than 1 KByte per second.
  25. # This function should be called each second.
  26. get_velocity()
  27. {
  28. value=$1
  29. old_value=$2
  30.  
  31. let vel=$value-$old_value
  32. let velKB=$vel/1024
  33. if [ $velKB != 0 ];
  34. then
  35. echo -n "$velKB KB/s";
  36. else
  37. echo -n "$vel B/s";
  38. fi
  39. }
  40.  
  41. # Gets initial values.
  42. get_bytes
  43. old_received_bytes=$received_bytes
  44. old_transmitted_bytes=$transmitted_bytes
  45.  
  46. # Shows a message and waits for one second.
  47. echo "Starting...";
  48. sleep 1;
  49. echo "";
  50.  
  51. # Main loop. It will repeat forever.
  52. while true;
  53. do
  54.  
  55. # Get new transmitted and received byte number values.
  56. get_bytes
  57.  
  58. # Calculates speeds.
  59. vel_recv=$(get_velocity $received_bytes $old_received_bytes)
  60. vel_trans=$(get_velocity $transmitted_bytes $old_transmitted_bytes)
  61.  
  62. # Shows results in the console.
  63. echo -en "$interface DOWN:$vel_recv\tUP:$vel_trans\r"
  64.  
  65. # Update old values to perform new calculations.
  66. old_received_bytes=$received_bytes
  67. old_transmitted_bytes=$transmitted_bytes
  68.  
  69. # Waits one second.
  70. sleep 1;
  71.  
  72. done

Report this snippet  

You need to login to post a comment.