0
import socket
hostname = socket.gethostname()
hostip=socket.gethostbyname(hostname)
print "hostname is", hostname
print "hostip is",hostip

I have got the hostname and IP address but how can I get CPU info and memory info. Can anyone please help me to do so?

B3W
  • 166
  • 11
  • Possible duplicate of [How to get current CPU and RAM usage in Python?](https://stackoverflow.com/questions/276052/how-to-get-current-cpu-and-ram-usage-in-python) – OneCricketeer Jan 05 '18 at 05:08

2 Answers2

3

psutil looks like what you're looking for. Library supports Python 2.6 - 3.6.

CPU Utilization as a Percentage:

>>> import psutil
>>> # blocking
>>> psutil.cpu_percent(interval=1)
2.0
>>> # non-blocking (percentage since last call)
>>> psutil.cpu_percent(interval=None)
2.9
>>> # blocking, per-cpu
>>> psutil.cpu_percent(interval=1, percpu=True)
[2.0, 1.0]

Find Memory Available:

>>> import psutil
>>> mem = psutil.virtual_memory()
>>> mem
svmem(total=10367352832, available=6472179712, percent=37.6, used=8186245120, free=2181107712, active=4748992512, inactive=2758115328, buffers=790724608, cached=3500347392, shared=787554304)
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
B3W
  • 166
  • 11
0

Get hostname

hostname=`hostname` 2> /dev/null

Get distro

if [ -f "/etc/system-release" ]; then
    distro=`cat /etc/system-release`
else
    distro=`python -c 'import platform; print platform.linux_distribution()[0] + "    " + platform.linux_distribution()[1]'` 2> /dev/null
fi

Get uptime

if [ -f "/proc/uptime" ]; then
    uptime=`cat /proc/uptime`
    uptime=${uptime%%.*}
    seconds=$(( uptime%60 ))
    minutes=$(( uptime/60%60 ))
    hours=$(( uptime/60/60%24 ))
    days=$(( uptime/60/60/24 ))
    uptime="$days"d", $hours"h", $minutes"m", $seconds"s""
else
    uptime=""
fi

Get cpus

if [ -f "/proc/cpuinfo" ]; then
    cpus=`grep -c processor /proc/cpuinfo` 2> /dev/null
else
    cpus=""
fi

Get load averages

loadavg=`uptime | awk -F'load average:' '{ print $2 }'` 2> /dev/null

Remove leading whitespace from load averages

loadavg=`echo $loadavg | sed 's/^ *//g'`

Get total memory

if [ -f "/proc/meminfo" ]; then
    memory=`cat /proc/meminfo | grep 'MemTotal:' | awk {'print $2}'` 2> /dev/null
else
    memory=""
fi

Get ip addresses

ips=`ifconfig | awk -F "[: ]+" '/inet addr:/ { if ($4 != "127.0.0.1") print $4 }'` 2> /dev/null

ips is empty, let's try and get ip addresses with python instead

if [ -z "${ips}" ]; then
    ips=`python -c 'import socket;
     print    socket.gethostbyname(socket.gethostname())'` 2> /dev/null
fi

echo -n '{"hostname": "'$hostname'", "distro": "'$distro'", "uptime": "'$uptime'", "cpus": '$cpus', "loadavg": "'$loadavg'", "memory": '$memory', "ips": "'$ips'"}'
Eugene Primako
  • 2,767
  • 9
  • 26
  • 35