Python运维脚本

#!/usr/bin/env python
# ueage: python tomcat.py start|stop|restart"
import paramiko
import threading
import sys


def ssh2(ip, username, passwd, cmd):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip, 22, username, passwd, timeout=5)
        for m in cmd:
            stdin, stdout, stderr = ssh.exec_command(m)
            out = stdout.readlines()
            for o in out:
                print o,
            print '###%s has done\n' % (ip)
        ssh.close()
    except:
        print '%s\tError\n' % (ip)


def usage():
    print "ueage: python tomcat.py start|stop|restart|diskcheck|tomcatcheck|rmolddir"
    sys.exit(1)


if __name__ == '__main__':
    argc = len(sys.argv)
    if argc < 2:
        usage()
    else:
        for i in sys.argv[1:]:
            if i == 'status':
                cmd = ['/nfs/tomcat/tomcat.sh status && ls -l /opt/tomcat/webapps/']
            elif i == 'start':
                cmd = ['/nfs/tomcat/tomcat.sh start']
            elif i == 'stop':
                cmd = ['/nfs/tomcat/tomcat.sh stop']
            elif i == 'restart':
                cmd = ['/nfs/tomcat/tomcat.sh restart']
            elif i == 'diskcheck':
                cmd = ['df -h']
            elif i == 'tomcatcheck':
                cmd = ['/nfs/tomcat/tomcat.sh tomcatcheck']
            elif i == 'rmolddir':
                cmd = ['cd /opt/tomcat/webapps/; rm -rf admin trade admin']
            elif i == 'rmtrade':
                cmd = ['cd /opt/tomcat/webapps/; rm -rf trade']
            else:
                usage()

        username = "tomcat"
        passwd = "tomcat"
        print "Begin......"
        for i in range(1, 5):
            ip = 'tomcat' + str(i)
            run = threading.Thread(target=ssh2, args=(ip, username, passwd, cmd))
            run.start()

Python资料: 

http://www.cnblogs.com/gannan/archive/2012/02/06/2339883.html

http://letong.me/category/python

猜你喜欢

转载自singhoo.iteye.com/blog/2254732