sshclient.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Sat Dec 1 11:47:53 2018
  5. @author: dufs
  6. """
  7. import time
  8. import logging
  9. import logging.config
  10. import ConfigParser
  11. import paramiko
  12. #import traceback
  13. import multiprocessing
  14. import databaseconn as dbcn
  15. #logging.config.fileConfig('conf/logging.conf')
  16. #logger = logging.getLogger(__name__)
  17. logger = logging.getLogger('autocheck.sshclient')
  18. def sshclient_execmd(host, execmd):
  19. paramiko.util.log_to_file("log/paramiko.log")
  20. hostname=host[0]
  21. port=host[1]
  22. username=host[2]
  23. password=host[3]
  24. try:
  25. s = paramiko.SSHClient()
  26. s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  27. s.connect(hostname=hostname, port=port, username=username, password=password, timeout=3, compress=True)
  28. stdin, stdout, stderr = s.exec_command (execmd[1])
  29. #stdin.write("Y")
  30. result=stdout.read()
  31. s.close()
  32. logger.debug('get result : %s', str(result))
  33. return (tuple([host[0], host[1], host[4]]), execmd, 0, result)
  34. except Exception as e:
  35. logger.error('get Exception : %s', str(e))
  36. #traceback.print_exc()
  37. return (tuple([host[0], host[1], host[4]]), execmd, -1, str(e))
  38. def ssh_result(res):
  39. '''
  40. '''
  41. if res[2]==0:
  42. logger.debug("%s exec command '%s' success.", res[0][0], res[1][1])
  43. else:
  44. logger.debug("%s exec command '%s' failed.", res[0][0], res[1][1])
  45. ssh_resultSet.add(res)
  46. def snmp_result_save(resSet):
  47. '''
  48. '''
  49. if len(resSet)==0:
  50. return
  51. saveSet=set()
  52. for res in resSet:
  53. IP_ADDRESS=res[0][0]
  54. DEVICE_ID=res[0][2]
  55. cmd=res[1][0]
  56. status=res[2]
  57. result=res[3]
  58. if status!=0:
  59. continue
  60. if cmd=='mkmfsinfo':
  61. INSPECTION_INDEX='DISK_STATUS'
  62. INSPECTION_OBJECT=''
  63. INDEX_VALUE=''
  64. TOTAL=''
  65. USED=''
  66. if len(result)==0:
  67. continue
  68. for line in result.split('\n'):
  69. if len(line)==0:
  70. continue
  71. if line.split()[0].startswith('devname'):
  72. continue
  73. else:
  74. INSPECTION_OBJECT=line.split()[0]
  75. if line.split()[1]=='ACTIVE':
  76. INDEX_VALUE=1
  77. else:
  78. INDEX_VALUE=0
  79. saveSet.add((IP_ADDRESS, DEVICE_ID, INSPECTION_INDEX, INSPECTION_OBJECT, INDEX_VALUE, TOTAL, USED))
  80. elif cmd=='userinfo':
  81. INSPECTION_INDEX='ACCOUNT'
  82. INSPECTION_OBJECT=''
  83. INDEX_VALUE=''
  84. TOTAL=''
  85. USED=''
  86. for user in result.split('\n'):
  87. if len(user)==0:
  88. continue
  89. INSPECTION_OBJECT=user
  90. saveSet.add((IP_ADDRESS, DEVICE_ID, INSPECTION_INDEX, INSPECTION_OBJECT, INDEX_VALUE, TOTAL, USED))
  91. logger.info('total %d result need to save', len(saveSet))
  92. if len(saveSet)==0:
  93. return 0
  94. v_sql='''insert into isp_autoinspection_test(ip_address,device_id,inspection_index,inspection_object,index_value,total,used,inspection_time,into_time) values(:x1, :x2, :x3, :x4, :x5, :x6, :x7, trunc(sysdate,'hh24'), sysdate)'''
  95. logger.info('exec result save sql : %s', v_sql)
  96. try:
  97. cf = ConfigParser.SafeConfigParser()
  98. cf.read('conf/autocheck.conf')
  99. db_url=cf.get('db', 'url')
  100. nls_lang=cf.get('db', 'nls_lang')
  101. except Exception as e:
  102. logger.error('parse config file error: ' + str(e) , exc_info=True)
  103. raise
  104. if len(nls_lang)==0:
  105. nls_lang='SIMPLIFIED CHINESE_CHINA.UTF8'
  106. try:
  107. dbclt=dbcn.DataBaseConn(db_url, nls_lang=nls_lang)
  108. except Exception as e:
  109. logger.error('connect db faild : ' + str(e) , exc_info=True)
  110. raise
  111. for rlst in saveSet:
  112. try:
  113. dbclt.exec_sql(v_sql, rlst)
  114. except Exception as e:
  115. logger.error('connect db faild : ' + str(e) , exc_info=True)
  116. dbclt.conn.commit()
  117. dbclt.close_connect()
  118. logger.info('save result success')
  119. def ssh_batch_cmd(hostSet, cmdSet):
  120. global ssh_resultSet
  121. ssh_resultSet=set()
  122. time_start=time.time()
  123. max_thread=100
  124. try:
  125. cf = ConfigParser.SafeConfigParser()
  126. cf.read('conf/autocheck.conf')
  127. max_thread=cf.getint('sshclient', 'max_thread')
  128. except Exception as e:
  129. logger.error('parse config file error: ' + str(e) , exc_info=True)
  130. logger.debug('use defult : %d', max_thread)
  131. if len(hostSet)<=max_thread:
  132. pool_size=len(hostSet)
  133. else:
  134. pool_size=max_thread
  135. pool = multiprocessing.Pool(processes=pool_size)
  136. for host in hostSet:
  137. for execmd in cmdSet:
  138. pool.apply_async(sshclient_execmd, (host, execmd), callback=ssh_result)
  139. pool.close()
  140. pool.join()
  141. time_end=time.time()
  142. time_used=time_end-time_start
  143. logger.info("all sub-processes done, used time %d s", time_used)
  144. snmp_result_save(ssh_resultSet)
  145. if __name__ == "__main__":
  146. logging.config.fileConfig("conf/logging.conf")
  147. #create logger
  148. logger = logging.getLogger("sshclient")
  149. hostSet=set()
  150. hostSet.add(('10.102.52.9', 22444, 'iss', 'Iss@52.8!', 101))
  151. hostSet.add(('10.102.52.10', 22444, 'iss', 'Iss@52.8!', 102))
  152. cmdSet=set()
  153. cmdSet.add(('userinfo', '''cat /etc/passwd |awk -F":" '{print $1}' '''))
  154. cmdSet.add(('mkmfsinfo', "sudo -u root mkmfsinfo -querydisk |awk '{print $1,$8}'"))
  155. ssh_batch_cmd(hostSet, cmdSet)