Python运维学习Day02-subprocess/threading/psutil

文章目录

  • 1. 检测网段在线主机
  • 2. 获取系统变量的模块 psutil

1. 检测网段在线主机

import subprocessdef checkIP(ip):cmd = f'ping -n 1 -w 1 {ip}'null = open('nlll',mode='wb')status = subprocess.call(cmd,shell=True,stdout=null,stderr=null)if status == 0:print(f"主机[{ip}]在线")null.close()if __name__ == '__main__':for i in range(1,255,1):ip = f"192.169.3.{i}"checkIP(ip)

运行结果:
在这里插入图片描述

我们看看 subprocess.call的用法


In [10]: subprocess.call??
Signature: subprocess.call(*popenargs, timeout=None, **kwargs)
Source:
def call(*popenargs, timeout=None, **kwargs):"""Run command with arguments.  Wait for command to complete ortimeout, then return the returncode attribute.The arguments are the same as for the Popen constructor.  Example:retcode = call(["ls", "-l"])"""with Popen(*popenargs, **kwargs) as p:try:return p.wait(timeout=timeout)except:  # Including KeyboardInterrupt, wait handled that.p.kill()# We don't call p.wait() again as p.__exit__ does that for us.raise
File:      c:\users\thinkpad\appdata\local\programs\python\python39\lib\subprocess.py
Type:      function

该函数运行一条带参数的命令,返回值执行命令的返回码,运行时发现如此串联运行太慢了,我们修改下代码让其并行运行。

import subprocess
import threadingdef checkIP(ip):cmd = f'ping -n 1 -w 1 {ip}'null = open('nlll',mode='wb')status = subprocess.call(cmd,shell=True,stdout=null,stderr=null)if status == 0:print(f"主机[{ip}]在线")null.close()if __name__ == '__main__':for i in range(1,255,1):ip = f"192.169.3.{i}"ping_threading = threading.Thread(target=checkIP,args=(ip,))ping_threading.start()

我们看一下threading.Thread的用法


In [12]: threading.Thread??
Init signature:
threading.Thread(group=None,target=None,name=None,args=(),kwargs=None,*,daemon=None,
)
Source:
class Thread:"""A class that represents a thread of control.This class can be safely subclassed in a limited fashion. There are two waysto specify the activity: by passing a callable object to the constructor, orby overriding the run() method in a subclass."""_initialized = Falsedef __init__(self, group=None, target=None, name=None,args=(), kwargs=None, *, daemon=None):"""This constructor should always be called with keyword arguments. Arguments are:*group* should be None; reserved for future extension when a ThreadGroupclass is implemented.*target* is the callable object to be invoked by the run()method. Defaults to None, meaning nothing is called.*name* is the thread name. By default, a unique name is constructed ofthe form "Thread-N" where N is a small decimal number.*args* is the argument tuple for the target invocation. Defaults to ().*kwargs* is a dictionary of keyword arguments for the targetinvocation. Defaults to {}.If a subclass overrides the constructor, it must make sure to invokethe base class constructor (Thread.__init__()) before doing anythingelse to the thread."""assert group is None, "group argument must be None for now"if kwargs is None:kwargs = {}self._target = targetself._name = str(name or _newname())self._args = argsself._kwargs = kwargsif daemon is not None:self._daemonic = daemonelse:self._daemonic = current_thread().daemonself._ident = Noneif _HAVE_THREAD_NATIVE_ID:self._native_id = Noneself._tstate_lock = Noneself._started = Event()self._is_stopped = Falseself._initialized = True# Copy of sys.stderr used by self._invoke_excepthook()self._stderr = _sys.stderrself._invoke_excepthook = _make_invoke_excepthook()# For debugging and _after_fork()_dangling.add(self)def _reset_internal_locks(self, is_alive):# private!  Called by _after_fork() to reset our internal locks as# they may be in an invalid state leading to a deadlock or crash.self._started._at_fork_reinit()if is_alive:# bpo-42350: If the fork happens when the thread is already stopped# (ex: after threading._shutdown() has been called), _tstate_lock# is None. Do nothing in this case.if self._tstate_lock is not None:self._tstate_lock._at_fork_reinit()self._tstate_lock.acquire()else:# The thread isn't alive after fork: it doesn't have a tstate# anymore.self._is_stopped = Trueself._tstate_lock = Nonedef __repr__(self):assert self._initialized, "Thread.__init__() was not called"status = "initial"if self._started.is_set():status = "started"self.is_alive() # easy way to get ._is_stopped set when appropriateif self._is_stopped:status = "stopped"if self._daemonic:status += " daemon"if self._ident is not None:status += " %s" % self._identreturn "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status)def start(self):"""Start the thread's activity.It must be called at most once per thread object. It arranges for theobject's run() method to be invoked in a separate thread of control.This method will raise a RuntimeError if called more than once on thesame thread object."""if not self._initialized:raise RuntimeError("thread.__init__() not called")if self._started.is_set():raise RuntimeError("threads can only be started once")with _active_limbo_lock:_limbo[self] = selftry:_start_new_thread(self._bootstrap, ())except Exception:with _active_limbo_lock:del _limbo[self]raiseself._started.wait()def run(self):"""Method representing the thread's activity.You may override this method in a subclass. The standard run() methodinvokes the callable object passed to the object's constructor as thetarget argument, if any, with sequential and keyword arguments takenfrom the args and kwargs arguments, respectively."""try:if self._target:self._target(*self._args, **self._kwargs)finally:# Avoid a refcycle if the thread is running a function with# an argument that has a member that points to the thread.del self._target, self._args, self._kwargs
...
File:           c:\users\thinkpad\appdata\local\programs\python\python39\lib\threading.py
Type:           type
Subclasses:     Timer, _MainThread, _DummyThread, HistorySavingThread

这里着重讲下几个重要参数和start方法
target: 一个回调函数,将会运行run()方法。
args: 元组对象,回调函数target的参数
start: 开始激活线程

2. 获取系统变量的模块 psutil

查看当前用户的名称,和开机时间

In [14]: import psutil as psIn [15]: ps.users()
Out[15]: [suser(name='ThinkPad', terminal=None, host=None, started=1698541200.6304576, pid=None)]In [16]: ps.users()[0]
Out[16]: suser(name='ThinkPad', terminal=None, host=None, started=1698541200.6304576, pid=None)In [17]: ps.users()[0].started
Out[17]: 1698541200.6304576In [18]: import datetimeIn [19]: t = ps.users()[0].startedIn [20]: datetime.datetime.fromtimestamp(t)
Out[20]: datetime.datetime(2023, 10, 29, 9, 0, 0, 630458)

获取电脑cpu核数

In [23]: ps.cpu_count()
Out[23]: 8In [24]: ps.cpu_count??
Signature: ps.cpu_count(logical=True)
Source:
def cpu_count(logical=True):"""Return the number of logical CPUs in the system (same asos.cpu_count() in Python 3.4).If *logical* is False return the number of physical cores only(e.g. hyper thread CPUs are excluded).Return None if undetermined.The return value is cached after first call.If desired cache can be cleared like this:>>> psutil.cpu_count.cache_clear()"""if logical:ret = _psplatform.cpu_count_logical()else:ret = _psplatform.cpu_count_cores()if ret is not None and ret < 1:ret = Nonereturn ret
File:      c:\users\thinkpad\envs\support\lib\site-packages\psutil\__init__.py
Type:      function

这里默认是获取的逻辑核,如果要获取是物理核数,需要加上参数logical=False

In [25]: ps.cpu_count(logical=False)
Out[25]: 4

获取boot开机时间

In [29]: ps.boot_time??
Signature: ps.boot_time()
Source:
def boot_time():"""Return the system boot time expressed in seconds since the epoch."""# Note: we are not caching this because it is subject to# system clock updates.return _psplatform.boot_time()
File:      c:\users\thinkpad\envs\support\lib\site-packages\psutil\__init__.py
Type:      functionIn [30]: b = ps.boot_time()In [31]: b
Out[31]: 1698541187.1580527In [32]: datetime.datetime.fromtimestamp(b)
Out[32]: datetime.datetime(2023, 10, 29, 8, 59, 47, 158053)

获取电脑内存信息

In [36]: ps.virtual_memory()
Out[36]: svmem(total=17048784896, available=10635776000, percent=37.6, used=6413008896, free=10635776000)In [37]: ps.virtual_memory??
Signature: ps.virtual_memory()
Source:
def virtual_memory():"""Return statistics about system memory usage as a namedtupleincluding the following fields, expressed in bytes:- total:total physical memory available.- available:the memory that can be given instantly to processes without thesystem going into swap.This is calculated by summing different memory values dependingon the platform and it is supposed to be used to monitor actualmemory usage in a cross platform fashion.- percent:the percentage usage calculated as (total - available) / total * 100- used:memory used, calculated differently depending on the platform anddesigned for informational purposes only:macOS: active + wiredBSD: active + wired + cachedLinux: total - free- free:memory not being used at all (zeroed) that is readily available;note that this doesn't reflect the actual memory available(use 'available' instead)Platform-specific fields:- active (UNIX):memory currently in use or very recently used, and so it is in RAM.- inactive (UNIX):memory that is marked as not used.- buffers (BSD, Linux):cache for things like file system metadata.- cached (BSD, macOS):cache for various things.- wired (macOS, BSD):memory that is marked to always stay in RAM. It is never moved to disk.- shared (BSD):memory that may be simultaneously accessed by multiple processes.The sum of 'used' and 'available' does not necessarily equal total.On Windows 'available' and 'free' are the same."""global _TOTAL_PHYMEMret = _psplatform.virtual_memory()# cached for later use in Process.memory_percent()_TOTAL_PHYMEM = ret.totalreturn ret
File:      c:\users\thinkpad\envs\support\lib\site-packages\psutil\__init__.py
Type:      functionIn [38]:

获取cpu性能,上下文切换,硬件中断,软件中断,系统调用

In [42]: ps.cpu_stats()
Out[42]: scpustats(ctx_switches=217425683, interrupts=185259877, soft_interrupts=0, syscalls=753877621)In [43]: ps.cpu_stats??
Signature: ps.cpu_stats()
Source:
def cpu_stats():"""Return CPU statistics."""return _psplatform.cpu_stats()
File:      c:\users\thinkpad\envs\support\lib\site-packages\psutil\__init__.py
Type:      function
```

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/124030.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

ue5 右击.uproject generator vs project file 错误

出现如下错误 Unable to find valid 14.31.31103 C toolchain for VisualStudio2022 x64 就算你升级了你的 vs installer 也不好使 那是因为 在C:\Users\{YourUserName}\AppData\Roaming\Unreal Engine\UnrealBuildTool\BuildConfiguration.xml 这个缓存配置文件中写死了 14…

leetcode-链表

链表是一个用指针串联起来的线性结构&#xff0c;每个结点由数据域和指针域构成&#xff0c;指针域存放的是指向下一个节点的指针&#xff0c;最后一个节点指向NULL&#xff0c;第一个结点称为头节点head。 常见的链表有单链表、双向链表、循环链表。双向链表就是多了一个pre指…

​轻量应用服务器有什么优势?如何评价亚马逊云科技轻量应用服务器?

什么是轻量应用服务器&#xff1f; 随着如今各行各业对云计算的需求越来越多&#xff0c;云服务器也被越来越多的企业所广泛采用。其中&#xff0c;轻量应用服务器是一种简单、高效、可靠的云计算服务&#xff0c;能够为开发人员、企业和个人提供轻量级的虚拟专用服务器&#…

AWTK 液体流动效果控件发布

液体流动效果控件。 主要特色&#xff1a; 支持水平和垂直方向。支持正向和反向流动。支持设置头尾的图片。支持设置流动的图片。支持设置速度的快慢。支持启停操作。 准备 获取 awtk 并编译 git clone https://github.com/zlgopen/awtk.git cd awtk; scons; cd -运行 生成…

JMeter简单使用

JMeter是一个功能强大的开源性能测试工具&#xff0c;用于对各种应用程序、协议和服务器进行性能和负载测试。它被广泛用于测试Web应用程序的性能&#xff0c;并可以模拟多种负载条件和行为。 JMeter使用 添加线程组 设置线程组的配置 设置请求 配置请求 添加监听器 查看压…

JVM虚拟机:Java对象的头信息有什么?

本文重点 在前面的课程中,我们学习了对象头,其中对象头包含Mark Word和class pointer,当然数组还会有一个数组长度。本文主要分析Mark Work中包含的信息。 Mark Word 以下两张图是一个意思: 32位 32位 64位 以上就是Mark Word会存储的信息,这个意思是说Java对象在不同…

计网小题题库整理第一轮(面向期末基础)(2)

该系列第二期&#xff0c;第一期链接在这~ 计网小题题库整理第一轮&#xff08;面向期末基础&#xff09;&#xff08;1&#xff09;https://blog.csdn.net/jsl123x/article/details/134030486?spm1001.2014.3001.5501 一.选择题 1、Internet的前身是 &#xff08;C &#x…

2015年亚太杯APMCM数学建模大赛B题城市公共交通服务水平动态评价模型求解全过程文档及程序

2015年亚太杯APMCM数学建模大赛 B题 城市公共交通服务水平动态评价模型 原题再现 城市公共交通服务评价是城市公共交通系统建设和提高公共交通运营效率的重要组成部分。对于公交企业&#xff0c;管理和规划部门&#xff0c;传统公交车站、线路和换乘枢纽的规划数据只是基于主…

【MySQL索引与优化篇】InnoDB数据存储结构

文章目录 1. 数据库的存储结构:页1.1 磁盘与内存交互基本单位:页1.2 页结构概述1.3 页的上层结构 2. 页的内部结构3. InnoDB行格式(或记录格式)3.1 Compact行格式3.2 Dynamic和Compressed行格式3.3 Redundant行格式 4. 区、段与碎片区4.1 为什么要有区&#xff1f;4.2 为什么要…

Ortec974A EPICS IOC程序

1&#xff09; 创建一个用户存放这个IOC程序结构的目录&#xff1a; rootorangepi4-lts:/usr/local/EPICS/program# mkdir ortec974A rootorangepi4-lts:/usr/local/EPICS/program# cd ortec974A/ rootorangepi4-lts:/usr/local/EPICS/program/ortec974A# ls2&#xff09;使用…

mediapipe 训练自有图像数据分类

参考&#xff1a; https://developers.google.com/mediapipe/solutions/customization/image_classifier https://colab.research.google.com/github/googlesamples/mediapipe/blob/main/examples/customization/image_classifier.ipynb#scrollToplvO-YmcQn5g 安装&#xff1a…

CSS中的栅格布局

CSS中的栅格布局 在写前端项目的时候&#xff0c;我之前一直习惯使用flex布局&#xff0c;flex布局写起来比较随心&#xff0c;几乎可以实现任意形式的页面布局。不过自从B占看到某位大佬的grid布局后&#xff0c;发现布局居然还可以这么玩&#xff0c;正好自己在写一个vue3的…

【大数据Hive】hive 表数据优化使用详解

目录 一、前言 二、hive 常用数据存储格式 2.1 文件格式-TextFile 2.1.1 操作演示 2.2 文件格式 - SequenceFile 2.2.1 操作演示 2.3 文件格式 -Parquet 2.3.1 Parquet简介 2.3.2 操作演示 2.4 文件格式-ORC 2.4.1 ORC介绍 2.4.2 操作演示 三、hive 存储数据压缩优…

在线主动学习算法评估策略:prequential evaluation procedure

在线主动学习算法评估策略&#xff1a;prequential evaluation procedure 在在线主动学习领域(Online Active Learning)&#xff0c;对在线主动学习算法的评估策略有多种方法&#xff0c;而现如今常用的方法是prequential evaluation procedure(出自论文《High density-focuse…

c++二叉树遍历

参考文献 数据结构c语言版&#xff0c;严蔚敏_吴伟民著。 二叉树 中序遍历代码实现 #include<vector> #include<iostream> using namespace std;//Definition for a binary tree node. struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode() : v…

腾讯云轻量应用镜像、系统镜像、Docker基础镜像、自定义镜像和共享镜像介绍

腾讯云轻量应用服务器镜像类型分为应用镜像、系统镜像、Docker基础镜像、自定义镜像和共享镜像&#xff0c;腾讯云百科txybk.com来详细说下不同镜像类型说明和详细介绍&#xff1a; 轻量应用服务器镜像类型说明 腾讯云轻量应用服务器 应用镜像&#xff1a;独有的应用镜像除了包…

Mysql设置了更新时间自动更新,指定更新部分sql时不进行时间更新

现象&#xff1a; 因为字段设置了自动更新&#xff0c;所以sql语句一进行修改此字段就会自动更新时间&#xff0c;但是呢我们的有部分定时任务是半夜执行&#xff0c;并且不能让这个任务修改到数据的更新时间 解决&#xff1a; <update id"updateCreative">ALT…

GoLand GC(垃圾回收机制)简介及调优

GC(Garbage Collector)垃圾回收机制及调优 简单理解GC机制 其实gc机制特别容易理解&#xff0c;就是物理内存的自动清理工。我们可以把内存想象成一个房间&#xff0c;程序运行时会在这个房间里存放各种东西&#xff0c;但有时候我们会忘记把不再需要的东西拿出去&#xff0c…

HubSpot CRM是什么?如何添加、使用呢?

HubSpot CRM是一款强大的客户关系管理工具&#xff0c;它不仅简化了销售和市场营销过程&#xff0c;还提供了多种功能&#xff0c;有助于增强客户互动、提高销售效率和提供更多的洞察信息。 今天运营坛将带领大家深入了解HubSpot CRM&#xff0c;涵盖了它的定义、使用流程、添…

基于STM32闭环步进电机控制系统设计

**单片机设计介绍&#xff0c;1654基于STM32闭环步进电机控制系统设计&#xff08;仿真&#xff0c;程序&#xff0c;说明&#xff09; 文章目录 一 概要二、功能设计设计思路 三、 软件设计原理图 五、 程序文档 六、 文章目录 一 概要 基于STM32的闭环步进电机控制系统设计是…