Technology Sharing

  • 首页
  • 资料分享
  • 在线工具
    • 随机密码生成器
  • 介绍
  • RSS
  • privacy
  • 云产品推广
    • 腾讯云
    • 阿里云
Share IT knowledge
  1. 首页
  2. linux
  3. 正文

Python-服务器&交换机自动化巡检

2022年9月16日 216点热度 0人点赞 0条评论

功能

远程登录多台linux服务器或交换机执行相应命令输出到txt文本。其中服务器ip列表(ip_file.txt)自定义,巡检命令列表(cmd_file.txt)自定义。
注意:交换机必须设置look_for_keys(bool类型),设置为False时用来禁用在~/.ssh中搜索私钥文件

环境准备

  • linux系统
  • python3环境
  • python3模块paramiko
脚本内容

#vim check.py

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

import re
import paramiko
import time
import datetime


def sshexeccmd(ip):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname=ip.strip(), port=22, username='用户名', password='密码', look_for_keys=False)
        print("You have successfully connect to ", ip)

        command = ssh.invoke_shell()
        cmdlist = open(r"./cmd_file.txt", 'r')

        cmdlist.seek(0)
        for line in cmdlist.readlines():
            if len(line.strip()) == 0:
                continue
            command.send(line.strip())
            command.send("\n")
        time.sleep(3)
        cmdlist.close()
        output = command.recv(65535)
        t = datetime.datetime.now()
        # 对现在时间格式化,以此作为文件名
        cur_time = t.strftime('%Y-%m-%d_%H-%M-%S')

        save_file = open(ip.strip() + '_' + cur_time + '.txt', "wb")
        save_file.seek(0)
        save_file.write(output)
        save_file.close()
        ssh.close()
        change_file = open(ip.strip() + '_' + cur_time + '.txt', "r")
        alllines = change_file.readlines()
        change_file.close()
        change_file = open(ip.strip() + '_' + cur_time + '.txt', "w+")
        for eachline in alllines:
            a = re.sub(r"\[\?2004h", '', eachline)
            a = re.sub(r"\[\?2004l", '', a)
            change_file.writelines(a)
        change_file.close()

    except Exception as e:
        print(e)


def main():
    iplist = open(r"./ip_file.txt", 'r')
    for line in iplist.readlines():
        if len(line.strip()) == 0 :
            continue
        sshexeccmd(line)

main()

备注:username='用户名', password='密码' 记得修改

ip列表

#vim ip_file.txt

192.168.1.1
192.168.1.2
巡检命令列表

#vim cmd_file.txt

ifconfig
hostname
执行脚本

条件:ip列表文件和巡检命令列表文件与python脚本文件要在同级目录下

#python3 check.py

结果

脚本执行完成之后会生成对应的结果文件

192.168.1.1_2022-09-16_09-09-56.txt
192.168.1.2_2022-09-16_09-09-57.txt

打赏微海报分享
标签: 暂无
最后更新:2022年9月16日

nico

Linux运维工程师 软考网络工程师 && 软考信息安全工程师

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

nico

Linux运维工程师
软考网络工程师 && 软考信息安全工程师

最新 热点 随机
最新 热点 随机
linux部署JDK环境 [Solved] MariaDB import issue: Error at line 1: Unknown command '\-'. Could not retrieve mirrorlist http://mirrorlist.centos.org/ CentOS 7 Kubernetes如何删除卡在“Terminating”状态的命名空间 解决GitLab Runner签名无效 如何禁用 Ubuntu "Daemons using outdated libraries" 弹出窗口
安装指定版本的 Node.js、npm、cnpm 免费申请HTTPS通配符证书,保障网站安全 [SOLVED]nginx: upstream sent too big header while reading response header from upstream Bpytop:一款优于Linux `top`的资源监视器 Python操作Excel (xlwings模块) 把ChatGPT部署到自己的网站
最近评论
woodcockkienzlelsj8o9+73s48g9rr3m0@gmail.com 发布于 10 个月前(07月17日) necessitatibus corporis et odit nam quo harum et c...
RonaldG 发布于 10 个月前(07月07日) Very interesting topic, thank you for putting up.&...
小黑 发布于 1 年前(12月28日) 不错
nico 发布于 2 年前(02月09日) 嘻嘻嘻!!!
Bruse 发布于 2 年前(02月09日) 我来啦!!!
nico 发布于 2 年前(12月10日) 方便查询
Justin 发布于 2 年前(12月10日) 写的很好,谢谢分享!我 Mark 一下~
nico 发布于 3 年前(11月18日) 主题的原因吧
Justin 发布于 3 年前(09月22日) 这篇文章的质量很高呀!写得很详细~ 话说你的文章是隐藏了发布时间吗?
Justin 发布于 3 年前(08月27日) 好家伙,这标题乍一看还以为你打算进军英文技术写作领域了🤓

COPYRIGHT © 2023 Technology Sharing. ALL RIGHTS RESERVED.

备案图标 皖公网安备34132402000202 皖ICP备2023004851号-1