天天看点

批量执行脚本

  最近由于在研究saltstack和运维平台的搭建,很久没有写博客了,今天同事说现在三台缓存服务器总共有几个站点,每回都远程ssh上去清理有点麻烦,叫我能不能想想办法,刚好近段时间刚好学习批量,简单实现以下(要安装paramiko模块,这里不演示了,大家可以百度一下):

1、执行脚本:

#-*- coding: utf-8 -*-

#xiaoluo

#!/usr/bin/python 

import paramiko

import time,os,sys

import threading

status=[]

status_dic={}

def ssh2(ip,port,username,passwd,cmd):

    try:

        ssh = paramiko.SSHClient()

        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        ssh.connect(ip,port,username,passwd,timeout=5)

        stdin, stdout, stderr = ssh.exec_command(cmd)

        cmd_result = stdout.read(),stderr.read()

        for cmd in cmd_result:

                print cmd

        ssh.close()

    except :

        print '%s\tError\n'%(ip)

if __name__=='__main__':

    f=open("/clean_cache/ssh.txt")

    for lines in f.readlines():

        ip=lines.split()[0]

        username=lines.split()[1]

        passwd = lines.split()[2]

        port = int(lines.split()[3])

        print ip,username,passwd,port

        cmd = 'rm -rf /tmp/xiaoluo/*'

        threads = []

        print "Begin......"

        a=threading.Thread(target=ssh2,args=(ip,port,username,passwd,cmd))

        a.start()

实现很简单:调用paramiko模块。从ssh.txt这个文件下面去读取,使用的用户名密码,端口号。通过读写文件的方式去获取,然后就能多线程批量执行了。

ssh.txt:格式如下:

192.168.10.234   root    OPEsdNdsssl.SHI<+om123{    22

192.168.10.235   root    OPEN>?sdssSkee.com123{     22

192.168.10.236   root    OPE.,.23NIkee.com123{      22

到此就结束了,大家可以根据自己扩展,通过交互的方式,一执行脚本就叫选择删除的目录,然后用if判断哪个目录要删除就好。

或者批量执行命令返回结果可以方便我们平时的排错;cmd那里可以添加几个命令:

如:df -h ,free -m,uptime都是可以的。

本文转自 小罗ge11 51CTO博客,原文链接:http://blog.51cto.com/xiaoluoge/1609931,如需转载请自行联系原作者