Python monitor SSH Telnet SNMP command Material

丶灬走出姿态 提交于 2020-03-27 23:16:51

First, refer https://blog.csdn.net/yannanxiu/article/details/55045108
Scenario:
Windows -------- Monitor -------- > Linux
via paramiko SSH login with psutil to get informaiton

import paramiko
import os
import psutil
import json

##读取当前路径
base_dir=os.getcwd()
##读取在远程主机执行的脚本
cmd_filepath=base_dir+r"\pu.txt"
cmd_file=open(cmd_filepath,"r")
cmd=cmd_file.read()
##连接远程主机
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect("192.168.42.62", 22,'root','Abcd1234')
##执行命令
stdin, stdout, stderr = client.exec_command(cmd)
##读取信息
for line in stdout:
    data = json.loads(line)
    #print(type(data))
    print(data["available"])
##关闭连接
client.close()

前面提到的 pu.txt 内容为:

python <<EOF
import json
import psutil as pu
memInfo = {}
mem = pu.virtual_memory()
memInfo["total"] = mem.total
memInfo["available"] = mem.available
memInfo["percent"] = mem.percent
memInfo["used"] = mem.used
memInfo["free"] = mem.free
data = json.dumps(memInfo)
print(data)
EOF

Second, via https://blog.csdn.net/u014326004/article/details/80084032
https://blog.csdn.net/yannanxiu/article/details/55045108
net-snmp-python packet installation https://www.cnblogs.com/zuoshoushizi/p/8191944.html
Scenario:
Windows/Linux -------- Monitor -------- > Cisco/Switch/Windows/Linux
via paramiko SSH login with psutil to get informaiton

import os
import re
import time
import platform
import psutil
import datetime

def montiorsystem():
    # 获取cpu使用情况
    cpuper = psutil.cpu_percent()
    # 获取内存使用情况:系统内存大小,使用内存,有效内存,内存使用率
    mem = psutil.virtual_memory()
    # 内存使用率
    memper = mem.percent
    # 获取当前时间
    now = datetime.datetime.now()
    # 获取网络收信息
    netinfo = psutil.net_io_counters()
    ts = now.strftime('%Y-%m-%d %H:%M:%S')
    line = f'"time":{ts},"cpu":{cpuper}%, "mem":{memper}%, "bytessent"={netinfo.bytes_sent}, "bytesrecv"={netinfo.bytes_recv}\n'
    print(line)
    # with open('../logfile', 'a', encoding='utf-8') as fp:
    #     fp.write(line)
    # Timer(3, montiorsystem).start

if 'Windows' == platform.system():
    print("the system is windows")
    print(os.getcwd())
    print(os.path.dirname(__file__))
else:
    print('the system is not windows')

def snmpWalk(host, oid):
    result = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid).read().split('\n')[:-1]
    return result

# ------------------------------------------------------------
# 获取负载信息
# ------------------------------------------------------------
def getSystem(host):
    system = ':'.join(snmpWalk(host, 'system')[0].split(':')[3:]).strip()
    return system

# ------------------------------------------------------------
# 获取负载信息
# ------------------------------------------------------------
def getLoad(host, loid):
    """系统负载"""
    load_oids = '1.3.6.1.4.1.2021.10.1.3.' + str(loid)
    return snmpWalk(host, load_oids)[0].split(':')[3]

def getLoads(host):
    load1 = getLoad(host, 1)
    load10 = getLoad(host, 2)
    load15 = getLoad(host, 3)
    return load1, load10, load15
# ------------------------------------------------------------
# 获取网卡流量
# ------------------------------------------------------------
def getNetworkDevices(host):
    """获取网络设备信息"""
    device_mib = snmpWalk(host, 'RFC1213-MIB::ifDescr')
    device_list = []
    for item in device_mib:
        device_list.append(item.split(':')[3].strip())
    return device_list
def getNetworkData(host, oid):
    """获取网络流量"""
    data_mib = snmpWalk(host, oid)
    data = []
    for item in data_mib:
        byte = float(item.split(':')[3].strip())
        data.append(str(round(byte / 1024, 2)) + ' KB')
    return data
def getNetworkInfo(host):
    device_list = getNetworkDevices(host)
    # 流入流量
    inside = getNetworkData(host, 'IF-MIB::ifInOctets')
    # 流出流量
    outside = getNetworkData(host, 'IF-MIB::ifOutOctets')
    return device_list, inside, outside

def main():
    for host in hosts:
        print('=' * 10 + host + '=' * 10)
        start = time.time()
        print("系统信息")
        system = getSystem(host)
        print(system)

        print("系统负载")
        load1, load10, load15 = getLoads(host)
        print('load(5min): %s ,load(10min): %s ,load(15min): %s' % (load1, load10, load15))

        print("网卡流量")
        device_list, inside, outside = getNetworkInfo(host)
        for i, item in enumerate(device_list):
            print('%s : RX: %-15s   TX: %s ' % (device_list[i], inside[i], outside[i]))

        end = time.time()
        print('run time:', round(end - start, 2), 's')

if __name__ == '__main__':
    main()

放到交换机上:

import os
import re
import time
import platform
import psutil
import datetime

if 'Windows' == platform.system():
    print("the system is windows")
    print(os.getcwd())
    print(os.path.dirname(__file__))
else:
    print('the system is not windows')

def snmpWalk(host, oid):
    result = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid).read().split('\n')[:-1]
    return result

def main():
    print("please enter ip address:")
    host = raw_input()
    print("please enter string:")
    commuinty = raw_input()
    start = time.time()
    print('system info')
    DeviceList = getPortDevices(host, commuinty)
if __name__ == '__main__':
    main()

SSH Telnet Login Execute Commands:
https://blog.csdn.net/wintershang/article/details/89465166
via Telent way:

# -*- coding: utf-8 -*-
import ciscolib
def main():
    PASSWORD="wfweb2kd"
    USERNAME="root"
    ENABLE_PWD="c#andphp"
    for ip in open('sw2960.txt').readlines():
        ip = ip.strip()
        if USERNAME != "":
            switch = ciscolib.Device(ip, PASSWORD, USERNAME, ENABLE_PWD)
        else:
            switch = ciscolib.Device(ip, PASSWORD, enable_password=ENABLE_PWD)
         try:
            switch.connect()
            print("Logged into %s,Successful" % ip)
        except ciscolib.AuthenticationError as e:
            print("Couldn't connect to %s: %s" % (ip, e.value))
            continue
        except Exception as e:
            print("Couldn't connect to %s: %s" % (ip, str(e)))
            continue
         switch.enable(ENABLE_PWD)
        switch.cmd("clock set 18:42:30 22 Apr 2019")
        switch.cmd("conf t")
        switch.cmd("service password-encryption")
        switch.cmd("username admin secret admin123") #//这里只是测试,实际环境不要这样
        switch.cmd("line vty 0 4")
        switch.cmd("login local")
        switch.cmd("crypto key generate rsa") 
        switch.cmd("\n") 
        #//这里只是测试最好是一条一条测试好了再上批量,这里踩了一个坑。
        switch.cmd("end")
        switch.cmd("wri mem")
        switch.disconnect()

if __name__ == '__main__':
    main()

via SSH way:

import paramiko
import time
import getpass
import sys
import socket

username = raw_input("用户名:")
password = getpass.getpass("密码:")
ip_file = sys.argv[1]
cmd_file = sys.argv[2]
switch_with_authentication_issue = []
switch_not_reachable = []
f = open(ip_file,'r')
for line in f.readlines():
   try:
        ip = line.strip()
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_client.connect(hostname=ip,username=username,password=password,look_for_keys=False)
        print "你已经成功连接到: ", ip
        command = ssh_client.invoke_shell()
        cmdlist = open(cmd_file,'r')
        cmdlist.seek(0)
        for line in cmdlist.readlines():
                command.send(line + "\n")
        time.sleep(2)
        cmdlist.close()
        output = command.recv(65535)
        print output
   except paramiko.ssh_exception.AuthenticationException:
        print "用户认证失败的" + ip + "."
        switch_with_authentication_issue.append(ip)
   except socket.error:
        print ip + "不可达,请检查网络."
        switch_not_reachable.append(ip)
f.close()
ssh_client.close

print '\n 以下交换机认证失败:'
for i in switch_with_authentication_issue:
        print i
print '\n 以下交换机网络不可达:'
for i in switch_not_reachable:
        print i
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!