用C++和shell获取本机CPU、网卡IO、内存、磁盘等的基本信息

时间:2021-08-11 14:52:40

用C++和shell获取本机CPU、网卡、内存、磁盘等的基本信息;

由于对C++相关的函数没多少了解,但是觉得用shell反而相对简单一些:

一、shell脚本,用来辅助C++获取主机的资源使用信息

(1) cpurate.sh 获取cpu的使用率

#!/bin/sh

##echo user nice system idle iowait irq softirq
CPULOG_1=$(cat /proc/stat | grep 'cpu ' | awk '{print $2" "$3" "$4" "$5" "$6" "$7" "$8}')
SYS_IDLE_1=$(echo $CPULOG_1 | awk '{print $4}')
Total_1=$(echo $CPULOG_1 | awk '{print $1+$2+$3+$4+$5+$6+$7}') sleep CPULOG_2=$(cat /proc/stat | grep 'cpu ' | awk '{print $2" "$3" "$4" "$5" "$6" "$7" "$8}')
SYS_IDLE_2=$(echo $CPULOG_2 | awk '{print $4}')
Total_2=$(echo $CPULOG_2 | awk '{print $1+$2+$3+$4+$5+$6+$7}') SYS_IDLE=`expr $SYS_IDLE_2 - $SYS_IDLE_1` Total=`expr $Total_2 - $Total_1`
SYS_USAGE=`expr $SYS_IDLE/$Total* |bc -l` SYS_Rate=`expr -$SYS_USAGE |bc -l` Disp_SYS_Rate=`expr "scale=3; a=$SYS_Rate/1; if(length(a)==scale(a) && a!=0) print 0;print a" |bc`
echo $Disp_SYS_Rate%

(2)memrate.sh 获取内存的使用率

#!/bin/sh

MemTotal=$(cat /proc/meminfo | grep 'MemTotal' | awk '{print $2}')
MemFree=$(cat /proc/meminfo | grep 'MemFree' | awk '{print $2}') Disp_SYS_Rate=`expr "scale=3; a=100*$MemFree/$MemTotal; if(length(a)==scale(a)) print 0;print a" |bc`
echo $Disp_SYS_Rate%

(3)network.sh 获取网卡的使用率

#!/bin/sh

cat /proc/net/dev | grep 'eth' | awk '{ if($2!=0) print $1"/"$2}'

(4)getsize.sh 获取磁盘的可用与总共的大小

#!/bin/bash

LISTEN_PATH=./
if [ -n $ ]; then
LISTEN_PATH=$
fi
echo `df -h $LISTEN_PATH | grep "dev" `| awk '{print $3"/"$2}'

二、C++ file用来调用上面的shell文件获取信息

#include<iostream>
#include<string>
#include <stdio.h> using namespace std; bool GetCpuRate(std::string& cpurate)
{
FILE *file;
string cmd("./cpurate.sh"); file = popen(cmd.c_str(), "r");
if(file == NULL)
{
cout<<cmd<<" fail"<<endl;
return false;
}
char buf[] = {}; while(fgets(buf, sizeof(buf), file) != NULL)
{
char tmpbuf[]={};
sscanf(buf,"%s",tmpbuf);
cpurate=std::string(tmpbuf);
}
pclose(file);
return true;
}
bool GetMemRate(std::string& memrate)
{
FILE *file;
string cmd("./memrate.sh"); file = popen(cmd.c_str(), "r");
if(file == NULL)
{
cout<<cmd<<" fail"<<endl;
return false;
}
char buf[] = {}; while(fgets(buf, sizeof(buf), file) != NULL)
{
char tmpbuf[]={};
sscanf(buf,"%s",tmpbuf);
memrate=std::string(tmpbuf);
}
pclose(file);
return true;
} bool GetNetInfo(std::string& network)
{
FILE *file;
string cmd("./network.sh"); file = popen(cmd.c_str(), "r");
if(file == NULL)
{
cout<<cmd<<" fail"<<endl;
return false;
}
char buf[] = {}; while(fgets(buf, sizeof(buf), file) != NULL)
{
char tmpbuf[]={};
sscanf(buf,"%s",tmpbuf);
network=std::string(tmpbuf);
}
pclose(file);
return true;
} bool GetDiskInfo(std::string& diskInfo,const std::string path)
{
FILE *file;
string cmd("./getsize.sh "+path); file = popen(cmd.c_str(), "r");
if(file == NULL)
{
cout<<cmd<<" fail"<<endl;
return false;
}
char buf[] = {}; while(fgets(buf, sizeof(buf), file) != NULL)
{
char tmpbuf[]={};
sscanf(buf,"%s",tmpbuf);
diskInfo=std::string(tmpbuf);
}
pclose(file);
return true;
} int main()
{
std::string cpurate, memrate, network, diskInfo;
GetCpuRate(cpurate);
GetMemRate(memrate);
GetNetInfo(network);
GetDiskInfo(diskInfo, "/home/");
cout<<cpurate<<endl;
cout<<memrate<<endl;
cout<<network<<endl;
cout<<diskInfo<<endl;
return ;
}

三、获取当前活动的网卡和mac,C++file(这两个是抄别人的,但是时间有点久,找不到是谁的了)

(1) getethaddr.c 获取当前的网卡地址

#include <stdio.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h> int get_local_ip(char *ip_list) {
struct ifaddrs *ifAddrStruct;
void *tmpAddrPtr;
char ip[INET_ADDRSTRLEN];
int n = ;
getifaddrs(&ifAddrStruct);
while (ifAddrStruct != NULL) {
if (ifAddrStruct->ifa_addr->sa_family==AF_INET) {
tmpAddrPtr=&((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;
inet_ntop(AF_INET, tmpAddrPtr, ip, INET_ADDRSTRLEN);
if (strcmp(ip, "127.0.0.1") != ) {
// printf("%s IP Address:%s\n", ifAddrStruct->ifa_name, ip);
if (n == ){
memcpy(ip_list, ip, INET_ADDRSTRLEN);
} else {
memcpy(ip_list+INET_ADDRSTRLEN, ip, INET_ADDRSTRLEN);
}
n++;
}
}
ifAddrStruct=ifAddrStruct->ifa_next;
}
//free ifaddrs
freeifaddrs(ifAddrStruct);
return n;
}
int main()
{
char ip[][INET_ADDRSTRLEN];
memset(ip, , sizeof(ip));
int n;
for (n=get_local_ip(*ip); n>; n--) {
printf("%s\n", ip[n-]);
}
return ;
}

(2) 获取mac地址getmac.c

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> #include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <linux/if.h> #define IFNAMSIZ 16 char ifname_buf[];
char *ifnames = ifname_buf;
int count = ; void add_interface_name(const char * name)
{
int i;
for (i=;i<count;i++)
{
if (!strcmp(ifnames+i*IFNAMSIZ, name))
return;
}
strncpy(ifnames+(count++)*IFNAMSIZ, name, IFNAMSIZ-);
} char * get_name(char *name, char *p)
{
while (isspace(*p))
p++;
while (*p) {
if (isspace(*p))
break;
if (*p == ':') { /* could be an alias */
char *dot = p, *dotname = name;
*name++ = *p++;
while (isdigit(*p))
*name++ = *p++;
if (*p != ':') { /* it wasn't, backup */
p = dot;
name = dotname;
}
if (*p == '\0')
return NULL;
p++;
break;
}
*name++ = *p++;
}
*name++ = '\0';
return p;
} // get /proc/net/dev interface name list into buffer
// return 0 if success
int get_procnet_list()
{
FILE *fh;
char buf[];
fh = fopen("/proc/net/dev", "r");
if (!fh)
return -; fgets(buf, sizeof buf, fh); /* eat title lines */
fgets(buf, sizeof buf, fh);
while (fgets(buf, sizeof buf, fh))
{
char name[IFNAMSIZ];
get_name(name, buf);
add_interface_name(name);
}
fclose(fh);
return ;
} long mac_addr_sys ( u_char *addr)
{
/* implementation for Linux */
struct ifreq ifr;
struct ifreq *IFR;
struct ifconf ifc;
char buf[];
int s, i;
int ok = ; // clear buffer
memset(ifname_buf, , sizeof(ifname_buf)); s = socket(AF_INET, SOCK_DGRAM, );
if (s==-) {
return -;
} ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = buf;
ioctl(s, SIOCGIFCONF, &ifc); IFR = ifc.ifc_req;
// put the ioctl interface names in the list
for (i = ifc.ifc_len / sizeof(struct ifreq); --i >= ; IFR++) {
add_interface_name(IFR->ifr_name);
}
// put the /proc/net/dev interface names in the list
if (get_procnet_list())
return -; // get the first mac address of eth* device hardware address
for (i = ; i < count; i++) {
strcpy(ifr.ifr_name, ifnames + i*IFNAMSIZ);
if (!strncmp(ifr.ifr_name, "eth", ))
if (ioctl(s, SIOCGIFFLAGS, &ifr) == ) {
if (! (ifr.ifr_flags & IFF_LOOPBACK)) {
if (ioctl(s, SIOCGIFHWADDR, &ifr) == ) {
char *p = (char *)ifr.ifr_hwaddr.sa_data;
if (!*((int *)p) && !*((int *)(p+)) )
continue;
// if not 00:00:00:00:00:00, yes, we get the real mac addr
ok = ;
break;
}
}
}
} close(s);
if (ok) {
bcopy( ifr.ifr_hwaddr.sa_data, addr, );
}
else {
return -;
}
return ;
} int main( int argc, char **argv)
{
long stat;
int i;
u_char addr[]; stat = mac_addr_sys( addr);
if ( == stat) {
printf( "MAC address = ");
for (i=; i<; ++i) {
printf("%2.2x", addr[i]);
if (i<)
printf(":");
}
printf( "\n");
}
else {
fprintf( stderr, "can't get MAC address\n");
exit( );
}
return ;
}