Linux上传主机开销

上传主机信息

编写服务端、客户端程序。要求客户端程序上传其主机 CPU、内存、硬盘空 间开销,服务端程序接收到数据后以合理形式在屏幕上显示。

思路

? 调用系统的 \(shell\) 命令,然后再解析结果。就是正则表达式和一些基本操作。求出结果后整理格式上传即可。服务器随便搞一个能接字符串输出字符串就行。服务器的 \(tcp\) 内容是抄的,就不放了。主要看下怎么获取信息即可。

代码部分

$ client.c $

/* File Name: client.c */  
  
#include<stdio.h>  
#include<stdlib.h>  
#include<string.h>  
#include<errno.h>  
#include<sys/types.h>  
#include<sys/socket.h>  
#include<netinet/in.h>  
#include<arpa/inet.h> 
#define MAXLINE 4096  
  
char str[256];
void getdisk(long long int* diskall,long long int* diskused){
	FILE* fp;
	fp=popen(" df / | tail -1 ","r");
	fscanf(fp,"%s",str);
	fscanf(fp,"%lld%lld",diskall,diskused);
	pclose(fp);
}
void getmem(long long int* memall,long long int* memused){
	*memall=0,*memused=0;
	FILE* fp;
	fp=popen("top -n 1 | grep Mem | awk -F: ‘{print $2}‘","r");
	fscanf(fp,"%s",str);
	fscanf(fp,"%lld",memall);
	fscanf(fp,"%s",str);
	fscanf(fp,"%lld",memused);
	pclose(fp);
}
void getcpu(double *percent){
	*percent=0;
	FILE* fp;
	fp=popen("top -n 1 | grep Cpu | awk -F, ‘{print $4}‘","r");
	fscanf(fp,"%s",str);
	fscanf(fp,"%lf",percent);
	pclose(fp);
}

long long int memall,memused,diskall,diskused;
double cpurate;
void get(){
	double cpupercent;
	getdisk(&diskall,&diskused);
	getmem(&memall,&memused);
	getcpu(&cpurate);
}
int main(int argc, char** argv)  
{  
    int    sockfd, n,rec_len;  
    char    recvline[4096], sendline[4096];  
    char    buf[MAXLINE];  
    struct sockaddr_in    servaddr;  
  
  
    if( argc != 2){  
    printf("usage: ./client <ipaddress>\n");  
    exit(0);  
    }  
  
    sockfd = socket(AF_INET, SOCK_STREAM, 0)  ;
  
  
    memset(&servaddr, 0, sizeof(servaddr));  
    servaddr.sin_family = AF_INET;  
    servaddr.sin_port = htons(8000);  
    inet_pton(AF_INET, argv[1], &servaddr.sin_addr) ;  
  
    connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) ; 
  	get();
    printf("send msg to server: \n");  
	sprintf(sendline,"\nDisk:all:%lldKiB\tfree:%lldKiB\nMem:all:%lldKiB\tfree:%lldKiB\ncpu:emptyrate:%.2lf%%\n",diskall,diskused,memall,memused,cpurate);
    send(sockfd, sendline, strlen(sendline),0);
	rec_len = recv(sockfd, buf, MAXLINE,0);
    buf[rec_len]  = ‘\0‘;  
    printf("Received : %s ",buf);  
    exit(0);  
}  

Linux上传主机开销

上一篇:Django使用channels实现Websocket连接


下一篇:Arduino ESP8266 ESP8266WebServer.h