python获取机器信息脚本(网上寻找的)
获取机器信息(待测试)
# -*- coding: UTF-8 -*-
import psutil
import json
import os
import socket
import struct
import time
import sys # 当前时间函数
def now_time():
now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
return now_time # 获取硬盘信息函数
def disk_info():
disk_dict = {}
disk_name = []
disk_parttions = psutil.disk_partitions()
for i in range(len(disk_parttions)):
parttions_name = disk_parttions[i].device
mountpoint = disk_parttions[i].mountpoint
mountfstype = disk_parttions[i].fstype
disk_info = psutil.disk_usage(mountpoint)
total = disk_info.total
used = disk_info.used
free = disk_info.free
disk_io = psutil.disk_io_counters(perdisk=True)
disk_name.append(str(parttions_name.split('/', parttions_name.count('/'))[-1]))
for key1 in disk_name:
tmp_disk_list = []
for key2 in disk_io.keys():
tmp_disk_list.append(key2)
if key1 in tmp_disk_list:
disk_dict[parttions_name] = {
"read_bytes": disk_io[key1].read_bytes,
"write_bytes": disk_io[key1].write_bytes,
"read_count": disk_io[key1].read_count,
"write_count": disk_io[key1].write_count,
"mountpoint": mountpoint,
"mountfstype": mountfstype,
"total": total,
"used": used,
"free": free
}
else:
pass
return disk_dict # 获取内存信息函数
def mem_info():
mem_dict_list = psutil.virtual_memory()
mem_total = mem_dict_list.total
mem_used = mem_dict_list.used
mem_free = mem_dict_list.free
cpu_use = psutil.cpu_percent(interval=True)
host_runtime = psutil.boot_time()
mem_list_info = {
"mem_total": mem_total,
"mem_used": mem_used,
"mem_free": mem_free,
"cpu_used": cpu_use,
"host_run": host_runtime
}
return mem_list_info # 获取CPU信息函数
def cpu_info():
cpu_use = psutil.cpu_percent(interval=True)
cpu_usage = {
"cpu_used": cpu_use
}
return cpu_usage # 获取网卡信息函数
def net_info():
net_dict_list = {}
net_dev = psutil.net_io_counters(pernic=True)
for dev_name in net_dev.keys():
net_dict_list[dev_name] = {
"RX_b": net_dev[dev_name].bytes_recv,
"TX_b": net_dev[dev_name].bytes_sent,
"Dropout": net_dev[dev_name].dropout,
"Dropint": net_dev[dev_name].dropin
}
return net_dict_list # 获取用户信息函数
def user_info():
user_dict_list = []
user_dict = psutil.users()
for i in range(len(user_dict)):
user_dict_tmp = {}
user_dict_tmp[user_dict[i].name] = {
"terminal": user_dict[i].terminal,
"host": user_dict[i].host,
"start_time": user_dict[i].started
}
user_dict_list.append(user_dict_tmp)
return user_dict_list # 获取内存消耗前10的进程函数
def process_info():
process_dict_list_tmp = []
pid_dict = psutil.pids()
for i in pid_dict:
pid = psutil.Process(i)
pid_tuple = (i, pid.name(), pid.memory_percent(), pid.create_time(), pid.status(), pid.cwd(), pid.exe())
process_dict_list_tmp.append(pid_tuple)
process_dict_list_tmp.sort(key=lambda mem1: mem1[2], reverse=True)
process_dict_list = process_dict_list_tmp[0:10]
return process_dict_list # 获取开机时间函数
def runtime_info():
host_runtime = psutil.boot_time()
host_run_time = {
"host_runtime": host_runtime
}
return host_run_time # 没用的函数
def get_info():
host_info = {
'disk_info': disk_info(),
'mem_info': mem_info(),
'cpu_info': cpu_info(),
'net_info': net_info(),
'process_info': process_info(),
'user_info': user_info(),
'runtime_info': runtime_info()
}
return repr(host_info) # socket数据发送函数
def socket_send(socket_server=None, socket_port=None, cammds=None, type=None, PackName=None):
if type == 'regs':
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket_server, socket_port))
s.sendall(cammds)
request = str(s.recv(18))
s.close()
return request
elif type == 'data':
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket_server, socket_port))
s.sendall(cammds)
request = str(s.recv(128))
if request == 'OK':
Rtime = now_time()
PackSize = sys.getsizeof(cammds)
print(" '%s' : transfer TCP Package '%s' Size '%s' sucessful ") % (Rtime, PackName, PackSize)
s.close() # 构架TCP格式数据包函数
def trans_pack(commands=None, type=None):
Net_type = 4 # package versions
Mem_type = 1
Cpu_type = 2
Disk_type = 3
Runtime_type = 5
if type == 'Mem':
machine_number = json_conf()["machine_number"] # 获取机器码
body = json.dumps(dict(commands)) # 生成JSON格式包体
header = [Mem_type, body.__len__(), machine_number] # 组成包头格式为:版本,包体长度,机器码
headPack = struct.pack("!3I", *header) # 生成包头
sendPack = headPack + body.encode() # 构建TCP数据包
return sendPack
elif type == 'Net':
machine_number = json_conf()["machine_number"] # 获取机器码
body = json.dumps(dict(commands)) # 生成JSON格式包体
header = [Net_type, body.__len__(), machine_number] # 组成包头格式为:版本,包体长度,机器码
headPack = struct.pack("!3I", *header) # 生成包头
sendPack = headPack + body.encode() # 构建TCP数据包
return sendPack
elif type == 'Cpu':
machine_number = json_conf()["machine_number"] # 获取机器码
body = json.dumps(dict(commands)) # 生成JSON格式包体
header = [Cpu_type, body.__len__(), machine_number] # 组成包头格式为:版本,包体长度,机器码
headPack = struct.pack("!3I", *header) # 生成包头
sendPack = headPack + body.encode() # 构建TCP数据包
return sendPack
elif type == 'Disk':
machine_number = json_conf()["machine_number"] # 获取机器码
body = json.dumps(dict(commands)) # 生成JSON格式包体
header = [Disk_type, body.__len__(), machine_number] # 组成包头格式为:版本,包体长度,机器码
headPack = struct.pack("!3I", *header) # 生成包头
sendPack = headPack + body.encode() # 构建TCP数据包
return sendPack
elif type == 'Run':
machine_number = json_conf()["machine_number"] # 获取机器码
body = json.dumps(dict(commands)) # 生成JSON格式包体
header = [Runtime_type, body.__len__(), machine_number] # 组成包头格式为:版本,包体长度,机器码
headPack = struct.pack("!3I", *header) # 生成包头
sendPack = headPack + body.encode() # 构建TCP数据包
return sendPack # 读取JSON配置函数
def json_conf():
a = os.getcwd()
# os.chdir("%s/client/conf" % a) # 改变工作目录为JSON文件目录
json_list = file("%s/client/conf/client_conf.json" % a) # 读取JSON配置文件
m = json_list.read()
json_list.seek(0)
json_conf = json.loads(json_list.read()) # 取出JSON配置文件
json_list.close()
return json_conf def json_write(command=None):
a = os.getcwd()
os.chdir("%s/client/conf" % a)
print(command)
b = type(command)
m = open("client_conf.json", 'w') # agent第一次注册函数
def client_regs():
host_info = json.dumps({'ip': str(json_conf()['local_adder']), 'mac': str(json_conf()['local_mac'])})
regs_addr = json_conf()['send_server']
regs_port = json_conf()['server_regs_port']
server_request = str(socket_send(socket_server=regs_addr, socket_port=regs_port, cammds=host_info, type='regs'))
conf = json_conf()
conf['machine_number'] = server_request
conf = json.dumps(conf)
json_write(command=conf) # 数据包发送函数
def send_data():
DiskPack = trans_pack(commands=disk_info(), type='Disk') # 生成TCP数据包
MemPack = trans_pack(commands=mem_info(), type='Mem')
NetPack = trans_pack(commands=net_info(), type='Net')
regs_addr = json_conf()['send_server'] # 获取服务器地址
regs_port = json_conf()['send_port'] # 获取服务器端口
socket_send(socket_server=regs_addr, socket_port=regs_port, cammds=DiskPack, type='data',
PackName='DiskPack') # 向服务器发送数据包
socket_send(socket_server=regs_addr, socket_port=regs_port, cammds=MemPack, type='data', PackName='MemPack')
socket_send(socket_server=regs_addr, socket_port=regs_port, cammds=NetPack, type='data', PackName='NetPack')
time.sleep(json_conf()['sendoff_time']) # 等待延时 def check_client():
print('start get client info....')
machine_number = json_conf()['machine_number']
if machine_number:
print(machine_number)
print(11111)
else:
print(machine_number)
print(22222) if __name__ == '__main__':
while True:
send_data()
python获取机器信息脚本(网上寻找的)的更多相关文章
- python 读取机器信息
本人最近新学python ,用到关于机器的相关信息,经过一番研究,从网上查找资料,经过测试,总结了一下相关的方法. # -*- coding: UTF8 -*- import os import wi ...
- python 获取对象信息
当我们拿到一个对象的引用时,如何知道这个对象是什么类型.有哪些方法呢? 使用type() 首先,我们来判断对象类型,使用type()函数: 基本类型都可以用type()判断: >>> ...
- shell,python获取当前路径(脚本的当前路径) (aso项目记录)
一.shell获取脚本当前路径 cur_dir=$(cd "$(dirname "$0")"; pwd) #获取当前脚本的绝对路径,参数$0是当前脚本对象 等 ...
- Python 获取车票信息
提示:该代码仅供学习使用,切勿滥用!!! 先来一个git地址:https://gitee.com/wang_li/li_wang 效果图: 逻辑: 1.获取Json文件的内容 2.根据信息生成URL ...
- 用python获取服务器硬件信息[转]
#!/usr/bin/env python # -*- coding: utf-8 -*- import rlcompleter, readline readline.parse_and_bind(' ...
- 用python获取ip信息
1.138网站 http://user.ip138.com/ip/首次注册后赠送1000次请求,API接口请求格式如下,必须要有token值 import httplib2 from urllib.p ...
- python获取对象信息
获取对象信息 拿到一个变量,除了用 isinstance() 判断它是否是某种类型的实例外,还有没有别的方法获取到更多的信息呢? 例如,已有定义: class Person(object): def ...
- PYTHON 获取机器硬件信息及状态
#!/usr/bin/env python # encoding: utf-8 from optparse import OptionParser import os import re import ...
- 关于Python 获取windows信息收集
收集一些Python操作windows的代码 (不管是自带的or第三方库)均来自网上 1.shutdown 操作 定时关机.重启.注销 #!/usr/bin/python #-*-coding:utf ...
随机推荐
- Jest 学习笔记(一)之matchers
Jest官网地址 Jest是专门被facebook用于测试包括React应用在内的所有javascript代码,Jest旨在提供一个综合的零计算的测试体验. 因为没有找到文档,基于我个人的经验,Jes ...
- 虚拟机3种网络模式(桥接、nat、Host-only)
http://www.cnblogs.com/ggjucheng/archive/2012/08/19/2646007.html
- Codeforces Round #554 (Div. 2) C. Neko does Maths (简单推导)
题目:http://codeforces.com/contest/1152/problem/C 题意:给你a,b, 你可以找任意一个k 算出a+k,b+k的最小公倍数,让最小公倍数尽量小,求出 ...
- java 两行代码解析json文件
public void JsonRead() throws IOException{ String str = FileUtils.readFileToString(new File("D: ...
- Mac 中 PyCharm 配置 Anaconda环境
- MVC简单增删改
/// <summary> /// /显示分页 /// </summary> /// <param name="model"></para ...
- 《贝贝GO》服务条款
服务条款 一.服务条款的确认与接收 1.贝贝GO客户端软件(以下简称“本软件”)各项电子服务的所有权和运作权归属于“东莞市山水信息技术有限公司”(以下称“本公司”)所有,本软件提供的服务将完全按照其发 ...
- log4j 2.+框架
今天听网友介绍说Log4j2说效率比lOG4J高而且敲级好用.晚上有空就花了几个时间研究了一下.发现嗯,的确好用.我还清楚的记得Log4j1.2的时候我们需要设置log4j需要通过一个properti ...
- 删除单链表节点,时间复杂度为O(1)
一个编程练习,删除单链表一个节点,且时间复杂度控制在O(1)内. 1.核心操作代码如下: struct ListNode { int m_data; ListNode *m_pNext; }; voi ...
- iOS开发,改变系统铃声音量和静音,并非媒体播放音量
使用AVSystemController可以改变系统声音,而且是铃声,并非媒体播放的声音. 它可以让iPhone手机静音.但是,AVSystemController存在于私有Celestial框架中. ...