1. python能检测软件状态吗
python是能检测软件运行状态的。具体代码如下:
首先我们需要首先注意的一个地方是配置文件的后缀。
vim /etc/supervisord.conf
[include]
files = supervisord.d/*.ini
如果你想配置文件为其他格式,比如 conf 格式的话, 需要更改 iles = supervisord.d/*.conf 。
比如我们需要守护启动一个进程,我们就以守护Prometheus 为例:
vim /etc/supervisord.d/proms.ini
[program:proms]
command=/opt/prometheus/server/prometheus/prometheus
directory=/opt/prometheus/server/prometheus
stdout_logfile=/home/data/logs/prometheus/sever.log
autostart=true
autorestart=true
redirect_stderr=true
user=root
startsecs=3
supervisor配置文件详解:
program: 指定的守护进程名
command: 命令
stdout_logfile: 日志路径
autostart: supervisor启动的时候是否随着同时启动,默认为 true
autorestart: 是否挂了自动重启
redirect_stderr:标准错误重定向
startsecs: 子进程启动多少秒之后,此时的状态是running
启动supervisor--(yum方式安装的)
/usr/bin/python /usr/bin/supervisord -c /etc/supervisord.conf
2. python如何获取进程和线程状态
threading.active_count()
Return the number of Thread objects currently alive. The returned count is equal to the length of the list returned by enumerate().
active_count可以返回当前活动的线程枚举
我一般是这么用的
def getHeatsParallel(self): threads = [] for i in range(0, self.threadCount): t = threading.Thread(target=self.SomeFunction, name=str(i)) threads.append(t) t.start() for t in threads: t.join()
3. 请教python中调用DeviceIoControl的一个问题
代码如粗空下
##from winioctlcon import *
##from win32file import *
from ctypes import *
from ctypes.wintypes import *
import win32api
import win32file
import winioctlcon
import win32con
IDE_ATA_IDENTIFY = 0xEC
DFP_SEND_DRIVE_COMMAND = 0x0007c084
class _IDEREGS(Structure):
_fields_=[
("bFeaturesReg",BYTE), ## 特征寄存器(用于SMART命令)
("bSectorCountReg",BYTE), ## 扇区数目寄存器
("bSectorNumberReg",BYTE), ## 开始扇区寄存器
("bCylLowReg",BYTE), ## 开始柱面低字节寄存器
("bCylHighReg",BYTE), ## 开始柱面高字节寄存器
("bDriveHeadReg",BYTE), ## 驱动器/磁头寄存器
("bCommandReg",BYTE), ## 指令寄存器
("bReserved",BYTE), ## 保留
]
IDEREGS = _IDEREGS #*PIDEREGS, *LPIDEREGS;
## 从驱动程序返回的状态
class _DRIVERSTATUS(Structure):
_fields_=[
("bDriverError",BYTE), ## 错误码
("bIDEStatus",BYTE), ## IDE状态寄存器
("bReserved",BYTE*2), ## 保留
("dwReserved",DWORD*2), ## 保留
]
DRIVERSTATUS=_DRIVERSTATUS #*PDRIVERSTATUS, *LPDRIVERSTATUS;
## IDE设备IOCTL输入数据结构
class _SENDCMDINPARAMS(Structure):
_fields_=[
("cBufferSize",DWORD), ## 缓冲区字节数
("irDriveRegs",IDEREGS), ## IDE寄存器组
("bDriveNumber",BYTE), ## 驱动器号
("bReserved"竖凳蚂,BYTE*3), ## 保留
("dwReserved",DWORD*4), ## 保留
("bBuffer[1]",BYTE), ## 输入缓冲区(此处象征性地包含1字节)
]
SENDCMDINPARAMS=_SENDCMDINPARAMS #*PSENDCMDINPARAMS, *LPSENDCMDINPARAMS;
## IDE设备IOCTL输出数据结构
class _SENDCMDOUTPARAMS(Structure):
_fields_=[
("cBufferSize",DWORD), ## 缓冲区字节数
("DriverStatus",DRIVERSTATUS), ## 驱动程序返回状态
("bBuffer[1]",BYTE), ## 输入缓冲区(此处象征性地包含1字节)
]
SENDCMDOUTPARAMS = _SENDCMDOUTPARAMS # *PSENDCMDOUTPARAMS, *LPSENDCMDOUTPARAMS;
## IDE的ID命令返回的数据
## 共512字节(256个WORD),这里仅定义了一些感兴趣的项(基本上依据ATA/ATAPI-4)
USHORT = c_ushort
CHAR = c_char
ULONG = c_ulong
UCHAR = c_ubyte
class Capabilities(Structure): ## WORD 49: 一般能力
_fields_=[
("reserved1:8",USHORT),
("DMA:1",USHORT), ## 1=支持DMA
("LBA:1",USHORT), ## 1=支持LBA
("DisIORDY:1",USHORT), ## 1=可不使用IORDY
("IORDY:1",USHORT), ## 1=支持IORDY
("SoftReset:1",USHORT), ## 1=需要ATA软余埋启动
("Overlap:1",USHORT), ## 1=支持重叠操作
("Queue:1",USHORT), ## 1=支持命令队列
("InlDMA:1",USHORT), ## 1=支持交叉存取DMA
]
class FieldValidity(Structure): ## WORD 53: 后续字段有效性标志
_fields_=[
("CHSNumber:1",USHORT), ## 1=WORD 54-58有效
("CycleNumber:1",USHORT), ## 1=WORD 64-70有效
("UnltraDMA:1",USHORT), ## 1=WORD 88有效
("reserved:13",USHORT),
]
class MultSectorStuff(Structure): ## WORD 59: 多扇区读写设定
_fields_=[
("CurNumber:8",USHORT), ## 当前一次性可读写扇区数
("Multi:1",USHORT), ## 1=已选择多扇区读写
("reserved1:7",USHORT),
]
class MultiWordDMA(Structure): ## WORD 63: 多字节DMA支持能力
_fields_=[
("Mode0:1",USHORT), ## 1=支持模式0 (4.17Mb/s)
("Mode1:1",USHORT), ## 1=支持模式1 (13.3Mb/s)
("Mode2:1",USHORT), ## 1=支持模式2 (16.7Mb/s)
("Reserved1:5",USHORT),
("Mode0Sel:1",USHORT), ## 1=已选择模式0
("Mode1Sel:1",USHORT), ## 1=已选择模式1
("Mode2Sel:1",USHORT), ## 1=已选择模式2
("Reserved2:5",USHORT),
]
class PIOCapacity(Structure): ## WORD 64: 高级PIO支持能力
_fields_=[
("AdvPOIModes:8",USHORT), ## 支持高级POI模式数
("reserved:8",USHORT),
]class MajorVersion(Structure): ## WORD 80: 主版本
_fields_=[
("Reserved1:1",USHORT),
("ATA1:1",USHORT), ## 1=支持ATA-1
("ATA2:1",USHORT), ## 1=支持ATA-2
("ATA3:1",USHORT), ## 1=支持ATA-3
("ATA4:1",USHORT), ## 1=支持ATA/ATAPI-4
("ATA5:1",USHORT), ## 1=支持ATA/ATAPI-5
("ATA6:1",USHORT), ## 1=支持ATA/ATAPI-6
("ATA7:1",USHORT), ## 1=支持ATA/ATAPI-7
("ATA8:1",USHORT), ## 1=支持ATA/ATAPI-8
("ATA9:1",USHORT), ## 1=支持ATA/ATAPI-9
("ATA10:1",USHORT), ## 1=支持ATA/ATAPI-10
("ATA11:1",USHORT), ## 1=支持ATA/ATAPI-11
("ATA12:1",USHORT), ## 1=支持ATA/ATAPI-12
("ATA13:1",USHORT), ## 1=支持ATA/ATAPI-13
("ATA14:1",USHORT), ## 1=支持ATA/ATAPI-14
("Reserved2:1",USHORT),
]
class UltraDMA(Structure): ## WORD 88: Ultra DMA支持能力
_fields_=[
("Mode0:1",USHORT), ## 1=支持模式0 (16.7Mb/s)
("Mode1:1",USHORT), ## 1=支持模式1 (25Mb/s)
("Mode2:1",USHORT), ## 1=支持模式2 (33Mb/s)
("Mode3:1",USHORT), ## 1=支持模式3 (44Mb/s)
("Mode4:1",USHORT), ## 1=支持模式4 (66Mb/s)
("Mode5:1",USHORT), ## 1=支持模式5 (100Mb/s)
("Mode6:1",USHORT), ## 1=支持模式6 (133Mb/s)
("Mode7:1",USHORT), ## 1=支持模式7 (166Mb/s) ???
("Mode0Sel:1",USHORT), ## 1=已选择模式0
("Mode1Sel:1",USHORT), ## 1=已选择模式1
("Mode2Sel:1",USHORT), ## 1=已选择模式2
("Mode3Sel:1",USHORT), ## 1=已选择模式3
("Mode4Sel:1",USHORT), ## 1=已选择模式4
("Mode5Sel:1",USHORT), ## 1=已选择模式5
("Mode6Sel:1",USHORT), ## 1=已选择模式6
("Mode7Sel:1",USHORT), ## 1=已选择模式7
]
class _IDINFO(Structure):
_fields_=[
("wGenConfig",USHORT), ## WORD 0: 基本信息字
("wNumCyls",USHORT), ## WORD 1: 柱面数
("wReserved2",USHORT), ## WORD 2: 保留
("wNumHeads",USHORT), ## WORD 3: 磁头数
("wReserved4",USHORT), ## WORD 4: 保留
("wReserved5",USHORT), ## WORD 5: 保留
("wNumSectorsPerTrack",USHORT), ## WORD 6: 每磁道扇区数
("wVendorUnique",USHORT*3), ## WORD 7-9: 厂家设定值
("sSerialNumber",CHAR*20), ## WORD 20: 缓冲类型
("wBufferSize",USHORT), ## WORD 21: 缓冲大小
("wECCSize",USHORT), ## WORD 22: ECC校验大小
("sFirmwareRev",CHAR*8), ## WORD 23-26: 固件版本
("sModelNumber",CHAR*40), ## WORD 27-46: 内部型号
("wMoreVendorUnique",USHORT), ## WORD 47: 厂家设定值
("wReserved48",USHORT), ## WORD 48: 保留
("wCapabilities",Capabilities),
("wReserved1",USHORT), ## WORD 50: 保留
("wPIOTiming",USHORT), ## WORD 51: PIO时序
("wDMATiming",USHORT), ## WORD 52: DMA时序
("wFieldValidity",FieldValidity),
("wNumCurCyls",USHORT), ## WORD 54: CHS可寻址的柱面数
("wNumCurHeads",USHORT), ## WORD 55: CHS可寻址的磁头数
("wNumCurSectorsPerTrack",USHORT), ## WORD 56: CHS可寻址每磁道扇区数
("wCurSectorsLow",USHORT), ## WORD 57: CHS可寻址的扇区数低位字
("wCurSectorsHigh",USHORT), ## WORD 58: CHS可寻址的扇区数高位字
("wMultSectorStuff",MultSectorStuff),
("dwTotalSectors",ULONG), ## WORD 60-61: LBA可寻址的扇区数
("wSingleWordDMA",USHORT), ## WORD 62: 单字节DMA支持能力
("wMultiWordDMA",MultiWordDMA),
("wPIOCapacity",PIOCapacity),
("wMinMultiWordDMACycle",USHORT), ## WORD 65: 多字节DMA传输周期的最小值
("wRecMultiWordDMACycle",USHORT), ## WORD 66: 多字节DMA传输周期的建议值
("wMinPIONoFlowCycle",USHORT), ## WORD 67: 无流控制时PIO传输周期的最小值
("wMinPOIFlowCycle",USHORT), ## WORD 68: 有流控制时PIO传输周期的最小值
("wReserved69[11]",USHORT), ## WORD 69-79: 保留
("wMajorVersion",MajorVersion),
("wMinorVersion",USHORT), ## WORD 81: 副版本
("wReserved82",USHORT*6), ## WORD 82-87: 保留
("wUltraDMA",UltraDMA),
("wReserved89",USHORT*167) # WORD 89-255
]
IDINFO = _IDINFO #*PIDINFO;
hDisk = win32file.CreateFile('\\\\.\\PhysicalDrive0',
win32file.GENERIC_READ | win32file.GENERIC_WRITE,
win32file.FILE_SHARE_READ|win32file.FILE_SHARE_WRITE,
None,
win32file.OPEN_EXISTING,
0,
None)
print(hDisk)
pSCIP=SENDCMDINPARAMS()
pSCOP=SENDCMDOUTPARAMS()
#print(pSCIP)
pSCIP.irDriveRegs.bCommandReg = IDE_ATA_IDENTIFY
#print(pSCIP.irDriveRegs.bCommandReg)
pSCIP.cBufferSize = 0
#pSCIP=create_string_buffer(pSCIP)
pSCOP.cBufferSize=sizeof(IDINFO)
Total=pSCOP.cBufferSize + sizeof(pSCOP)
#print(pSCIP.irDriveRegs.bCommandReg)
#print(pSCIP)
#print(pSCOP)
#print(Total)
##IOCTL_DISK_GET_DRIVE_GEOMETRY=0x0007c084
##IOCTL_DISK_GET_MEDIA_TYPES = 0x70c00
info = win32file.DeviceIoControl(hDisk,
DFP_SEND_DRIVE_COMMAND,
pSCIP,
Total, #sizeof(SENDCMDOUTPARAMS) + sizeof(IDINFO) - 1,
None)
print(info)
win32file.CloseHandle(hDisk)
4. 如何用Python获取笔记本电脑的电源状态
你研究下wmi模块
http://stackoverflow.com/questions/16380394/getting-battery-capacity-windows-with-python
5. Python里如何取得第一个光驱的盘符
letters = [l.upper() + ':' for l in '裤启手胡嫌abcdefghijklmnopqrstuvwxyz'旁空]
for drive in letters:
if win32file.GetDriveType(drive)==5:
self.drives.append(drive)
if not self.drive:
self.drive = self.drives[0]
6. 怎么用python获取GPIO状态
不同操作系统安装GPIO的命令是不同的,这里以树莓派的官方操作系统Raspbian为例,说明如何安装GPIO库。Raspbian中安装了两个Python版本,分别是做腊2.7.3和3.2.2。Python2.x的安装包会一python为前缀,而Python3.x的安装包回忆python3为前缀。Python2安装键誉GPIO库需要输纯亮滑入命令:1sudoapt-getinstallpython-rpi.gpioPython3安装GPIO库需要输入命令:1sudoapt-getinstallpython
7. python如何获取服务器硬件状态信息,包括CPU温度、硬盘温度、主板电池电压、主机电源电压、CPU风扇转速
>>> import psutil
>>> psutil.cpu_times()
scputimes(user=3961.46, nice=169.729, system=2150.659, idle=16900.540, iowait=629.59, irq=0.0, softirq=19.42, steal=0.0, guest=0, nice=0.0)
>>>
>>> for x in range(3):
... psutil.cpu_percent(interval=1)
...
4.0
5.9
3.8
>>>
>>> for x in range(3):
... psutil.cpu_percent(interval=1, percpu=True)
...
[4.0, 6.9, 3.7, 9.2]
[7.0, 8.5, 2.4, 2.1]
[1.2, 9.0, 9.9, 7.2]
>>>
>>>
>>> for x in range(3):
... psutil.cpu_times_percent(interval=1, percpu=False)
...
scputimes(user=1.5, nice=0.0, system=0.5, idle=96.5, iowait=1.5, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
scputimes(user=1.0, nice=0.0, system=0.0, idle=99.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
scputimes(user=2.0, nice=0.0, system=0.0, idle=98.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
>>>
>>> psutil.cpu_count()
4
>>> psutil.cpu_count(logical=False)
2
>>>
8. linux上启动python程序,shell脚本服务怎么编写
1.只能够输入Python命令。
在Python交互模式下输入Python代码,而不要输入系统的命令。
2.在交互模式下打印语句不是必须的。
在交互模式下不需要输入完整的打印语句,解释器自动打印表达式的结果,但是在文件中则需要写print语句来打印结果。
3.提示符的变换和复合语句。
当在交互模式下输入两行或多行的复合语句时,提示符会由>>>变成;如果要结束复合语句的输入并执行它,那么必须按下Enter键两次,复合语句才会被执行。
4.交互提示模式一次运行一条语句。
当你想测试某一条命令的时候,交互模式是一个很好的测试方法,输入然后回车即可猛高大看到执行结果枝竖,非常方便,当然对于复合语句来说,只要最后按两次Enter键即可运行代码,看到执行结果。
具体如下:
1、简介
Linux操作系统是基于UNIX操作系统发展而来的一种克隆系统,它诞生于1991年的[Linux桌面]10月5日(这是第一次正式向外公布的时间)。以后借助于Internet网络,并通过全世界各地计算机爱好者的共同努力,已成为今天世界上使用最多的一种UNIX类操作系统,并且使用人数还在迅猛增长。
2、基本信息
Linux[2]操作系统是UNIX操作系统的一种克隆系统,它诞生linux系统于1991年的10月5日(这是第一次正式向外公布的时间)。以后借助于Internet网络,并通过全世界各地计算机爱好者的共同努力,已成为今天世界上使用最多的一种UNIX类操作系统,并且使用人数还在迅猛增长。
3、分区规定
设备管理在Linux中,每一个硬件设备都映射到一个系统的文件,对于硬盘、光驱等,IDE或SCSI设备也不例外。Linux把各种IDE设备分配了一个由hd前缀组成念锋的文件;而对于各种SCSI设备,则分配了一个由sd前缀组成的文件。
9. python 运维常用脚本
Python 批量遍历目录文件,并修改访问时间
import os
path = "D:/UASM64/include/"
dirs = os.listdir(path)
temp=[];
for file in dirs:
temp.append(os.path.join(path, file))
for x in temp:
os.utime(x, (1577808000, 1577808000))
Python 实现的自动化服务器管理
import sys
import os
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
def ssh_cmd(user,passwd,port,userfile,cmd):
def ssh_put(user,passwd,source,target):
while True:
try:
shell=str(input("[Shell] # "))
if (shell == ""):
continue
elif (shell == "exit"):
exit()
elif (shell == "put"):
ssh_put("root","123123","./a.py","/root/a.py")
elif (shell =="cron"):
temp=input("输入一个计划任务: ")
temp1="(crontab -l; echo "+ temp + ") |crontab"
ssh_cmd("root","123123","22","./user_ip.conf",temp1)
elif (shell == "uncron"):
temp=input("输入要删除的计划任务: ")
temp1="crontab -l | grep -v " "+ temp + "|crontab"
ssh_cmd("root","123123","22","./user_ip.conf",temp1)
else:
ssh_cmd("lyshark","123123","22","./user_ip.conf",shell)
遍历目录和文件
import os
def list_all_files(rootdir):
import os
_files = []
list = os.listdir(rootdir) #列出文件夹下所有的目录与文件
for i in range(0,len(list)):
path = os.path.join(rootdir,list[i])
if os.path.isdir(path):
_files.extend(list_all_files(path))
if os.path.isfile(path):
_files.append(path)
return _files
a=list_all_files("C:/Users/LyShark/Desktop/a")
print(a)
python检测指定端口状态
import socket
sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sk.settimeout(1)
for ip in range(0,254):
try:
sk.connect(("192.168.1."+str(ip),443))
print("192.168.1.%d server open
"%ip)
except Exception:
print("192.168.1.%d server not open"%ip)
sk.close()
python实现批量执行CMD命令
import sys
import os
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print("------------------------------>
")
print("使用说明,在当前目录创建ip.txt写入ip地址")
print("------------------------------>
")
user=input("输入用户名:")
passwd=input("输入密码:")
port=input("输入端口:")
cmd=input("输入执行的命令:")
file = open("./ip.txt", "r")
line = file.readlines()
for i in range(len(line)):
print("对IP: %s 执行"%line[i].strip('
'))
python3-实现钉钉报警
import requests
import sys
import json
dingding_url = ' https://oapi.dingtalk.com/robot/send?access_token='
data = {"msgtype": "markdown","markdown": {"title": "监控","text": "apche异常"}}
headers = {'Content-Type':'application/json;charset=UTF-8'}
send_data = json.mps(data).encode('utf-8')
requests.post(url=dingding_url,data=send_data,headers=headers)
import psutil
import requests
import time
import os
import json
monitor_name = set(['httpd','cobblerd']) # 用户指定监控的服务进程名称
proc_dict = {}
proc_name = set() # 系统检测的进程名称
monitor_map = {
'httpd': 'systemctl restart httpd',
'cobblerd': 'systemctl restart cobblerd' # 系统在进程down掉后,自动重启
}
dingding_url = ' https://oapi.dingtalk.com/robot/send?access_token='
while True:
for proc in psutil.process_iter(attrs=['pid','name']):
proc_dict[proc.info['pid']] = proc.info['name']
proc_name.add(proc.info['name'])
判断指定端口是否开放
import socket
port_number = [135,443,80]
for index in port_number:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((飗.0.0.1', index))
if result == 0:
print("Port %d is open" % index)
else:
print("Port %d is not open" % index)
sock.close()
判断指定端口并且实现钉钉轮询报警
import requests
import sys
import json
import socket
import time
def dingding(title,text):
dingding_url = ' https://oapi.dingtalk.com/robot/send?access_token='
data = {"msgtype": "markdown","markdown": {"title": title,"text": text}}
headers = {'Content-Type':'application/json;charset=UTF-8'}
send_data = json.mps(data).encode('utf-8')
requests.post(url=dingding_url,data=send_data,headers=headers)
def net_scan():
port_number = [80,135,443]
for index in port_number:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((飗.0.0.1', index))
if result == 0:
print("Port %d is open" % index)
else:
return index
sock.close()
while True:
dingding("Warning",net_scan())
time.sleep(60)
python-实现SSH批量CMD执行命令
import sys
import os
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
def ssh_cmd(user,passwd,port,userfile,cmd):
file = open(userfile, "r")
line = file.readlines()
for i in range(len(line)):
print("对IP: %s 执行"%line[i].strip('
'))
ssh.connect(hostname=line[i].strip('
'),port=port,username=user,password=passwd)
cmd=cmd
stdin, stdout, stderr = ssh.exec_command(cmd)
result = stdout.read()
ssh_cmd("lyshark","123","22","./ip.txt","free -h |grep 'Mem:' |awk '{print $3}'")
用python写一个列举当前目录以及所有子目录下的文件,并打印出绝对路径
import sys
import os
for root,dirs,files in os.walk("C://"):
for name in files:
print(os.path.join(root,name))
os.walk()
按照这样的日期格式(xxxx-xx-xx)每日生成一个文件,例如今天生成的文件为2013-09-23.log, 并且把磁盘的使用情况写到到这个文件中。
import os
import sys
import time
new_time = time.strftime("%Y-%m-%d")
disk_status = os.popen("df -h").readlines()
str1 = ''.join(disk_status)
f = open(new_time+'.log','w')
f.write("%s"%str1)
f.flush()
f.close()
统计出每个IP的访问量有多少?(从日志文件中查找)
import sys
list = []
f = open("/var/log/httpd/access_log","r")
str1 = f.readlines()
f.close()
for i in str1:
ip=i.split()[0]
list.append(ip)
list_num=set(list)
for j in list_num:
num=list.count(j)
print("%s -----> %s" %(num,j))
写个程序,接受用户输入数字,并进行校验,非数字给出错误提示,然后重新等待用户输入。
import tab
import sys
while True:
try:
num=int(input("输入数字:").strip())
for x in range(2,num+1):
for y in range(2,x):
if x % y == 0:
break
else:
print(x)
except ValueError:
print("您输入的不是数字")
except KeyboardInterrupt:
sys.exit("
")
ps 可以查看进程的内存占用大小,写一个脚本计算一下所有进程所占用内存大小的和。
import sys
import os
list=[]
sum=0
str1=os.popen("ps aux","r").readlines()
for i in str1:
str2=i.split()
new_rss=str2[5]
list.append(new_rss)
for i in list[1:-1]:
num=int(i)
sum=sum+num
print("%s ---> %s"%(list[0],sum))
关于Python 命令行参数argv
import sys
if len(sys.argv) < 2:
print ("没有输入任何参数")
sys.exit()
if sys.argv[1].startswith("-"):
option = sys.argv[1][1:]
利用random生成6位数字加字母随机验证码
import sys
import random
rand=[]
for x in range(6):
y=random.randrange(0,5)
if y == 2 or y == 4:
num=random.randrange(0,9)
rand.append(str(num))
else:
temp=random.randrange(65,91)
c=chr(temp)
rand.append(c)
result="".join(rand)
print(result)
自动化-使用pexpect非交互登陆系统
import pexpect
import sys
ssh = pexpect.spawn('ssh [email protected]')
fout = file('sshlog.txt', 'w')
ssh.logfile = fout
ssh.expect("[email protected]'s password:")
ssh.sendline("密码")
ssh.expect('#')
ssh.sendline('ls /home')
ssh.expect('#')
Python-取系统时间
import sys
import time
time_str = time.strftime("日期:%Y-%m-%d",time.localtime())
print(time_str)
time_str= time.strftime("时间:%H:%M",time.localtime())
print(time_str)
psutil-获取内存使用情况
import sys
import os
import psutil
memory_convent = 1024 * 1024
mem =psutil.virtual_memory()
print("内存容量为:"+str(mem.total/(memory_convent))+"MB
")
print("已使用内存:"+str(mem.used/(memory_convent))+"MB
")
print("可用内存:"+str(mem.total/(memory_convent)-mem.used/(1024*1024))+"MB
")
print("buffer容量:"+str(mem.buffers/( memory_convent ))+"MB
")
print("cache容量:"+str(mem.cached/(memory_convent))+"MB
")
Python-通过SNMP协议监控CPU
注意:被监控的机器上需要支持snmp协议 yum install -y net-snmp*
import os
def getAllitems(host, oid):
sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid + '|grep Raw|grep Cpu|grep -v Kernel').read().split('
')[:-1]
return sn1
def getDate(host):
items = getAllitems(host, '.1.3.6.1.4.1.2021.11')
if name == ' main ':
Python-通过SNMP协议监控系统负载
注意:被监控的机器上需要支持snmp协议 yum install -y net-snmp*
import os
import sys
def getAllitems(host, oid):
sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid).read().split('
')
return sn1
def getload(host,loid):
load_oids = Ƈ.3.6.1.4.1.2021.10.1.3.' + str(loid)
return getAllitems(host,load_oids)[0].split(':')[3]
if name == ' main ':
Python-通过SNMP协议监控内存
注意:被监控的机器上需要支持snmp协议 yum install -y net-snmp*
import os
def getAllitems(host, oid):
def getSwapTotal(host):
def getSwapUsed(host):
def getMemTotal(host):
def getMemUsed(host):
if name == ' main ':
Python-通过SNMP协议监控磁盘
注意:被监控的机器上需要支持snmp协议 yum install -y net-snmp*
import re
import os
def getAllitems(host,oid):
def getDate(source,newitem):
def getRealDate(item1,item2,listname):
def caculateDiskUsedRate(host):
if name == ' main ':
Python-通过SNMP协议监控网卡流量
注意:被监控的机器上需要支持snmp协议 yum install -y net-snmp*
import re
import os
def getAllitems(host,oid):
sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid).read().split('
')[:-1]
return sn1
def getDevices(host):
device_mib = getAllitems(host,'RFC1213-MIB::ifDescr')
device_list = []
def getDate(host,oid):
date_mib = getAllitems(host,oid)[1:]
date = []
if name == ' main ':
Python-实现多级菜单
import os
import sys
ps="[None]->"
ip=["192.168.1.1","192.168.1.2","192.168.1.3"]
flage=1
while True:
ps="[None]->"
temp=input(ps)
if (temp=="test"):
print("test page !!!!")
elif(temp=="user"):
while (flage == 1):
ps="[User]->"
temp1=input(ps)
if(temp1 =="exit"):
flage=0
break
elif(temp1=="show"):
for i in range(len(ip)):
print(i)
Python实现一个没用的东西
import sys
ps="[root@localhost]# "
ip=["192.168.1.1","192.168.1.2","192.168.1.3"]
while True:
temp=input(ps)
temp1=temp.split()
检查各个进程读写的磁盘IO
import sys
import os
import time
import signal
import re
class DiskIO:
def init (self, pname=None, pid=None, reads=0, writes=0):
self.pname = pname
self.pid = pid
self.reads = 0
self.writes = 0
def main():
argc = len(sys.argv)
if argc != 1:
print ("usage: please run this script like [./lyshark.py]")
sys.exit(0)
if os.getuid() != 0:
print ("Error: This script must be run as root")
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
os.system('echo 1 > /proc/sys/vm/block_mp')
print ("TASK PID READ WRITE")
while True:
os.system('dmesg -c > /tmp/diskio.log')
l = []
f = open('/tmp/diskio.log', 'r')
line = f.readline()
while line:
m = re.match(
'^(S+)(d+)(d+): (READ|WRITE) block (d+) on (S+)', line)
if m != None:
if not l:
l.append(DiskIO(m.group(1), m.group(2)))
line = f.readline()
continue
found = False
for item in l:
if item.pid == m.group(2):
found = True
if m.group(3) == "READ":
item.reads = item.reads + 1
elif m.group(3) == "WRITE":
item.writes = item.writes + 1
if not found:
l.append(DiskIO(m.group(1), m.group(2)))
line = f.readline()
time.sleep(1)
for item in l:
print ("%-10s %10s %10d %10d" %
(item.pname, item.pid, item.reads, item.writes))
def signal_handler(signal, frame):
os.system('echo 0 > /proc/sys/vm/block_mp')
sys.exit(0)
if name ==" main ":
main()
利用Pexpect实现自动非交互登陆linux
import pexpect
import sys
ssh = pexpect.spawn('ssh [email protected]')
fout = file('sshlog.log', 'w')
ssh.logfile = fout
ssh.expect("[email protected]'s password:")
ssh.sendline("密码")
ssh.expect('#')
ssh.sendline('ls /home')
ssh.expect('#')
利用psutil模块获取系统的各种统计信息
import sys
import psutil
import time
import os
time_str = time.strftime( "%Y-%m-%d", time.localtime( ) )
file_name = "./" + time_str + ".log"
if os.path.exists ( file_name ) == False :
os.mknod( file_name )
handle = open ( file_name , "w" )
else :
handle = open ( file_name , "a" )
if len( sys.argv ) == 1 :
print_type = 1
else :
print_type = 2
def isset ( list_arr , name ) :
if name in list_arr :
return True
else :
return False
print_str = "";
if ( print_type == 1 ) or isset( sys.argv,"mem" ) :
memory_convent = 1024 * 1024
mem = psutil.virtual_memory()
print_str += " 内存状态如下:
"
print_str = print_str + " 系统的内存容量为: "+str( mem.total/( memory_convent ) ) + " MB
"
print_str = print_str + " 系统的内存以使用容量为: "+str( mem.used/( memory_convent ) ) + " MB
"
print_str = print_str + " 系统可用的内存容量为: "+str( mem.total/( memory_convent ) - mem.used/( 1024*1024 )) + "MB
"
print_str = print_str + " 内存的buffer容量为: "+str( mem.buffers/( memory_convent ) ) + " MB
"
print_str = print_str + " 内存的cache容量为:" +str( mem.cached/( memory_convent ) ) + " MB
"
if ( print_type == 1 ) or isset( sys.argv,"cpu" ) :
print_str += " CPU状态如下:
"
cpu_status = psutil.cpu_times()
print_str = print_str + " user = " + str( cpu_status.user ) + "
"
print_str = print_str + " nice = " + str( cpu_status.nice ) + "
"
print_str = print_str + " system = " + str( cpu_status.system ) + "
"
print_str = print_str + " idle = " + str ( cpu_status.idle ) + "
"
print_str = print_str + " iowait = " + str ( cpu_status.iowait ) + "
"
print_str = print_str + " irq = " + str( cpu_status.irq ) + "
"
print_str = print_str + " softirq = " + str ( cpu_status.softirq ) + "
"
print_str = print_str + " steal = " + str ( cpu_status.steal ) + "
"
print_str = print_str + " guest = " + str ( cpu_status.guest ) + "
"
if ( print_type == 1 ) or isset ( sys.argv,"disk" ) :
print_str += " 硬盘信息如下:
"
disk_status = psutil.disk_partitions()
for item in disk_status :
print_str = print_str + " "+ str( item ) + "
"
if ( print_type == 1 ) or isset ( sys.argv,"user" ) :
print_str += " 登录用户信息如下:
"
user_status = psutil.users()
for item in user_status :
print_str = print_str + " "+ str( item ) + "
"
print_str += "---------------------------------------------------------------
"
print ( print_str )
handle.write( print_str )
handle.close()
import psutil
mem = psutil.virtual_memory()
print mem.total,mem.used,mem
print psutil.swap_memory() # 输出获取SWAP分区信息
cpu = psutil.cpu_stats()
printcpu.interrupts,cpu.ctx_switches
psutil.cpu_times(percpu=True) # 输出每个核心的详细CPU信息
psutil.cpu_times().user # 获取CPU的单项数据 [用户态CPU的数据]
psutil.cpu_count() # 获取CPU逻辑核心数,默认logical=True
psutil.cpu_count(logical=False) # 获取CPU物理核心数
psutil.disk_partitions() # 列出全部的分区信息
psutil.disk_usage('/') # 显示出指定的挂载点情况【字节为单位】
psutil.disk_io_counters() # 磁盘总的IO个数
psutil.disk_io_counters(perdisk=True) # 获取单个分区IO个数
psutil.net_io_counter() 获取网络总的IO,默认参数pernic=False
psutil.net_io_counter(pernic=Ture)获取网络各个网卡的IO
psutil.pids() # 列出所有进程的pid号
p = psutil.Process(2047)
p.name() 列出进程名称
p.exe() 列出进程bin路径
p.cwd() 列出进程工作目录的绝对路径
p.status()进程当前状态[sleep等状态]
p.create_time() 进程创建的时间 [时间戳格式]
p.uids()
p.gids()
p.cputimes() 【进程的CPU时间,包括用户态、内核态】
p.cpu_affinity() # 显示CPU亲缘关系
p.memory_percent() 进程内存利用率
p.meminfo() 进程的RSS、VMS信息
p.io_counters() 进程IO信息,包括读写IO数及字节数
p.connections() 返回打开进程socket的nametples列表
p.num_threads() 进程打开的线程数
import psutil
from subprocess import PIPE
p =psutil.Popen(["/usr/bin/python" ,"-c","print 'helloworld'"],stdout=PIPE)
p.name()
p.username()
p.communicate()
p.cpu_times()
psutil.users() # 显示当前登录的用户,和Linux的who命令差不多
psutil.boot_time() 结果是个UNIX时间戳,下面我们来转换它为标准时间格式,如下:
datetime.datetime.fromtimestamp(psutil.boot_time()) # 得出的结果不是str格式,继续进行转换 datetime.datetime.fromtimestamp(psutil.boot_time()).strftime('%Y-%m-%d%H:%M:%S')
Python生成一个随机密码
import random, string
def GenPassword(length):
if name == ' main ':
print (GenPassword(6))
10. python 如何查看光驱盘符
南无阿正败族弥陀举弊佛
南无枯前阿弥陀佛
南无阿弥陀佛
同求方法!!!!