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
```
相关文章:

Python运维学习Day02-subprocess/threading/psutil
文章目录 1. 检测网段在线主机2. 获取系统变量的模块 psutil 1. 检测网段在线主机 import subprocessdef checkIP(ip):cmd fping -n 1 -w 1 {ip}null open(nlll,modewb)status subprocess.call(cmd,shellTrue,stdoutnull,stderrnull)if status 0:print(f"主机[{ip}]在…...

开源库存管理系统InvenTree的安装
本文是应网友 shijie880500 要求折腾的; 什么是 InvenTree ? InvenTree 是一个开源的库存管理系统,提供强大的低级别库存控制和零件跟踪。InvenTree 系统的核心是 Python/Django 数据库后端,它提供了一个管理界面(基于…...

[双指针] (二) LeetCode 202.快乐数 和 11.盛最多水的容器
[双指针] (二) LeetCode 202.快乐数 和 11.盛最多水的容器 快乐数 202. 快乐数 题目解析 (1) 判断一个数是不是快乐数 (2) 快乐数的定义:将整数替换为每个位上的和;如果最终结果为1,就是快乐数 (3) 这个数可能变为1,也可能无…...
前端、HTTP协议(重点)
什么是前端 前端是所有跟用户直接打交道的都可以称之为是前端 比如:PC页面、手机页面、平板页面、汽车显示屏、大屏幕展示出来的都是前端内容 能够用肉眼看到的都是前端 为什么要学前端 学了前端以后我们就可以做全栈工程师(会后端、会前端、会DB、会运维等) 咱…...

软件开发项目文档系列之六概要设计:构建可靠系统的蓝图
概要设计是软件开发项目中至关重要的阶段,它为整个系统提供了设计蓝图和技术方向。它的重要性在于明确项目目标、规划系统结构、确定技术选择、识别风险、以及为团队提供共同的视角,确保项目在后续开发阶段按计划进行。概要设计的主要内容包括项目的背景…...

[C++]命名空间等——喵喵要吃C嘎嘎
希望你开心,希望你健康,希望你幸福,希望你点赞! 最后的最后,关注喵,关注喵,关注喵,大大会看到更多有趣的博客哦!!! 喵喵喵,你对我真的…...
安装ora2pg遇到如下问题
通过源码安装ora2pg成功后,查询帮助信息报错 [rootlocalhost bin]# ora2pg --help Cant locate open.pm in INC (you may need to install the open module) (INC contains: /usr/local/lib64/perl5 /usr/local/share/perl5 /usr/lib64/perl5/vendor_perl /usr/shar…...

x86-32-Linux下栈溢出攻击原理
在x86-32-Linux下构造一个栈溢出攻击 栈缓冲区溢出攻击:向栈上的数组写入超过数组长度的数据导致覆盖到正常数据{栈帧上的返回地址}。 IA-32下C函数调用约定: 调用者将参数从右向左入栈,构造参数call 指令短跳转,会将call指令下一…...

GPS学习(一):在ROS2中将GPS经纬度数据转换为机器人ENU坐标系,在RVIZ中显示坐标轨迹
文章目录 一、GPS模块介绍二、坐标转换转换原理参数解释: 增加回调函数效果演示 本文记录在Ubuntu22.04-Humbel中使用NMEA协议GPS模块的过程,使用国产ROS开发板鲁班猫(LubanCat )进行调试。 一、GPS模块介绍 在淘宝找了款性价比较高的轮趣科技GPS北斗双…...

chatgpt生成文本的底层工作原理是什么?
文章目录 🌟 ChatGPT生成文本的底层工作原理🍊 一、数据预处理🍊 二、模型结构🍊 三、模型训练🍊 四、文本生成🍊 总结 📕我是廖志伟,一名Java开发工程师、Java领域优质创作者、CSDN…...

javaEE -11(10000字HTML入门级教程)
一: HTML HTML 代码是由 “标签” 构成的. 例如: <body>hello</body>标签名 (body) 放到 < > 中大部分标签成对出现. 为开始标签, 为结束标签.少数标签只有开始标签, 称为 “单标签”.开始标签和结束标签之间, 写的是标签的内容. (h…...
LeetCode75——Day21
文章目录 一、题目二、题解 一、题目 1207. Unique Number of Occurrences Given an array of integers arr, return true if the number of occurrences of each value in the array is unique or false otherwise. Example 1: Input: arr [1,2,2,1,1,3] Output: true Ex…...

学习笔记---更进一步的双向链表专题~~
目录 1. 双向链表的结构🦊 2. 实现双向链表🐝 2.1 要实现的目标🎯 2.2 创建初始化🦋 2.2.1 List.h 2.2.2 List.c 2.2.3 test.c 2.2.4 代码测试运行 2.3 尾插打印头插🪼 思路分析 2.3.1 List.h 2.3.2 List.…...
vscode格式化代码, 谷歌风格, 允许短if同行短块同行, tab = 4舒适风格
ctrl ,输入format, 点开C风格设置 在这块内容输入{ BasedOnStyle: Chromium, IndentWidth: 4, ColumnLimit: 200, AllowShortIfStatementsOnASingleLine: true, AllowShortLoopsOnASingleLine: true} C_Cpp: Clang_format_fallback Style 用作回退的预定义样式的名称&#x…...

百度富文本上传图片后样式崩塌
🔥博客主页: 破浪前进 🔖系列专栏: Vue、React、PHP ❤️感谢大家点赞👍收藏⭐评论✍️ 问题描述:上传图片后,图片会变得很大,当点击的时候更是会顶开整个的容器的高跟宽 原因&#…...
autoware.ai中检测模块lidar_detector caffe
lidar_apollo_cnn_seg_detect模块:该模块主要是调用百度apollo的目标分割。 1.需要安装caffe进行实现: caffe安装步骤: git clone https://github.com/BVLC/caffecd caffe && mdkir build && cd buildcmake ..出现报错: CM…...
CentOS安装Ruby环境
安装依赖项 sudo yum install -y perl zlib-devel openssl-devel安装git sudo yum install -y git git config --global http.sslVerify falsecurl取消ssl认证 echo "insecure" >> ~/.curlrc安装rbenv https://github.com/rbenv/rbenv git clone https://…...
力扣第509题 斐波那契数 新手动态规划(推荐参考) c++
题目 509. 斐波那契数 简单 相关标签 递归 记忆化搜索 数学 动态规划 斐波那契数 (通常用 F(n) 表示)形成的序列称为 斐波那契数列 。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是: F(0) 0&a…...

canvas绘制签名并保存
实现签名的三个关键方法: 1.mousedown:当鼠标按下时开始绘制签名。 2.mousemove:鼠标移动时持续绘制。 3.mouseup:鼠标抬起时结束绘制。 html: <div class"setSign"><canvasref"canvas&q…...

Android渲染流程
目录 缓冲区的不同生命周期代表当前缓冲区的状态: 多个源 ViewRootImpl: Android4.0: Android5.0: Android应用程序调用SurfaceFliger将测量,布局,绘制好的Surface借助GPU渲染显示到屏幕上。 一个Acti…...
零门槛NAS搭建:WinNAS如何让普通电脑秒变私有云?
一、核心优势:专为Windows用户设计的极简NAS WinNAS由深圳耘想存储科技开发,是一款收费低廉但功能全面的Windows NAS工具,主打“无学习成本部署” 。与其他NAS软件相比,其优势在于: 无需硬件改造:将任意W…...

基于FPGA的PID算法学习———实现PID比例控制算法
基于FPGA的PID算法学习 前言一、PID算法分析二、PID仿真分析1. PID代码2.PI代码3.P代码4.顶层5.测试文件6.仿真波形 总结 前言 学习内容:参考网站: PID算法控制 PID即:Proportional(比例)、Integral(积分&…...

3.3.1_1 检错编码(奇偶校验码)
从这节课开始,我们会探讨数据链路层的差错控制功能,差错控制功能的主要目标是要发现并且解决一个帧内部的位错误,我们需要使用特殊的编码技术去发现帧内部的位错误,当我们发现位错误之后,通常来说有两种解决方案。第一…...

Swift 协议扩展精进之路:解决 CoreData 托管实体子类的类型不匹配问题(下)
概述 在 Swift 开发语言中,各位秃头小码农们可以充分利用语法本身所带来的便利去劈荆斩棘。我们还可以恣意利用泛型、协议关联类型和协议扩展来进一步简化和优化我们复杂的代码需求。 不过,在涉及到多个子类派生于基类进行多态模拟的场景下,…...
【位运算】消失的两个数字(hard)
消失的两个数字(hard) 题⽬描述:解法(位运算):Java 算法代码:更简便代码 题⽬链接:⾯试题 17.19. 消失的两个数字 题⽬描述: 给定⼀个数组,包含从 1 到 N 所有…...
基于Uniapp开发HarmonyOS 5.0旅游应用技术实践
一、技术选型背景 1.跨平台优势 Uniapp采用Vue.js框架,支持"一次开发,多端部署",可同步生成HarmonyOS、iOS、Android等多平台应用。 2.鸿蒙特性融合 HarmonyOS 5.0的分布式能力与原子化服务,为旅游应用带来…...

2025盘古石杯决赛【手机取证】
前言 第三届盘古石杯国际电子数据取证大赛决赛 最后一题没有解出来,实在找不到,希望有大佬教一下我。 还有就会议时间,我感觉不是图片时间,因为在电脑看到是其他时间用老会议系统开的会。 手机取证 1、分析鸿蒙手机检材&#x…...

AI书签管理工具开发全记录(十九):嵌入资源处理
1.前言 📝 在上一篇文章中,我们完成了书签的导入导出功能。本篇文章我们研究如何处理嵌入资源,方便后续将资源打包到一个可执行文件中。 2.embed介绍 🎯 Go 1.16 引入了革命性的 embed 包,彻底改变了静态资源管理的…...
2023赣州旅游投资集团
单选题 1.“不登高山,不知天之高也;不临深溪,不知地之厚也。”这句话说明_____。 A、人的意识具有创造性 B、人的认识是独立于实践之外的 C、实践在认识过程中具有决定作用 D、人的一切知识都是从直接经验中获得的 参考答案: C 本题解…...
Android第十三次面试总结(四大 组件基础)
Activity生命周期和四大启动模式详解 一、Activity 生命周期 Activity 的生命周期由一系列回调方法组成,用于管理其创建、可见性、焦点和销毁过程。以下是核心方法及其调用时机: onCreate() 调用时机:Activity 首次创建时调用。…...