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…...

UE5 学习系列(二)用户操作界面及介绍
这篇博客是 UE5 学习系列博客的第二篇,在第一篇的基础上展开这篇内容。博客参考的 B 站视频资料和第一篇的链接如下: 【Note】:如果你已经完成安装等操作,可以只执行第一篇博客中 2. 新建一个空白游戏项目 章节操作,重…...
Linux链表操作全解析
Linux C语言链表深度解析与实战技巧 一、链表基础概念与内核链表优势1.1 为什么使用链表?1.2 Linux 内核链表与用户态链表的区别 二、内核链表结构与宏解析常用宏/函数 三、内核链表的优点四、用户态链表示例五、双向循环链表在内核中的实现优势5.1 插入效率5.2 安全…...
Spring Boot 实现流式响应(兼容 2.7.x)
在实际开发中,我们可能会遇到一些流式数据处理的场景,比如接收来自上游接口的 Server-Sent Events(SSE) 或 流式 JSON 内容,并将其原样中转给前端页面或客户端。这种情况下,传统的 RestTemplate 缓存机制会…...

以下是对华为 HarmonyOS NETX 5属性动画(ArkTS)文档的结构化整理,通过层级标题、表格和代码块提升可读性:
一、属性动画概述NETX 作用:实现组件通用属性的渐变过渡效果,提升用户体验。支持属性:width、height、backgroundColor、opacity、scale、rotate、translate等。注意事项: 布局类属性(如宽高)变化时&#…...

通过Wrangler CLI在worker中创建数据库和表
官方使用文档:Getting started Cloudflare D1 docs 创建数据库 在命令行中执行完成之后,会在本地和远程创建数据库: npx wranglerlatest d1 create prod-d1-tutorial 在cf中就可以看到数据库: 现在,您的Cloudfla…...

ESP32读取DHT11温湿度数据
芯片:ESP32 环境:Arduino 一、安装DHT11传感器库 红框的库,别安装错了 二、代码 注意,DATA口要连接在D15上 #include "DHT.h" // 包含DHT库#define DHTPIN 15 // 定义DHT11数据引脚连接到ESP32的GPIO15 #define D…...
JVM垃圾回收机制全解析
Java虚拟机(JVM)中的垃圾收集器(Garbage Collector,简称GC)是用于自动管理内存的机制。它负责识别和清除不再被程序使用的对象,从而释放内存空间,避免内存泄漏和内存溢出等问题。垃圾收集器在Ja…...

如何将联系人从 iPhone 转移到 Android
从 iPhone 换到 Android 手机时,你可能需要保留重要的数据,例如通讯录。好在,将通讯录从 iPhone 转移到 Android 手机非常简单,你可以从本文中学习 6 种可靠的方法,确保随时保持连接,不错过任何信息。 第 1…...
leetcodeSQL解题:3564. 季节性销售分析
leetcodeSQL解题:3564. 季节性销售分析 题目: 表:sales ---------------------- | Column Name | Type | ---------------------- | sale_id | int | | product_id | int | | sale_date | date | | quantity | int | | price | decimal | -…...

算法笔记2
1.字符串拼接最好用StringBuilder,不用String 2.创建List<>类型的数组并创建内存 List arr[] new ArrayList[26]; Arrays.setAll(arr, i -> new ArrayList<>()); 3.去掉首尾空格...