如何获取主机名,IP地址,CPU信息,内存信息

时间:2018-01-05 04:50:43

标签: python-2.7 shell

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

我有主机名和IP地址但是如何获取CPU信息和内存信息。有人可以帮我这么做吗?

2 个答案:

答案 0 :(得分:3)

psutil看起来像你正在寻找的东西。库支持Python 2.6 - 3.6。

CPU利用率百分比:

>>> 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]

查找可用内存:

>>> 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)

答案 1 :(得分:0)

获取主机名

hostname=`hostname` 2> /dev/null

获取发行版

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

获得正常运行时间

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

获取cpus

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

获取平均负载

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

从平均负载中删除领先的空格

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

获取总内存

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

获取IP地址

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

ips为空,让我们尝试使用python获取IP地址

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'"}'