[Python] 分享一段使用Python编写的远程巡检脚本。

说明:

1)下面这段Python脚本在 3.7.3版本的python环境下编写和测试通过;

2)paramiko需要安装依赖组件(如下图所示),具体安装方法可以在网上查询;

 3)将不同远程Linux主机的IP地址、端口、用户名和密码放在一个cfg配置文件中,在python脚本中对ssh.connect()进行for循环,如果脚本所在主机恶=和被巡检主机之间路由态度是通的,即可实现批量巡检。

#!/usr/bin/env python3.7.3
# -*- coding: utf-8 -*-

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='192.168.xxx.xxx', port=22, username='test', password='xxxxxx')

stdin, stdout, stderr = ssh.exec_command('cat /etc/hosts| grep `hostname`|awk \'{print $1}\'')
print('1. Host IP:', stdout.read().decode())

stdin, stdout, stderr = ssh.exec_command('cat /etc/redhat-release')
print('2. OS Version:', stdout.read().decode())

stdin, stdout, stderr = ssh.exec_command('uname -r')
print('3. Kernel Version:', stdout.read().decode())

stdin, stdout, stderr = ssh.exec_command('uptime| awk \'{print $2,$3,$4}\'')
print('4. HostRunTime:', stdout.read().decode())

stdin, stdout, stderr = ssh.exec_command('df -h| sort -rn -k 5n')
print('5. File System Usage:')
print(stdout.read().decode())

stdin, stdout, stderr = ssh.exec_command('cat /proc/meminfo| grep MemTotal| awk \'{print $2$3}\'')
print('6. MemTotal: ', stdout.read().decode())

stdin, stdout, stderr = ssh.exec_command('cat /proc/meminfo| grep MemFree| awk \'{print $2$3}\'')
print('7. MemFree: ', stdout.read().decode())

stdin,stdout,stderr=ssh.exec_command('vmstat 1 3|sed \'1d\'|sed \'1d\'|awk \'{print $15}\'')
cpu=stdout.readlines()
# get avg of three execute result of IDEL;
cpu_usage=str(round((100 - (int(cpu[0])+int(cpu[1])+int(cpu[2]))/3),2))+'%'
print('8. CPU Usage: ', cpu_usage)
print('')

stdin, stdout, stderr = ssh.exec_command('ps -ef| grep java| egrep \'tomcat|weblogic.Server\'| grep -v grep')
print('9. Java Process: ')
print(stdout.read().decode())

stdin, stdout, stderr = ssh.exec_command('for pid in `ps -ef| egrep \'tomcat|weblogic.Server\'| grep java| grep -v grep| awk \'{print $2}\'`; do echo "pid="$pid;/usr/jdk1.7.0_191/bin/jstat -gc $pid 1000 5; done')
print('10. Process GC Display: ')
print(stdout.read().decode())

stdin, stdout, stderr = ssh.exec_command('for pid in `ps -ef| egrep \'tomcat|weblogic.Server\'| grep java| grep -v grep| awk \'{print $2}\'`; do echo "pid="$pid", open files:" `lsof -p $pid| wc -l`; done')
print('11. Process Open-files: ')
print(stdout.read().decode())

stdin, stdout, stderr = ssh.exec_command('ulimit -n')
print('12. System Max Open-files: ', stdout.read().decode())

ssh.close()

猜你喜欢

转载自www.cnblogs.com/cnskylee/p/12973924.html