import socket
hostname = socket.gethostname()
hostip=socket.gethostbyname(hostname)
print "hostname is", hostname
print "hostip is",hostip
我有主机名和IP地址但是如何获取CPU信息和内存信息。有人可以帮我这么做吗?
答案 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
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
ips=`ifconfig | awk -F "[: ]+" '/inet addr:/ { if ($4 != "127.0.0.1") print $4 }'` 2> /dev/null
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'"}'