«

Python批量巡检(Linux)demo

发布于 阅读:132 教程


import time
import paramiko
import sys
import os

def xunjian_ssh(ip,password,username,root_pwd,port='22'):
    # 建立一个sshclient对象
    ssh = paramiko.SSHClient()
    # 允许将信任的主机自动加入到host_allow 列表,此方法必须放在connect方法的前面
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)

    try:
        # 调用connect方法连接服务器
        ssh.connect(hostname=ip,username=username,password=password,port=port)
        channel = ssh.invoke_shell()
        print('--'*25 + '巡检系统' + '--'*25)
        if ip == '192.168.1.2':
            print("当前巡检服务器 %s" %ip)
            stdin,stdout,stderr = ssh.exec_command("systemctl status docker")
            print(stdout.read().decode("utf-8"))
            stdin, stdout, stderr = ssh.exec_command("systemctl status sshd")
            print(stdout.read().decode("utf-8"))
            # 查看内存情况
            stdin, stdout, stderr = ssh.exec_command("free -mh")
            print(stdout.read().decode("utf-8"))
            # 查看cpu使用率(取五次平均值)
            stdin, stdout, stderr = ssh.exec_command("vmstat 1 5|sed  '1d'|sed  '1d'|awk '{print $15}'")
            cpu = stdout.readlines()
            cpu_usage = str(
                round((100 - (int(cpu[0]) + int(cpu[1]) + int(cpu[2]) + int(cpu[3]) + int(cpu[4])) / 5), 2)) + '%'
            print("当前服务器CPU使用率为:" + cpu_usage)
            channel.send('su - root \n')
            time.sleep(0.1)
            channel.send(root_pwd+"\n")
            time.sleep(0.1)
            channel.send("whoami\n")
            time.sleep(0.1)
            buff = ''
            while not buff.endswith("# "):
               resp = channel.recv(9999)
               buff += resp.decode("utf-8")
            print(buff+"\n")
        if ip == '192.168.1.3':
            print("当前巡检服务器 %s" %ip)
            stdin,stdout,stderr = ssh.exec_command("systemctl status docker")
            print(stdout.read().decode("utf-8"))
            stdin, stdout, stderr = ssh.exec_command("systemctl status sshd")
            print(stdout.read().decode("utf-8"))

            # 查看内存情况
            stdin, stdout, stderr = ssh.exec_command("free -mh")
            print(stdout.read().decode("utf-8"))
            # 查看cpu使用率(取五次平均值)
            stdin, stdout, stderr = ssh.exec_command("vmstat 1 5|sed  '1d'|sed  '1d'|awk '{print $15}'")
            cpu = stdout.readlines()
            cpu_usage = str(
                round((100 - (int(cpu[0]) + int(cpu[1]) + int(cpu[2]) + int(cpu[3]) + int(cpu[4])) / 5), 2)) + '%'
            print("当前服务器CPU使用率为:" + cpu_usage)
            channel.send('su - root \n')
            time.sleep(0.1)
            channel.send(root_pwd+"\n")
            time.sleep(0.1)
            channel.send("whoami\n")
            time.sleep(0.1)
            buff = ''
            while not buff.endswith("# "):
               resp = channel.recv(9999)
               buff += resp.decode("utf-8")
            print(buff+"\n")

            # 关闭ssh连接
            ssh.close()
            # 执行完不关闭窗口
            #os.system("pause")
    except Exception as e:
        print('服务器%s连接失败' % ip)
        print(e)
        sys.exit()

if __name__ == '__main__':
    # 定义一个字典,写服务器信息
    servers = {
        # 以服务器IP为键,值为服务器的用户密码端口定义的字典
        "192.168.1.2": {
            "username": "root",
            "password": "123456",
            "root_pwd": "123456"
        },
        "192.168.1.3": {
            "username": "root",
            "password": "123456",
            "root_pwd": "123456"
        }
    }
    for ip, info in servers.items():
        # 这里的info也就是上边定义的ip对应值的字典,使用get获取这个字典里对应username键对应的值,赋值给变量username传给函数中使用
        xunjian_ssh(
            ip=ip,
            username=info.get("username"),
            password=info.get("password"),
            root_pwd=info.get("root_pwd")
        )

Python Linux