python远程监控linux进程

1、效果图

 

 

2、配置文件

 

 

3、源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import paramiko
import io
import colorama
 
def process(cfg):
    # 创建SSH客户端
    ssh = paramiko.SSHClient()
    # 自动接受新的主机密钥
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # 连接到远程Linux服务器
    ssh.connect(hostname=cfg['hostname'], username=cfg['username'], password=cfg['password'])
    # 执行Linux命令,获取进程状态信息
    process_list=cfg['process']
    str_disc=''
    for i in process_list:
        str_disc = str_disc + i.replace('[', '').replace(']', '')  # 去除[]符号
    if ',' in str_disc:  # 以逗号为分隔符
        arr = str_disc.split(',')
        #print("arr is", arr)
 
    for i in arr:
        stdin, stdout, stderr = ssh.exec_command(f'ps aux | grep {i}')
        result = stdout.readlines()
        if i=='进程名':
            if len(result) > 10:
                print(f"\033[0;32m  {i}  is running\033[0m")
            else:
                print(f"\033[0;31m  {i}  is stop\033[0m")
        else:
            if len(result) > 1:
                print(f"\033[0;32m  {i}  is running\033[0m")
            else:
                print(f"\033[0;31m  {i}  is stop\033[0m")
 
        print(f"\033[0;36m  {i} process info:\033[0m")
        for j in result:
            j=str(j).replace('\n','')
            print("  ",j)
        print("***************************************")
    # 关闭SSH连接
    ssh.close()
def load_config():# 读取配置文件
    pathfile = 'conf.txt' # 文件存放位置,自行修改
    f = io.open(str(pathfile), "r")
    data = str(f.read())
    f.close()
    dict = {}
    str_data = ''
    for i in data:
        str_data = str_data + i.strip('\n'# 去除换行符
        if ';' in str_data:  # 分号表示得到一个完整的数据,以这个数据为一个完整的整体进行切割
            str_data = str_data[:-1# 去除分号
            arr = str_data.split('=='# 以==为分隔符切割数据
            dict[arr[0]] = arr[1# 按字典存储
            str_data = ''  # 重置变量用于下一个数据的切割
    #print(dict)
    return dict
if __name__ == '__main__':
    colorama.init(autoreset=True)
    while True:
        cfg = load_config()  # 读取配置文件
        process(cfg)  # 执行监控
        end_flag = input("enter any key to continue:\n")

  

posted @   小白成长记-yan  阅读(160)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示