Python monitor SSH Telnet SNMP command Material

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
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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章