前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >py脚本 获取当前运行服务的相关信息

py脚本 获取当前运行服务的相关信息

原创
作者头像
陈不成i
修改2021-05-31 10:43:12
9420
修改2021-05-31 10:43:12
举报
文章被收录于专栏:ops技术分享

一.简介

最近在统计系统中都部署了什么服务,但服务器太多,在没有标准化之前进行整理,还是写脚本收集方便一些。

当然还是需要人工去判断整理表格,为后面标准化做准备。脚本是python2.7的,默认的centos系列都可以使用。

file
file

二.代码

  1. #!/usr/bin/python2.7
  2. #coding=utf-8
  3. #通过netstat -unltp命令收集监听端口,需要客户端安装net-tools
  4. #获取当前运行的服务相关信息、PID号、端口号、服务名称、目录位置
  5. import json, commands, string
  6. import socket, sys
  7. deny_port = ["123", "22"]
  8. def get_port():
  9. prostr = commands.getstatusoutput('netstat -unltp')
  10. prostr = str(prostr)
  11. prolist = prostr.split('\\n') #用两个\才行
  12. del prolist[0]
  13. del prolist[0]
  14. prolist = prolist[::-1]
  15. info_dict = {}
  16. for info in prolist:
  17. port_info = info.split()
  18. if len(port_info) >= 7:
  19. tmp_port = port_info[3].split(':')
  20. tmp_port = tmp_port.pop()
  21. tmp_info = port_info[6].split('/')
  22. tmp_pid = tmp_info[0]
  23. if tmp_port in deny_port:
  24. continue
  25. if tmp_pid in info_dict.keys():
  26. port_list = info_dict[tmp_pid]
  27. port_list.append(tmp_port)
  28. else:
  29. info_dict[tmp_pid] = [tmp_port]
  30. return info_dict
  31. #根据字典循环去查询名称
  32. def tmp_name(info_dict):
  33. inq_bin = "ps -aux"
  34. prostr = commands.getstatusoutput(inq_bin)
  35. prostr = str(prostr)
  36. prolist = prostr.split('\\n')
  37. del prolist[0]
  38. for i in prolist:
  39. ps_info = i.split()
  40. ps_pid = ps_info[2]
  41. ps_name = ps_info[11:]
  42. print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
  43. def get_name(info_dict):
  44. #获取ps
  45. inq_bin = "ps -aux"
  46. prostr = commands.getstatusoutput(inq_bin)
  47. prostr = str(prostr)
  48. prolist = prostr.split('\\n')
  49. del prolist[0]
  50. for k, v in info_dict.items():
  51. print("PID号: " + k)
  52. print("监听的端口: " + v)
  53. for i in prolist:
  54. ps_info = i.split()
  55. ps_pid = ps_info[1]
  56. if k == ps_pid:
  57. ps_name = ""
  58. for n in ps_info[10:]:
  59. ps_name = ps_name + " " + n
  60. print("运行用户: " + ps_info[0])
  61. print("服务名称: " + ps_name)
  62. exe_dir = "ls -l /proc/" + k + "/exe"
  63. exes = commands.getstatusoutput(exe_dir)
  64. exes = str(exes)
  65. exes_list = exes.split()
  66. cwd_dir = "ls -l /proc/" + k + "/cwd"
  67. cwds = commands.getstatusoutput(cwd_dir)
  68. cwds = str(cwds)
  69. cwds_list = cwds.split()
  70. print("目录位置: " + exes_list[11] + " 或者 " + cwds_list[11])
  71. print("+++++++++++++++++++++++++++++++++")
  72. info_dict = get_port()
  73. get_name(info_dict)

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一.简介
  • 二.代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档