SendCommandWithSalt.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # coding: utf-8
  2. import salt.client
  3. import MySQLdb
  4. from socket import socket, SOCK_DGRAM, AF_INET
  5. import os
  6. import sys
  7. class Cmdsender(object):
  8. def __init__(self):
  9. self.rooms_path = '/home/room/server'
  10. self.work_path = '/home/room/tools'
  11. s = socket(AF_INET, SOCK_DGRAM)
  12. s.connect(('192.168.1.1', 0))
  13. self.local_ip = s.getsockname()[0]
  14. self.conn = MySQLdb.connect(user='user', passwd='passwd', host='192.168.1.81', port=11306)
  15. self.cursor = self.conn.cursor()
  16. def salt_caller(self, hostlist, action, args):
  17. client = salt.client.LocalClient('/etc/salt/master')
  18. ret = client.cmd(hostlist,
  19. action,
  20. args,
  21. expr_form='list'
  22. )
  23. return ret
  24. def sendcmd(self, server_ip, server_name, cmd):
  25. controler_path = os.path.join(self.work_path, 'component_controler.py')
  26. salt_host_name = 'Dy-JXQ-' + server_ip.split('.')[-1]
  27. ret = self.salt_caller([salt_host_name], 'cmd.run',
  28. ['python ' + controler_path + ' ' + server_name + ' ' + cmd])
  29. return ret
  30. # 获取room所在chatroom信息
  31. def getserverinfo(self, roomid):
  32. self.cursor.execute("use stt_online")
  33. self.cursor.execute("select server_id from web_online_room where id=%s" % roomid)
  34. chatroom_id = self.cursor.fetchall()[0][0]
  35. self.cursor.execute("select server_id,client_name from online_msg_client where client_id=%s" % chatroom_id)
  36. msg_id, chatroom_name = self.cursor.fetchall()[0]
  37. self.cursor.execute("select ip from online_msg_server where server_id=%s" % msg_id)
  38. server_ip = self.cursor.fetchall()[0][0]
  39. return server_ip, chatroom_name
  40. if __name__ == "__main__":
  41. if len(sys.argv) < 2:
  42. print '''
  43. Usage: To Unload Room --> %s unloadroom roomid
  44. For Example:
  45. %s unloadroom 338700'
  46. If You Want Send Command To Screen, Then:
  47. %s remote_ip server_name, 'command'
  48. For Example:
  49. %s 192.168.1.1 ChatRoom71 'showroomlist'
  50. ''' % tuple([sys.argv[0]] * 4)
  51. sys.exit(0)
  52. caller = Cmdsender()
  53. if sys.argv[1] == 'unloadroom':
  54. roomid = sys.argv[2]
  55. server_ip, chatroom_name = caller.getserverinfo(roomid)
  56. print caller.sendcmd(server_ip, chatroom_name, 'unloadroom ' + roomid)
  57. else:
  58. server_ip = sys.argv[1]
  59. server_name = sys.argv[2]
  60. cmd = sys.argv[3]
  61. print caller.sendcmd(server_ip, server_name, cmd)