Python 是一种功能强大且易于学习的编程语言,它在运维工程师的日常工作中扮演着重要的角色。Python 的简洁性和丰富的库生态系统使其成为编写自动化脚本和工具的理想选择。下面是一些运维工程师在日常工作中经常使用的 Python 脚本的概述。
Python 运维脚本整理归纳_python自动化运维常用脚本-CSDN博客
# 判断端口是否开放
import socket
port_number = [135,443,80]
for index in port_number:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('127.0.0.1', index))
if result == 0:
print("Port %d is open" % index)
else:
print("Port %d is not open" % index)
sock.close()
# 自动发现tcp
#!/usr/bin/python
import os
import json
data = {}
tcp_list = []
port_list = []
command = "netstat -tlnp | sed -n '3,$p' | awk '{print $4}' | awk -F':' '{print $NF}'"
lines = os.popen(command).readlines()
for line in lines:
port=line.strip('\n')
# port = line.split(':')[1]
port_list.append(port)
for port in list(set(port_list)):
port_dict = {}
port_dict['{#TCP_PORT}'] = port
tcp_list.append(port_dict)
data['data'] = tcp_list
jsonStr = json.dumps(data, sort_keys=True, indent=4)
print jsonStr
# 自动发现java
#!/usr/bin/env python
#encoding: utf8
import subprocess
try:
import json
except ImportError:
import simplejson as json
command = "netstat -tpln | grep -v '127.0.0.1' | awk -F '[ :]+' '/java/ && / / {print $5}'"
p = subprocess.Popen(command,shell=True,stdout=subprocess.PIPE)
port_list = p.stdout.read().split('\n')
port = []
for i in port_list:
if len(i) != 0:
port += [{'{#JAVA_PORT}':i}]
print json.dumps({'data':port},sort_keys=True,indent=4,separators=(',',':'))
# 进程号内存
"""
Author: deepinwst
Email: wanshitao@donews.com
Date: 19-4-17 上午10:44
"""
import psutil
import time
import json
KEY_LIST = [
"status", # 进程状态
"pid", # 进程号
"create_time", # 进程启动时间
"cpu_percent", # cpu占用率
"username", # 启动进程的用户
"num_threads", # 线程数量
"memory_percent", # 内存使用率
"cmdline", # 启动命令
"cpu_affinity" # 使用了哪些核
]
def common_monitor(key_lis):
"""记录当前所有进程的状态"""
pids = psutil.pids()
pids_lis = []
for pid in pids:
if psutil.pid_exists(pid):
pid_obj = psutil.Process(pid)
dic = pid_obj.as_dict(attrs=key_lis)
dic['cpu_affinity'] = str(dic['cpu_affinity'])
dic['cmdline'] = ' '.join(dic['cmdline'])
dic['create_time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(dic['create_time']))
pids_lis.append(dic)
return pids_lis
def one_process(pid, key_lis):
""" 记录某个进程的状态 """
pid_obj = psutil.Process(pid)
dic = pid_obj.as_dict(attrs=key_lis)
dic['cpu_affinity'] = str(dic['cpu_affinity'])
dic['cmdline'] = ' '.join(dic['cmdline'])
dic['create_time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(dic['create_time']))
return dic
if __name__ == "__main__":
## 查看所有进程
#res = common_monitor(KEY_LIST)
#print(json.dumps(res, indent=4))
# 请确保进程号存在
res = one_process(5487, KEY_LIST)
print(json.dumps(res, indent=4))