-5

I cannot get the linux current users, memory, hdd usage, cpu load into ruby.

require 'socket'
puts "\n"

time = Time.new   
#puts time.day, time.month, time.year
puts "Date " + time.strftime("%d/%m/%Y")+"\t\t\tTime " + time.strftime("%H:%M:%S")+"\t\t\tSystem-Name: " + Socket.gethostname
puts "----------------------------------------------------------------------------------------------"
puts "Uptime: " 

#Uptime
uptime = exec "uptime"

#Memory Usage

system (free -m | awk 'NR==2{printf "Memory Usage: %s/%sMB (%.2f%%)\n", $3,$2,$3*100/$2 }')

#Disk usage
df -h | awk '$NF=="/"{printf "Disk Usage: %d/%dGB (%s)\n", $3,$2,$5}'

#Current Users
users | awk '{for(i=1;i<=NF;i++) {a[$i]++}} END {for(i in a) {print "Current Users:\t"a[i]}}'

#CPU load
top -bn1 | grep load | awk '{printf "CPU Load: %.2f\n", $(NF-2)}' 
Rob
  • 26,989
  • 16
  • 82
  • 98

3 Answers3

2

Use backticks

`command`

instead of exec or system.

You might want to read this answer about the different ways to run system commands and about their differences.

Community
  • 1
  • 1
spickermann
  • 100,941
  • 9
  • 101
  • 131
1

To grab the stdout and stderr from external commands, you can't use exec or system, but have to do it like this:

 output = `command`
user1934428
  • 19,864
  • 7
  • 42
  • 87
0

First: option should work better, because it returns in the string format.

Second: option is good for some reasons like clear the logs.

1) uptime = `uptime`
#OR
2) system("clear")
7urkm3n
  • 6,054
  • 4
  • 29
  • 46