您的位置:首页 > 编程语言 > Python开发

Python——远程管理脚本(二)

2014-06-12 11:17 344 查看
前言:Python初学者。脚本实现目的:
通过一台集中控制的服务器管理其他所有服务器。
主要功能有:批量多进程远程执行命令、上传文件、获取文件
服务器的相关信息(IP,username,port,auth_type,password)可以保存在数据库中,也可以写在一个文件中
类似功能的脚本已经存在并一直在使用,但是由于是shell写的,所以弊端就是速度慢,容错能力差。
脚本思路: 利用Python的multiprocessing模块(初步思路来源于Python入门老师Alex) 服务器的相关信息默认保存在数据库中,也可以通过-f参数指定一个文件来获取。
脚本内容:
#!/usr/bin/env python
# conding=UTF-8
#This script is use for multiprocessing host manage
#Create by eleven in 2014-06-01
#Last changed in 2014-06-11

import multiprocessing
import MySQLdb
import sys,os,time

script = 'paramiko_test.py'
mhost="192.168.100.211"
muser="user1"
mpasswd="123"
mdb="test"

#connect mysql and get host information
def con_mysql(mhost,muser,mpasswd,mdb):
try:
con = MySQLdb.connect(host=mhost,user=muser,passwd=mpasswd,db=mdb)
cur = con.cursor()
except MySQLdb.Error,err_msg:
print 'Mysql Error Msg:',err_msg
sys.exit()

try:
cur.execute('select * from host_list')
info = cur.fetchall()
return info
except MySQLdb.Error,err_msg:
print 'Mysql Error Msg:',err_msg
cur.close()
con.close()
sys.exit()

#get info
all_argv = sys.argv[1:]
if  '-f' in all_argv:
num=all_argv.index('-f')
hlist=all_argv[num+1]
if os.path.exists(hlist):
f=file(hlist)
info=[]
for line2 in f.readlines():
line2=line2.split()
info.append(line2)
f.close()
else:
print 'The %s is not exists !' %hlist
else:
info=con_mysql(mhost,muser,mpasswd,mdb)

#format host information
action = sys.argv[1]
exec_list=[]
for line in info:
line =  line[1:]
host = line[0]
user = line[1]
atype = line[3]
passwd = line[4]
if action == 'cmd':
command = sys.argv[2]
cmd = 'python %s cmd %s %s %s %s %s' %(script,host,user,atype,passwd,command)
elif action == 'get':
file1 = sys.argv[2]
file2 = sys.argv[3]+'_'+host
cmd = 'python %s get %s %s %s %s %s %s' %(script,host,user,atype,passwd,file1,file2)
elif action == 'put':
file1 = sys.argv[2]
file2 = sys.argv[3]
cmd = 'python %s put %s %s %s %s %s %s' %(script,host,user,atype,passwd,file1,file2)
exec_list.append(cmd)

def run_cmd(t):
os.system(t)

#multiprocessing defined
p=multiprocessing.Pool(processes=len(exec_list))
result=[]
for task in exec_list:
result.append(p.apply_async(run_cmd,(task,)))
p.close()

#get result
for answer in result:
answer.get(timeout=10)


说明:
此脚本需要和paramiko的脚本配合一起使用,已经在生产环境中验证过,使用无问题。并打算慢慢替换掉之前shell写的类似功能的脚本。
若有同样感兴趣的朋友,可以留言,到时再详细介绍一下用法,这里就不赘述了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息