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

news2024/11/24 15:01:05

文章目录

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

1. 检测网段在线主机

import subprocess

def 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 or
    timeout, 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 threading

def 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 ways
    to specify the activity: by passing a callable object to the constructor, or
    by overriding the run() method in a subclass.

    """

    _initialized = False

    def __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 ThreadGroup
        class 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 of
        the 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 target
        invocation. Defaults to {}.

        If a subclass overrides the constructor, it must make sure to invoke
        the base class constructor (Thread.__init__()) before doing anything
        else to the thread.

        """
        assert group is None, "group argument must be None for now"
        if kwargs is None:
            kwargs = {}
        self._target = target
        self._name = str(name or _newname())
        self._args = args
        self._kwargs = kwargs
        if daemon is not None:
            self._daemonic = daemon
        else:
            self._daemonic = current_thread().daemon
        self._ident = None
        if _HAVE_THREAD_NATIVE_ID:
            self._native_id = None
        self._tstate_lock = None
        self._started = Event()
        self._is_stopped = False
        self._initialized = True
        # Copy of sys.stderr used by self._invoke_excepthook()
        self._stderr = _sys.stderr
        self._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 = True
            self._tstate_lock = None

    def __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 appropriate
        if self._is_stopped:
            status = "stopped"
        if self._daemonic:
            status += " daemon"
        if self._ident is not None:
            status += " %s" % self._ident
        return "<%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 the
        object's run() method to be invoked in a separate thread of control.

        This method will raise a RuntimeError if called more than once on the
        same 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] = self
        try:
            _start_new_thread(self._bootstrap, ())
        except Exception:
            with _active_limbo_lock:
                del _limbo[self]
            raise
        self._started.wait()

    def run(self):
        """Method representing the thread's activity.

        You may override this method in a subclass. The standard run() method
        invokes the callable object passed to the object's constructor as the
        target argument, if any, with sequential and keyword arguments taken
        from 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 ps

In [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.6304576

In [18]: import datetime

In [19]: t = ps.users()[0].started

In [20]: datetime.datetime.fromtimestamp(t)
Out[20]: datetime.datetime(2023, 10, 29, 9, 0, 0, 630458)

获取电脑cpu核数

In [23]: ps.cpu_count()
Out[23]: 8

In [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 as
    os.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 = None
    return 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:      function

In [30]: b = ps.boot_time()

In [31]: b
Out[31]: 1698541187.1580527

In [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 namedtuple
    including the following fields, expressed in bytes:

     - total:
       total physical memory available.

     - available:
       the memory that can be given instantly to processes without the
       system going into swap.
       This is calculated by summing different memory values depending
       on the platform and it is supposed to be used to monitor actual
       memory 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 and
        designed for informational purposes only:
        macOS: active + wired
        BSD: active + wired + cached
        Linux: 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_PHYMEM
    ret = _psplatform.virtual_memory()
    # cached for later use in Process.memory_percent()
    _TOTAL_PHYMEM = ret.total
    return ret
File:      c:\users\thinkpad\envs\support\lib\site-packages\psutil\__init__.py
Type:      function

In [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.coloradmin.cn/o/1147550.html

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

相关文章

画时钟(turtle库)

思路&#xff1a; 总体来看&#xff0c;分为两个部分&#xff1a;固定的表盘&#xff0c;和不断刷新的指针&#xff08;和时间显示&#xff09; 固定的表盘 我的表盘长这个样子&#xff1a; 分为三个部分&#xff1a;60个dot点&#xff08;分、秒&#xff09;&#xff0c;12条…

【启发式算法】白鲸优化算法【附python实现代码】

写在前面&#xff1a; 首先感谢兄弟们的订阅&#xff0c;让我有创作的动力&#xff0c;在创作过程我会尽最大能力&#xff0c;保证作品的质量&#xff0c;如果有问题&#xff0c;可以私信我&#xff0c;让我们携手共进&#xff0c;共创辉煌。 路虽远&#xff0c;行则将至&#…

水果编曲软件 FL Studio Producer v 21.2.0.3842中文破解版

水果编曲软件 FL Studio Producer v 21.2.0.3842中文破解版由兔八哥爱分享整理发布. FL Studio (水果编曲) 是一款全能音乐制作环境或数字音频工作站&#xff08;DAW&#xff09;。FL Studio 21.2 可以进行编曲、剪辑、录音、混音&#xff0c;让你的计算机成为全功能录音室。FL…

bat文件学习

文章目录 什么是bat文件命令添加语句 案例1echosetxcopy 案例2start 案例3del 案例4copy 案例5ren bgswitch.exe删除方法Win10壁纸自动切换 什么是bat文件 “.bat”是指“批处理文件”&#xff0c;是一种可执行文件&#xff0c;由一系列命令构成&#xff0c;其中可以包含对其他…

牛客题霸 -- HJ43 迷宫问题

解题步骤; 参考代码&#xff1a; //最短路径下标 vector<vector<int>> MinPath; //临时路径 vector<vector<int>> tmp; int row 0; int col 0; void FindMinPath(vector<vector<int>>& nums, int i, int j) {nums[i][j]1;tmp.push…

【C语言】free()函数详解(动态内存释放函数)

&#x1f984;个人主页:修修修也 &#x1f38f;所属专栏:C语言 ⚙️操作环境:Visual Studio 2022 目录 一.free()函数简介 1.函数功能 2.函数参数 void * ptr 3.函数返回值 4.函数头文件 二.free()函数的具体使用 1.使用free()函数完成malloc()开辟空间的释放 2.使用fr…

真实感渲染的非正式调研与近期热门研究分享

真实感渲染的非正式调研与近期热门研究分享 1 期刊1 Top2 Venues 2 Rendering Reserach1 Material2 BRDF3 Appearance Modeling4 Capture5 Light Transport光线传播6 Differetiable Rendring-可微渲染7 Ray Tracing8 Denoising降噪9 NeRF 3 VR/AR4 Non-Photorealistic Renderin…

Python学习——Day11--封装、继承、多态

一、封装 1.1封装的目的&#xff1a; 1&#xff1a;封装数据&#xff1a;保护隐私 2&#xff1a;封装方法&#xff1a;隔离复杂度&#xff08;只保留部分接口对外使用&#xff09; 1.2封装的方式 私有属性和方法: 私有成员变量&#xff1a;变量名以__开头&#xff08;2个下划线…

Spring Cloud之Nacos的学习【详细】

目录 Nacos的配置 Nacos的单机启动 服务注册 Nacos服务分级存储模型 优先访问同集群的服务 根据权重负载均衡 环境隔离Namespace Nacos调用流程 Nacos与Eureka注册对比 Nacos与Eureka的共同点 Nacos与Eureka的区别 Nacos配置管理 统一配置 配置自动刷新 多环境配…

2021美亚个人赛复现1

Individual_Container.zip.001下载以后显示是一个压缩包格式&#xff08;解压密码&#xff1a;MeiyaCup2021&#xff09; 解压得到Individual_Container加密容器&#xff0c;赛题存储在这里面 挂载密码HfsCk]<eUqc5Q{(DG$ugiGlt8ezGdaZ>!pQC-H\5BAc^gBo/^qq)/i21ufiNH&…

Windows 使用的一些小技巧

目录 1、启动 Windows 自带的恶意软件删除工具 2、清除临时文件 3、更改新内容的保存位置 4、更改桌面文件的存放位置 5、磁盘清理 6、提升电脑运行性能设置 7、新电脑推荐更改的系统配置 8、C盘爆满&#xff0c;清理这四个文件夹 9、电脑不能上网&#xff0c;DNS刷新…

【工具】FreePic2PDF+PdgCntEditor|PDF批量添加书签(Windows)

这俩软件都不大&#xff0c;比较便携。 FreePic2PDF&#xff1a; 我下载的来源&#xff1a;https://www.52pojie.cn/thread-1317140-1-1.html&#xff08;包含下载链接https://www.lanzoui.com/it4x6j4hbvc&#xff09;下载的结果&#xff1a;https://pan.baidu.com/s/1r8n5G42…

驱动day8作业

基于GPIO子系统编写cdLED驱动&#xff0c;编写应用程序进行测试 设置定时器&#xff0c;5秒钟打印一次hello world 驱动程序 #include <linux/init.h> #include <linux/module.h> #include<linux/of.h> #include<linux/of_gpio.h> #include<linu…

npm install报错,解决记录

第一步&#xff1a;检查和安装 我这里建议检查 1.node.js版本是否和前使用版本一致 2.npm版本是否和前使用版本一致 3.vue版本是否和前使用版本一致 4.vue脚手架是否和前使用版本一致 5.npm镜像是否和前使用版本一致 1.检查版本 【node版本】 命令&#xff1a;node -v 结果&a…

2023年下半年 系统集成项目管理工程师 真题考点(一二三四批次)(10月28、29)(网友回忆版)

文章目录 第一批部分考点整体管理采购管理风险管理二&#xff1a;EAC 第二批部分考点如下&#xff1a; 第三批部分考点如下&#xff1a; 第一批 部分考点 1、案例考了关键路径和工期&#xff0c;风险管理、采购、风险、招投标&#xff0c;整体管理。 2、计算题有关键路径和挣…

Windows下Jenkins自动化部署SpringBoot应用

Windows下Jenkins自动化部署SpringBoot应用 1、下载安装包 下载地址&#xff1a; 一个是 msi 程序&#xff1a; https://mirrors.aliyun.com/jenkins/windows/ 一个是 war 程序&#xff1a; https://get.jenkins.io/war-stable/ https://mirrors.jenkins.io/war/ 这里我…

关于线性模型的底层逻辑解读 (机器学习 细读01)

一 多元线性回归 线性回归是机器学习中 有监督机器学习 下的一种算法。 回归问题主要关注的是因变量(需要预测的值&#xff0c;可以是一个也可以是多个)和一个或多个数值型的自变量(预测变量)之间的关系。 需要预测的值:即目标变量&#xff0c;target&#xff0c;y&#xff0c…

稀疏矩阵存储

实验内容 1、&#xff08;1&#xff09;题目要求&#xff1a;如图所示&#xff0c;任意输入一个稀疏矩阵M&#xff0c;用三元组顺序表压缩存储该稀疏矩阵M&#xff0c;然后求其转置矩阵T&#xff0c;并输出转置矩阵T。 三元组的表示和初始化&#xff0c;用线性表 typedef st…

七彩童年有“米小圈”陪伴!

长期以来&#xff0c;我对孩子看的电视和动画片都很谨慎&#xff0c;怕有不好的内容会对孩子产生误导&#xff0c;不利于小孩子健康成长。令我没想到的是在这个假期里&#xff0c;“米小圈”的出现&#xff0c;让我对动画片的看法有了很大的改变&#xff0c;也让我对孩子观看动…

关爱通分享丨三大步九小步—重构管理价值链,驱动福利进阶

企业人才素质不断提升&#xff0c;对生活品质和精神层面的追求越来越高&#xff0c;也倒推企业不断改善管理、健全福利制度&#xff0c;激发员工的积极性和创造力。企业成本激增&#xff0c;但预期价值未能完全实现&#xff0c;为此&#xff0c;笔者在价值驱动管理理念的基础上…