python异常+自动化运维
python异常#简单异常print(5/0)Traceback(most recent call last):FileC:\Users\孟宇\PyCharmMiscProject\异常\基础.py,line1,inmoduleprint(5/0~^~ZeroDivisionError:division by zero#中断输入print(input(一段话))一段话Traceback(most recent call last):FileC:\Users\孟宇\PyCharmMiscProject\异常\基础.py,line2,inmoduleprint(input(一段话))^^^^^^^^^^^^^^^Filefrozen codecs,line319,indecode KeyboardInterrupt#索引异常list_one[]print(list_one[0])Traceback(most recent call last):FileC:\Users\孟宇\PyCharmMiscProject\异常\基础.py,line4,inmoduleprint(list_one[0])~~~~~~~~^^^IndexError:listindex out ofrange#属性异常classCat:colorbluedefshout(self):print(miao)catCat()cat.sleep()Traceback(most recent call last):FileC:\Users\孟宇\PyCharmMiscProject\异常\基础.py,line10,inmodulecat.sleep()^^^^^^^^^AttributeError:Catobjecthas no attributesleep#异常捕获try exceptnum1int(input(请输入被除数))num2int(input(请输入除数))try:resultnum1/num2print(result)exceptZeroDivisionError:print(分母不能为0)请输入被除数10请输入除数0分母不能为0#多异常捕获try:num1int(input(请输入被除数))num2int(input(请输入除数))resultnum1/num2print(result)except(ZeroDivisionError,ValueError)aserror:print(分母不能为0且必须为数字,error)请输入被除数a 分母不能为0且必须为数字 invalid literalforint()withbase10:a#无论是否出现异常都执行try:num1int(input(请输入被除数))num2int(input(请输入除数))resultnum1/num2exceptExceptionaserror:print(分母不能为0且必须为数字,error)else:print(result)finally:print(程序结束)请输入被除数10请输入除数a 分母不能为0且必须为数字 invalid literalforint()withbase10:a程序结束#raise抛出异常raiseValueError Traceback(most recent call last):FileC:\Users\孟宇\PyCharmMiscProject\异常\抛出异常.py,line2,inmoduleraiseValueError ValueError#raise再次引发上次异常try:raiseValueError(值类型错误)exceptValueErrorase:print(e)raise值类型错误 Traceback(most recent call last):FileC:\Users\孟宇\PyCharmMiscProject\异常\抛出异常.py,line2,inmoduleraiseValueError(值类型错误)ValueError:值类型错误#assert断言语句num1int(input(请输入被除数))num2int(input(请输入除数))assertnum2!0,分母不为零resultnum1/num2print(result)请输入被除数10请输入除数0Traceback(most recent call last):FileC:\Users\孟宇\PyCharmMiscProject\异常\抛出异常.py,line8,inmoduleassertnum2!0,分母不为零^^^^^^^AssertionError:分母不为零#异常传递definner():print(内层函数抛出)raiseValueError(值类型错误)defouter():print(外层函数抛出)inner()try:outer()exceptValueErrorase:print(e)外层函数抛出 内层函数抛出 值类型错误#自定义异常classShortPwd(Exception):def__init__(self,length,pwd_leng):self.lengthlength self.pwd_lengpwd_lengtry:textinput(请输入密码)iflen(text)3:raiseShortPwd(3,len(text))exceptShortPwdase:print(f你输入地密码长度是{e.pwd_leng},至少不能低于{e.length})请输入密码12你输入地密码长度是2,至少不能低于3自动化运维安装paramikpyuminstall-yopenssl-devel bzip2-devel expat-devel gdbm-devel readline-devel sqlite-devel libffi-devel gcc gcc-ctarzxvf Python-3.13.2.tgzcdPython-3.13.2/ ./configure--prefix/usr/local/python3makemakeinstallln-s/usr/local/python3/bin/python3 /usr/bin/python3ln-s/usr/local/python3/bin/pip3 /usr/bin/pip python3--version设置阿里云为默认镜像源bashpip config set global.index-url https://mirrors.aliyun.com/pypi/simple/添加受信任主机必需bashpip config set global.trusted-host mirrors.aliyun.com安装paramiko模块[rootxhde Python-3.14.215:18:10]# pip install paramikoLookinginindexes: https://mirrors.aliyun.com/pypi/simple/ Collecting paramiko Downloading https://mirrors.aliyun.com/pypi/packages/82/5b/eadf6d45de38d30ab603f49393b6cd2cbe7e233af8cf90197e32782b68a9/paramiko-5.0.0-py3-none-any.whl(208kB)Collecting bcrypt3.2(from paramiko)Downloading https://mirrors.aliyun.com/pypi/packages/24/b4/11f8a31d8b67cca3371e046db49baa7c0594d71eb40ac8121e2fc0888db0/bcrypt-5.0.0-cp39-abi3-manylinux_2_28_x86_64.whl(278kB)Collecting cryptography3.3(from paramiko)Downloading https://mirrors.aliyun.com/pypi/packages/20/2c/0622f20ff02b2ef32558733443805dc82fd4c275be01b2d19d14676f3a1b/cryptography-49.0.0-cp311-abi3-manylinux_2_28_x86_64.whl(4.7MB)━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━4.7/4.7 MB32.7kB/s0:02:33 Collecting invoke2.0(from paramiko)Downloading https://mirrors.aliyun.com/pypi/packages/5a/de/bbc12563bbf979618d17625a4e753ff7a078523e28d870d3626daa97261a/invoke-3.0.3-py3-none-any.whl(160kB)Collecting pynacl1.5(from paramiko)Downloading https://mirrors.aliyun.com/pypi/packages/3e/d0/f301f83ac8dbe53442c5a43f6a39016f94f754d7a9815a875b65e218a307/pynacl-1.6.2-cp38-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl(1.4MB)━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━1.4/1.4 MB32.1kB/s0:00:44 Collecting cffi2.0.0(from cryptography3.3-paramiko)Downloading https://mirrors.aliyun.com/pypi/packages/cc/d7/97d3136f81db489ec8d1d67748c110d6c994268fd7528014aa9f2b085e4e/cffi-2.1.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl(221kB)Collecting pycparser(from cffi2.0.0-cryptography3.3-paramiko)Downloading https://mirrors.aliyun.com/pypi/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl(48kB)Installing collected packages: pycparser, invoke, bcrypt, cffi, pynacl, cryptography, paramiko Successfully installed bcrypt-5.0.0 cffi-2.1.0 cryptography-49.0.0 invoke-3.0.3 paramiko-5.0.0 pycparser-3.0 pynacl-1.6.2 WARNING: Running pip as therootuser can resultinbroken permissions and conflicting behaviour with the system package manager, possibly rendering your system unusable. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv. Use the --root-user-action optionifyou know what you are doing and want to suppress this warning.[notice]A new release of pip is available:25.3-26.1.2[notice]To update, run: /usr/local/python3/bin/python3.14-mpipinstall--upgradepip查看CPU信息importpsutilasps cpu_infops.cpu_times(percpuTrue)foriincpu_info:print(i)scputimes(user2528.140625,system2129.4062499999964,idle19893.796875,interrupt617.078125,dpc451.3125)scputimes(user1980.53125,system893.609375,idle21676.999999999996,interrupt90.6875,dpc52.515625)scputimes(user2109.5,system2669.2343749999964,idle19772.40625,interrupt407.15625,dpc1042.828125)scputimes(user2632.8125,system1199.1874999999964,idle20719.140625,interrupt82.484375,dpc21.8125)scputimes(user2239.96875,system1040.1874999999964,idle21270.984375,interrupt61.65625,dpc20.03125)scputimes(user1786.859375,system911.1406250000036,idle21853.156249999996,interrupt58.03125,dpc21.171875)scputimes(user2262.390625,system1038.3281249999964,idle21250.4375,interrupt62.15625,dpc19.78125)scputimes(user2229.796875,system1029.6249999999964,idle21291.703125,interrupt59.828125,dpc15.96875)print(ps.cpu_times().user)print(ps.cpu_times().system)17838.14062510949.8125print(CPU核心数,ps.cpu_count())print(CPU物理核心数,ps.cpu_count(logicalFalse))CPU核心数8CPU物理核心数4查看内存信息memps.virtual_memory()print(mem)print(总大小,mem.total)print(空闲大小,mem.free)print(占用百分比,mem.percent,%)print(虚拟内存swap:,ps.swap_memory())总大小16934494208空闲大小2275581952占用百分比86.6%虚拟内存swap:sswap(total16734068736,used1930526720,free14803542016,percent11.5,sin0,sout0)查看磁盘信息disk_infops.disk_partitions()print(e盘信息,ps.disk_usage(g:\\))print(每个磁盘读写,ps.disk_io_counters(perdiskTrue))e盘信息 sdiskusage(total122402828288,used99089330176,free23313498112,percent81.0)每个磁盘读写{PhysicalDrive0:sdiskio(read_count648537,write_count444530,read_bytes35030433792,write_bytes18489394688,read_time1677,write_time862)}fork,vinps.disk_io_counters(perdiskTrue).items():print(k,v)PhysicalDrive0 sdiskio(read_count649855,write_count446011,read_bytes35064925696,write_bytes18515603968,read_time1678,write_time863)fork,vinps.disk_io_counters(perdiskTrue).items():print(v.read_count)650648查看网络信息fork,vinps.net_io_counters(pernicTrue).items():print(k,v)以太网2snetio(bytes_sent244448179,bytes_recv2856708712,packets_sent2050091,packets_recv2767843,errin0,errout0,dropin0,dropout0)VirtualBox Host-Only Network snetio(bytes_sent0,bytes_recv0,packets_sent0,packets_recv0,errin0,errout0,dropin0,dropout0)WLAN snetio(bytes_sent0,bytes_recv0,packets_sent0,packets_recv0,errin0,errout0,dropin0,dropout0)本地连接*1snetio(bytes_sent0,bytes_recv0,packets_sent0,packets_recv0,errin0,errout0,dropin0,dropout0)VMware Network Adapter VMnet1 snetio(bytes_sent687,bytes_recv0,packets_sent687,packets_recv0,errin0,errout0,dropin0,dropout0)VMware Network Adapter VMnet8 snetio(bytes_sent49795,bytes_recv15288,packets_sent49795,packets_recv15288,errin0,errout0,dropin0,dropout0)本地连接*2snetio(bytes_sent457514420,bytes_recv86543909,packets_sent722752,packets_recv655487,errin0,errout0,dropin0,dropout0)Loopback Pseudo-Interface1snetio(bytes_sent0,bytes_recv0,packets_sent0,packets_recv0,errin0,errout0,dropin0,dropout0)查看登录用户importdatetimeprint(用户登录时间,datetime.datetime.fromtimestamp(ps.users()[0].started).strftime(%Y-%m-%d %H:%M:%S))用户登录时间2026-07-1708:40:00