为减少现场运维的重复性工作、减轻现场运维工作的繁杂性,提升现场运维工作效率,为此实现批量操作功能。
#!/home/bomc/miniconda2/bin/python2.7
# -*- coding:utf-8 -*-
from paramiko import SSHClient, AutoAddPolicy
import os
import sys
import time
import datetime
sys.path.append("/home/bomc/chenjinyun/python")
import passwd
import cx_Oracle
reload(sys)
sys.setdefaultencoding('utf-8')
class data_process:
def __init__(self,data_user,word,data_name):
try:
self.password = passwd.crypto.decode(word)
self.db = cx_Oracle.connect(data_user,self.password,data_name)
except Exception as e:
print datetime.datetime.now(),"Failed to connect to the database--------"
def sql_insert(self,SQL,data):
'''insert'''
try:
curs = self.db.cursor()
#SQL = "INSERT INTO process_err_message(applytime,host,process,cprocess,application,condition,amount,amount_number,cpu,cpu_number,mem,mem_number,status) VALUES(:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,:12,:13)"
curs.executemany(SQL,data)
self.db.commit()
curs.close()
except Exception, e:
print (e)
def sql_update_delete(self,sql):
'''update,delete'''
try:
curs = self.db.cursor()
# SQL = "INSERT INTO task_process_err(applytime,user_id,status,WORKING_DIR,EXE_NAME,ARGS,stdout_file,proc_no,NAME,ip_addr,proc_id) VALUES(:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11)"
curs.execute(sql)
self.db.commit()
curs.close()
except Exception, e:
print (e)
def sql_select(self,sql1):
'''
select
'''
try:
#sql1="select t.process, t.application, t.path, t.patch, t.keyword, t.host from process_yy t where t.status = 1 and t.patch in ('START', 'STOP') and t.node = '%s' " % host
curs = self.db.cursor()
result = curs.execute(sql1)
rows = curs.fetchall()
except Exception as e:
return []
else:
curs.close()
return rows
def close(self):
self.db.close()
print datetime.datetime.now(),"Successfully disconnect the database-------------"
class AutoTask:
def __init__(self, ip, port, username, password,rusername,rpasword,cmd):
self.ip = ip
self.port = int(port)
self.username = username
self.pasword = password
self.rusername = rusername
self.rpasword = rpasword
self.cmd = cmd
self.client = SSHClient()
self.client.set_missing_host_key_policy(AutoAddPolicy())
def root_sshclient(self):
try:
self.client.connect(self.ip, port=self.port, username=self.username, password=self.pasword,timeout=5)
self.cmd = self.cmd.replace('"','\\"')
command = 'echo \'{}\' | su -l -c "{}" "{}"'.format(self.rpasword,self.cmd.replace('\n',';'),self.rusername)
#print command
stdin,stdout,stderr=self.client.exec_command(command)
result = stdout.read().split('\n')
#print result
result.insert(0,'host'+' '+self.ip)
except Exception as e:
print "ERR:unable to connect%s %s\n"%(self.ip,e)
return []
else:
self.client.close()
return result
def user_sshclient(self):
try:
self.client.connect(self.ip, port=self.port, username=self.username, password=self.pasword,timeout=5)
stdin,stdout,stderr=self.client.exec_command(self.cmd)
result = stdout.read().split('\n')
result.insert(0,'host'+' '+self.ip)
except Exception as e:
print "ERR:unable to connect%s %s\n"%(self.ip,e)
return []
else:
self.client.close()
return result
def create_sshclient(self):
try:
self.client.connect(self.ip, port=self.port, username=self.username, password=self.pasword,timeout=5)
chan=self.client.invoke_shell()
time.sleep(0.1)
chan.send("export LANG=us.en \n")
chan.send("su - "+self.rusername+"\n")
buff = ''
while not buff.endswith(('Password: ','Password:')):
resp = chan.recv(9999)
buff +=resp
chan.send(self.rpasword+"\n")
time.sleep(0.1)
buff=''
chan.send("export PS1='[shsnc_client]#' \n")
while not buff.decode('utf-8').endswith(('#','# \n','~ # ')):
resp = chan.recv(9999)
buff +=resp
chan.send(self.cmd+" \n")
buff=''
time.sleep(0.01)
while not buff.endswith(('[shsnc_client]#')):
resp = chan.recv(9999)
buff +=resp
result_data = buff.split('\n')[1:-1]
if 'shsnc_client' in result_data[0]:
result_data[0] = 'host'+' '+self.ip
else:
result_data.insert(0,'host'+' '+self.ip)
return result_data
chan.close()
except Exception as e:
log_file_err.write("ERR:unable to connect%s %s\n"%(self.ip,e))
return []
def auto_sshclient(self):
try:
if self.rusername == '' or self.rpasword == '':
client_result = self.user_sshclient()
else:
client_result = self.root_sshclient()
if client_result == [] or client_result[1] == '':
client_result = self.create_sshclient()
except :
return []
else:
return client_result
def host_def(sql_select):
password = passwd.crypto.decode("gAAAAABcpVuKaEnScGgRGl7Z2zVurdZZpWHYIKm-hjkBkbV9BXbIR3frFvsf3YfmjArD7G156t9c22SZVZAGoYMyxUVMDAYlIQ==")
try:
db = cx_Oracle.connect('shsnc',password,'shsnc')
# sql1="select t.* from nfs_host_info t where t.status= %s " % worktype
curs = db.cursor()
result = curs.execute(sql_select)
rows = curs.fetchall()
db.close()
except Exception as e:
raise e
return rows
def main():
host = host_list_input.split()
cmd = cmd_input
root_user = root_user_input
#print host,cmd,root_user
password = "gAAAAABcpVuKaEnScGgRGl7Z2zVurdZZpWHYIKm-hjkBkbV9BXbIR3frFvsf3YfmjArD7G156t9c22SZVZAGoYMyxUVMDAYlIQ=="
db_connect = data_process('shsnc',password,'shsnc')
for host_message in host :
sql1="select * from crm_machine_info t where t.hostip='%s' and rownum = 1" % (host_message)
line = db_connect.sql_select(sql1)
if len(line) < 1:
message = "Error : Crm_machine_info 表无该主机 %s" % host_message
print message
else :
print line
host = line[0][2]
username = line[0][4]
password1 = line[0][5]
password = passwd.crypto.decode(password1)
port = 22
if line[0][6] != None:
bomcname = 'root'
bomcword1 = line[0][6]
bomcword = passwd.crypto.decode(bomcword1)
elif line[0][7] != None:
bomcname = 'bomc'
bomcword1 = line[0][7]
bomcword = passwd.crypto.decode(bomcword1)
elif line[0][7] == None and line[0][6] == None:
bomcname = ''
bomcword = ''
if root_user == 'no':
client_result = AutoTask(host_message,port,username,password,'','',cmd)
elif root_user == 'yes' :
client_result = AutoTask(host_message,port,username,password,bomcname,bomcword,cmd)
cmd_result = client_result.auto_sshclient()
for result in cmd_result:
print result
if __name__ == '__main__':
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
网站声明:如果转载,请联系本站管理员。否则一切后果自行承担。
加入交流群
请使用微信扫一扫!