def setUp(self): self.resource = RTResource('http://rtkit.test/', None, None, AbstractAuthenticator) self.content = { 'content': { 'Queue': 1, 'Subject': 'New Ticket', 'Text': 'My useless\ntext on\nthree lines.', } } self.req_body = 'content=Queue: 1\nText: My useless\n text on\n three lines.\nSubject: New Ticket' self.req_headers_get = { 'connection': 'close', 'user-agent': 'rtkit-ua', 'host': 'rtkit.test', 'accept': 'text/plain', 'accept-encoding': 'identity', } self.req_headers_post = self.req_headers_get.copy() self.req_headers_post.update({ 'content-length': '76', 'content-type': 'application/x-www-form-urlencoded; charset=utf-8', })
def modifyTicket(ticketID): global emailGlobal dic = {"email": emailGlobal} lst = [] set_logging('debug') logger = logging.getLogger('rtkit') my_config = DITICConfig() system = my_config.get_system() resource = RTResource('http://localhost/rt/REST/1.0/', system['username'], system['password'], CookieAuthenticator) try: response = resource.get(path='ticket/' + ticketID) for r in response.parsed: for t in r: logger.info(t) lst.append(t) except RTResourceError as e: logger.error(e.response.status_int) logger.error(e.response.status) logger.error(e.response.parsed) lst = dict(lst) return template("ticketDetails", lst=lst, ticketID=ticketID, dic=dic)
def loadResponseInfoFromRT(request): if request.method != "POST": return HttpResponseNotAllowed(["POST"]) rt = RTResource(settings.RT_URL, settings.RT_USER, settings.RT_PW, BasicAuthenticator) res = { "failed" : 0, "succeded" : 0 , "updated" : 0 } unansweredContacts = SponsorContact.objects.filter(responded=False).exclude(rtTicketId=None) for contact in unansweredContacts: # read the ticket from RT rtres = rt.get(path="ticket/{}/history".format(contact.rtTicketId)) if rtres.status_int != 200: res["failed"] = res["failed"] + 1 continue res["succeded"] = res["succeded"] + 1 results = rtres.parsed if (len( [r for r in rtres.parsed[0] if r[1].lower().find("correspondence added") >= 0 and r[1].find("@") >= 0]) >= 1): # count the number of correspondances that also contain an @. corresespondances added with "@" come from external mail and not rt user?! res["updated"] = res["updated"] + 1 contact.responded = True contact.save() return respond_json(res)
def __callback(ch, method, properties, body): ''' This is the callback function that is called when a message is delivered to the message queue IT SHOULD NOT BE CALLED DIRECTLY In this implementation we are forwarding these messages into the RT queue specified in the configuration file ''' from rtkit.resource import RTResource from rtkit.authenticators import CookieAuthenticator from rtkit.errors import RTResourceError from rtkit import set_logging import logging set_logging('error') logger = logging.getLogger('rtkit') auth = CookieAuthenticator(configInfo['RTUser'], configInfo['RTUserPass']) resource = RTResource('%s/REST/1.0/' % (configInfo['RTHost'],), auth) content = {'content': { 'Queue': configInfo['RTQueueId'], 'Subject' : body, } } try: response = resource.post(path='ticket/new', payload=content,) logger.info(response.parsed) except RTResourceError as e: logger.error(e.response.status_int) logger.error(e.response.status) logger.error(e.response.parsed)
class BasicAuthTestCase(unittest.TestCase): def setUp(self): self.resource = RTResource('http://rtkit.test/', 'USER', 'PASS', BasicAuthenticator) @httprettified def test_auth(self): HTTPretty.register_uri( HTTPretty.GET, 'http://rtkit.test/ticket/1', responses=[ HTTPretty.Response( body='', status=401, www_authenticate='Basic realm="rtkit.test"'), HTTPretty.Response( body='RT/3.8.10 200 Ok\n\n# Ticket 1 does not exist.\n\n\n', status=200), ]) self.resource.get(path='ticket/1', headers={ 'User-Agent': 'rtkit-ua', }) self.assertEqual( HTTPretty.last_request.headers['authorization'], 'Basic ' + base64.b64encode('USER:PASS'), )
def create_ticket(mispid, subject): set_logging('error') logger = logging.getLogger('rtkit') resource = RTResource(rt_url, rt_user, rt_pass, CookieAuthenticator) emails = "*****@*****.**" subject = "%s - takedown" % (subject) body = "Automatically imported via MISP # %s" % (mispid) content = { 'content': { 'queue': 3, 'requestor': emails, 'subject': urllib.quote(subject), 'text': body, } } try: response = resource.post( path='ticket/new', payload=content, ) logger.info(response.parsed) for t in response.parsed: ticketid = t[0][1] return ticketid.replace('ticket/', '') except RTResourceError as e: logger.error(e.response.status_int) logger.error(e.response.status) logger.error(e.response.parsed)
class CookieAuthTestCase(unittest.TestCase): def setUp(self): self.resource = RTResource("http://rtkit.test/", "USER", "PASS", CookieAuthenticator) @httprettified def test_auth(self): HTTPretty.register_uri( HTTPretty.POST, "http://rtkit.test/", body="RT/4.0.5 200 Ok", status=200, set_cookie="RT_SID_example.com.80=2ec1d46cb1c05fff0fce34ed268e7d26; path=/; HttpOnly", transfer_encoding="chunked", ) HTTPretty.register_uri( HTTPretty.GET, "http://rtkit.test/ticket/1", body="RT/3.8.10 200 Ok\n\n# Ticket 1 does not exist.\n\n\n", status=200, ) self.resource.get(path="ticket/1", headers={"User-Agent": "rtkit-ua"}) self.assertEqual(len(HTTPretty.latest_requests), 2) self.assertEqual(HTTPretty.latest_requests[0].path, "/") self.assertEqual(HTTPretty.latest_requests[0].method, "POST") self.assertEqual(HTTPretty.latest_requests[0].body, "user=USER&pass=PASS") self.assertEqual(HTTPretty.latest_requests[1].path, "/ticket/1") self.assertEqual(HTTPretty.latest_requests[1].method, "GET") self.assertEqual(HTTPretty.latest_requests[1].body, "")
class CookieAuthTestCase(unittest.TestCase): def setUp(self): self.resource = RTResource('http://rtkit.test/', 'USER', 'PASS', CookieAuthenticator) @httprettified def test_auth(self): HTTPretty.register_uri( HTTPretty.POST, 'http://rtkit.test/', body='RT/4.0.5 200 Ok', status=200, set_cookie='RT_SID_example.com.80=2ec1d46cb1c05fff0fce34ed268e7d26; path=/; HttpOnly', transfer_encoding='chunked' ) HTTPretty.register_uri( HTTPretty.GET, 'http://rtkit.test/ticket/1', body='RT/3.8.10 200 Ok\n\n# Ticket 1 does not exist.\n\n\n', status=200 ) self.resource.get( path='ticket/1', headers={'User-Agent': 'rtkit-ua', } ) self.assertEqual(len(HTTPretty.latest_requests), 2) self.assertEqual(HTTPretty.latest_requests[0].path, '/') self.assertEqual(HTTPretty.latest_requests[0].method, 'POST') self.assertEqual(HTTPretty.latest_requests[0].body, 'user=USER&pass=PASS') self.assertEqual(HTTPretty.latest_requests[1].path, '/ticket/1') self.assertEqual(HTTPretty.latest_requests[1].method, 'GET') self.assertEqual(HTTPretty.latest_requests[1].body, '')
def comment_on_rt_ticket(self, rt_number, comment): full_rt_url = str(self.get_request_tracker_url()) + '/REST/1.0/' resource = RTResource(full_rt_url, self.rt_username, self.rt_password, CookieAuthenticator) content = { 'content': { 'id': rt_number, 'Action': 'comment', 'Text' : comment.replace('\n', '\n '), } } try: path = 'ticket/%s/comment' % (str(rt_number)) response = resource.post(path=path, payload=content,) except RTResourceError as e: error_msg = str(e.response.status_int) + '\n' error_msg += str(e.response.status) + '\n' error_msg += str(e.response.parsed) + '\n' log.error(error_msg) raise ValueError(error_msg) if response.status_int != 200: error_msg = 'HTTP status %s when attempting to contact %s\n' % (str(response.status_int), str(full_rt_url)) error_msg += str(response.status) + '\n' error_msg += str(response.parsed) + '\n' log.error(error_msg) raise ValueError(error_msg)
def logout(): set_logging('debug') logger = logging.getLogger('rtkit') my_config = DITICConfig() system = my_config.get_system() resource = RTResource('http://localhost/rt/REST/1.0/', system['username'], system['password'], CookieAuthenticator) #create a ticket content = {'content': {}} try: response = resource.post( path='logout/', payload=content, ) logger.info(response.parsed) except RTResourceError as e: logger.error(e.response.status_int) logger.error(e.response.status) logger.error(e.response.parsed) redirect("/")
def test(url): resource = RTResource(url, None, None, KerberosAuthenticator) try: response = resource.get(path='ticket/1') for r in response.parsed: for t in r: logger.info(t) except RTResourceError as e: logger.error(e.response.status_int) logger.error(e.response.status) logger.error(e.response.parsed)
class QueryStringAuthTestCase(unittest.TestCase): def setUp(self): self.resource = RTResource("http://rtkit.test/", "USER", "PASS", QueryStringAuthenticator) @httprettified def test_auth(self): HTTPretty.register_uri( HTTPretty.GET, "http://rtkit.test/ticket/1", responses=[HTTPretty.Response(body="RT/3.8.10 200 Ok\n\n# Ticket 1 does not exist.\n\n\n", status=200)], ) self.resource.get(path="ticket/1", headers={"User-Agent": "rtkit-ua"}) self.assertEqual(HTTPretty.latest_requests[0].path, "/ticket/1?user=USER&pass=PASS")
def createTicket(): global emailGlobal priority = '' priority = int(request.forms.get('priority')) if priority >= 200: setUrgent = 'yes' else: setUrgent = '' set_logging('debug') logger = logging.getLogger('rtkit') my_config = DITICConfig() system = my_config.get_system() resource = RTResource('http://localhost/rt/REST/1.0/', system['username'], system['password'], CookieAuthenticator) #create a ticket content = { 'content': { 'Queue': request.forms.get( "queue" ), #General - unassigned is the name of the desired queue 'Requestors': emailGlobal, 'Subject': request.forms.get("subject"), #text to go into subject field 'Text': request.forms.get("content"), 'Priority': request.forms.get('priority'), 'CF.{servico}': request.forms.get("servico"), 'CF.{IS - Informatica e Sistemas}': request.forms.get("inforsistemas"), 'CF.{DITIC - Interrupted}': '', 'CF.{DITIC - Urgent}': setUrgent, } } try: response = resource.post( path='ticket/new', payload=content, ) logger.info(response.parsed) except RTResourceError as e: logger.error(e.response.status_int) logger.error(e.response.status) logger.error(e.response.parsed)
class BasicAuthTestCase(unittest.TestCase): def setUp(self): self.resource = RTResource("http://rtkit.test/", "USER", "PASS", BasicAuthenticator) @httprettified def test_auth(self): HTTPretty.register_uri( HTTPretty.GET, "http://rtkit.test/ticket/1", responses=[ HTTPretty.Response(body="", status=401, www_authenticate='Basic realm="rtkit.test"'), HTTPretty.Response(body="RT/3.8.10 200 Ok\n\n# Ticket 1 does not exist.\n\n\n", status=200), ], ) self.resource.get(path="ticket/1", headers={"User-Agent": "rtkit-ua"}) self.assertEqual(HTTPretty.last_request.headers["authorization"], "Basic " + base64.b64encode("USER:PASS"))
def is_ticket_open(id): status = False global rt_url global rt_user global rt_pass resource = RTResource(rt_url, rt_user, rt_pass, CookieAuthenticator) try: ticket = "ticket/%s" % id response = resource.get(path=ticket) for r in response.parsed: l = {a: b for a, b in r} ticket_status = l["Status"] if ticket_status == "open" or ticket_status == "new": status = id except: return False return status
class QueryStringAuthTestCase(unittest.TestCase): def setUp(self): self.resource = RTResource('http://rtkit.test/', 'USER', 'PASS', QueryStringAuthenticator) @httprettified def test_auth(self): HTTPretty.register_uri( HTTPretty.GET, 'http://rtkit.test/ticket/1', responses=[ HTTPretty.Response(body='RT/3.8.10 200 Ok\n\n# Ticket 1 does not exist.\n\n\n', status=200), ] ) self.resource.get( path='ticket/1', headers={'User-Agent': 'rtkit-ua', } ) self.assertEqual(HTTPretty.latest_requests[0].path, '/ticket/1?user=USER&pass=PASS')
def __init__(self, roomJID, nick, rt_url, rt_user, rt_pwd, roomPassword, rt_display_url=None, output_format="extended"): BaseMUCBot.__init__(self, roomJID, nick, roomPassword) self.resource = RTResource(rt_url + 'REST/1.0/', rt_user, rt_pwd, CookieAuthenticator) self.rt_url = rt_url self.output_format = output_format if rt_display_url is None: self.rt_display_url = rt_url else: self.rt_display_url = rt_display_url
def __init__(self, userName, password, rt_api_url): ''' Constructor ''' from rtkit import set_logging import logging set_logging('debug') logger = logging.getLogger('rtkit') #resource = RTResource('http://<HOST>/REST/1.0/', '<USER>', '<PWD>', BasicAuthenticator) resource = RTResource(rt_api_url, userName, password, BasicAuthenticator)
def updateTicket(ticketID): global emailGlobal priority = int(request.forms.get('priority')) if priority > 255: priority = 255 if priority >= 200: setUrgent = 'yes' else: setUrgent = '' set_logging('debug') logger = logging.getLogger('rtkit') my_config = DITICConfig() system = my_config.get_system() resource = RTResource('http://localhost/rt/REST/1.0/', system['username'], system['password'], CookieAuthenticator) #create a ticket content = { 'content': { 'Priority': str(priority), 'cf.{ditic - urgent}': setUrgent, } } try: response = resource.post( path='ticket/' + ticketID, payload=content, ) logger.info(response.parsed) except RTResourceError as e: logger.error(e.response.status_int) logger.error(e.response.status) logger.error(e.response.parsed)
class BasicAuthTestCase(unittest.TestCase): def setUp(self): self.resource = RTResource('http://rtkit.test/', 'USER', 'PASS', BasicAuthenticator) @httprettified def test_auth(self): HTTPretty.register_uri( HTTPretty.GET, 'http://rtkit.test/ticket/1', responses=[ HTTPretty.Response(body='', status=401, www_authenticate='Basic realm="rtkit.test"'), HTTPretty.Response(body='RT/3.8.10 200 Ok\n\n# Ticket 1 does not exist.\n\n\n', status=200), ] ) self.resource.get( path='ticket/1', headers={'User-Agent': 'rtkit-ua', } ) self.assertEqual( HTTPretty.last_request.headers['authorization'], 'Basic ' + base64.b64encode('USER:PASS'), )
def __callback(ch, method, properties, body): ''' This is the callback function that is called when a message is delivered to the message queue IT SHOULD NOT BE CALLED DIRECTLY In this implementation we are forwarding these messages into the RT queue specified in the configuration file ''' from rtkit.resource import RTResource from rtkit.authenticators import CookieAuthenticator from rtkit.errors import RTResourceError from rtkit import set_logging import logging set_logging('error') logger = logging.getLogger('rtkit') auth = CookieAuthenticator(configInfo['RTUser'], configInfo['RTUserPass']) resource = RTResource('%s/REST/1.0/' % (configInfo['RTHost'], ), auth) content = { 'content': { 'Queue': configInfo['RTQueueId'], 'Subject': body, } } try: response = resource.post( path='ticket/new', payload=content, ) logger.info(response.parsed) except RTResourceError as e: logger.error(e.response.status_int) logger.error(e.response.status) logger.error(e.response.parsed)
def addComment(ticketID): set_logging('debug') logger = logging.getLogger('rtkit') my_config = DITICConfig() system = my_config.get_system() resource = RTResource('http://localhost/rt/REST/1.0/', system['username'], system['password'], CookieAuthenticator) try: params = { 'content': { 'Action': 'comment', 'Text': request.forms.get("content"), }, } params2 = { 'content': { 'status': 'resolved', } } response = resource.post( path='ticket/' + ticketID + '/comment', payload=params, ) response = resource.post(path='ticket/' + ticketID, payload=params2) for r in response.parsed: for t in r: logger.info(t) except RTResourceError as e: logger.error(e.response.status_int) logger.error(e.response.status) logger.error(e.response.parsed)
def create_ticket(*args): url = "https://{0}/REST/1.0/".format(str(rtir_ip)) resource = RTResource(url, username, password, CookieAuthenticator) ttime = time.strftime("%T").split(":")[0] raw_data = get_content() content = { 'content': { 'Queue': queue_number, 'Subject': title, 'Text': raw_data, 'status': 'open', 'Owner': owner, "Sla": urgency, "Requestor": req_email, "Cc": cc_email, "AdminCc": admin_cc_email } } print(dir(content)) print(content) try: response = resource.post( path='ticket/new', payload=content, ) except RTResourceError as e: logger.error(e.response.status_int) logger.error(e.response.status) logger.error(e.response.parsed)
def setUpClass(cls): super(TestCaseTicket, cls).setUpClass() cls.resource = RTResource('http://localhost:5000/', None, None, AbstractAuthenticator)
def process_job(self): if not self.request.POST.has_key("text"): self.job_errors.append("invalid request: item 'text' missing.") return False sponsoring = self.get_sponsoring(self.kwargs["spk"]) # check if invoice already exists if Invoice.objects.filter(sponsoring=sponsoring).count() > 0: invoice = sponsoring.invoice else: invoice = None if invoice is None: self.job_errors.append("There is no invoice for this sponsoring.") return False if not invoice.pdf: self.job_errors.append( "There is no invoice PDF available for this sponsoring.") return False rt = RTResource(settings.RT_URL, settings.RT_USER, settings.RT_PW, BasicAuthenticator) # TODO: Refactor froscon specific parts to config if sponsoring.contact.contactPersonLanguage.startswith("de"): subject = "Rechnung Partner-Paket {} {}".format( settings.CONFERENCE_NAME, date.today().year) else: subject = "Invoice Partnership {} {}".format( settings.CONFERENCE_NAME, date.today().year) data = { "content": { "Queue": settings.RT_QUEUE_INVOICE, "Owner": self.request.user.username, "Subject": subject, "Requestor": sponsoring.contact.contactPersonEmail, } } res = rt.post(path="ticket/new", payload=data) if res.status_int != 200: self.job_errors.append( "RT Ticket creation failed with status code {}".format( res.status)) return False tid = None for k, v in res.parsed[0]: if k == "id": tid = v break if tid is None: self.job_errors.append("RT answer contained no ticket id") return False # compile message resp_data = { "content": { "Action": "correspond", "Text": self.request.POST["text"].encode("utf8") } } resp_data["attachment_1"] = file(sponsoring.invoice.pdf.path) resp_data["content"]["Attachment"] = "{}.pdf".format( sponsoring.invoice.invoiceNumber) res = rt.post(path=(tid + "/comment"), payload=resp_data) if res.status_int != 200: self.job_errors.append("RT Correspondance failed") return False invoice.rtTicketRef = int(tid.lstrip("ticket/")) invoice.save() return True
def process_job(self): if not self.request.POST.has_key("text"): self.job_errors.append("invalid request: item 'text' missing.") return False sponsoring = self.get_sponsoring(self.kwargs["spk"]) # check if invoice already exists if Invoice.objects.filter(sponsoring=sponsoring).count() > 0: invoice = sponsoring.invoice else: invoice = None if invoice is None: self.job_errors.append("There is no invoice for this sponsoring.") return False if not invoice.pdf: self.job_errors.append("There is no invoice PDF available for this sponsoring.") return False rt = RTResource(settings.RT_URL, settings.RT_USER, settings.RT_PW, BasicAuthenticator) # TODO: Refactor froscon specific parts to config data = { "content" : { "Queue" : settings.RT_QUEUE_INVOICE, "Owner" : self.request.user.username, "Subject" : "Rechnung Sponsoring {} {}".format(settings.CONFERENCE_NAME, date.today().year) if sponsoring.contact.contactPersonLanguage.startswith("de") else "Invoice Sponsoring {} {}".format(settings.CONFERENCE_NAME, date.today().year), "Requestor" : sponsoring.contact.contactPersonEmail, } } res = rt.post(path="ticket/new",payload=data) if res.status_int != 200: self.job_errors.append("RT Ticket creation failed with status code {}".format(res.status)) return False tid = None for k,v in res.parsed[0]: if k == "id": tid = v break if tid is None: self.job_errors.append("RT answer contained no ticket id") return False # compile message resp_data = { "content" : { "Action" : "correspond", "Text" : self.request.POST["text"].encode("utf8") } } resp_data["attachment_1"] = file(sponsoring.invoice.pdf.path) resp_data["content"]["Attachment"] = "{}.pdf".format(sponsoring.invoice.invoiceNumber) res = rt.post(path=(tid + "/comment"),payload=resp_data) if res.status_int != 200: self.job_errors.append("RT Correspondance failed") return False invoice.rtTicketRef = int(tid.lstrip("ticket/")) invoice.save() return True
import logging set_logging('debug') logger = logging.getLogger('rtkit') DEBUGGING = False def read_credentials(credentials_file): with open(credentials_file) as f: content = f.readlines() return content[0].strip(), content[1].strip() username, password = read_credentials("credentials.txt") resource = RTResource('https://help.rice.edu/REST/1.0/', username, password, CookieAuthenticator) def submit_ticket(queue, status, requestor, subject, text): global resource, DEBUGGING content = { 'content': { 'Queue': queue, 'Status': status, 'Requestor': requestor, 'Subject': subject, 'Text': text } } if DEBUGGING: print "DEBUGGING - sent response with content:"
def setUp(self): self.resource = RTResource('http://rtkit.test/', 'USER', 'PASS', QueryStringAuthenticator)
pass # Initialize or restore RT state settings stored_last_updated_activity = time.gmtime(0) try: stored_last_updated_activity = rt_parse_ticket_time(config.get('rt', 'last_fetched_timestamp')) except: logger.warn('Unable to parse feed timestamp - Defaulting to: ' + rt_format_ticket_time(stored_last_updated_activity) + ' UTC') syslog.syslog(syslog.LOG_WARNING, 'Unable to parse feed timestamp - Defaulting to: ' + rt_format_ticket_time(stored_last_updated_activity) + ' UTC') # Initialize web services # Source RT Feed resource = None feed = None try: resource = RTResource(config.get('rt', 'api_url_prefix'), config.get('rt', 'username'), config.get('rt', 'password'), CookieAuthenticator) feed = resource.get(path=config.get('rt', 'api_search_suffix')) except RTResourceError as e: logger.error('Cannot connect to RT server') syslog.syslog(syslog.LOG_ERR, 'Cannot connect to RT server') logger.error(e.response.status_int) syslog.syslog(syslog.LOG_ERR, e.response.status_int) logger.error(e.response.status) syslog.syslog(syslog.LOG_ERR, e.response.status) logger.error(e.response.parsed) syslog.syslog(syslog.LOG_ERR, e.response.parsed) sys.exit(1) except: logger.error('Cannot connect to RT server') syslog.syslog(syslog.LOG_ERR, 'Cannot connect to RT server') sys.exit(1)
class RTBot(BaseMUCBot): def __init__(self, roomJID, nick, rt_url, rt_user, rt_pwd, roomPassword, rt_display_url=None, output_format="extended"): BaseMUCBot.__init__(self, roomJID, nick, roomPassword) self.resource = RTResource(rt_url + 'REST/1.0/', rt_user, rt_pwd, CookieAuthenticator) self.rt_url = rt_url self.output_format = output_format if rt_display_url is None: self.rt_display_url = rt_url else: self.rt_display_url = rt_display_url def handleGroupChat(self, room, user, message): if self.nick in message.body: if 'hi' in message.body or 'hello' in message.body: body = u"%s: greetings stranger arrr arrr!" % (user.nick) self.groupChat(self.roomJID, body) elif 'open' in message.body: queue = rt_default_queue m = re.search(r'open\s([^\s]+)', message.body) if m: queue = m.group(1) if queue == 'all': queue_query = '' else: queue_query = " AND QUEUE='" + queue + "'" query = "Owner = 'Nobody' AND ( Status = 'new' OR Status = 'open' )" + queue_query query = urllib.quote(query) prepend_string = 'Queue: ' + queue + '\n\n' try: ret = self.rtquery(query, prepend_string) self.groupChat(self.roomJID, ret) except NoResponse as e: self.groupChat(self.roomJID, e.message) elif 'search' in message.body: m = re.search(r'search\s([^\s]+)', message.body) if m: search = m.group(1) if len(search) >= 3: query = "Subject LIKE '" + search + "'" query = urllib.quote(query) try: ret = self.rtquery(query) self.groupChat(self.roomJID, ret) except NoResponse as e: self.groupChat(self.roomJID, e.message) else: self.groupChat(self.roomJID, 'Please enter at least 3 characters!') else: self.groupChat(self.roomJID, 'Nothing to search for!') elif 'ticket' in message.body: m = re.search(r'ticket\s([0-9]+)', message.body) if m: ticket_id = m.group(1) try: ret = self.rtticket(ticket_id) self.groupChat(self.roomJID, ret) except NoResponse as e: self.groupChat(self.roomJID, e.message) else: self.groupChat(self.roomJID, 'Nothing to search for!') elif 'help' in message.body: self.groupChat(self.roomJID, 'Usage:') self.groupChat(self.roomJID, 'open <queue name> - display all unassigned open and new tickets') self.groupChat(self.roomJID, ' queue name defaults to '+rt_default_queue) self.groupChat(self.roomJID, 'search <subject> - search for a subject') self.groupChat(self.roomJID, 'ticket <ticket-id> - display ticket information') def rtquery(self, query, prepend_text=''): ret = '\n' if self.output_format == "extended": ret += prepend_text try: response = self.resource.get(path='search/ticket?query=' + query) if len(response.parsed) > 0: first = True for r in response.parsed: for t in r: if not first and self.output_format == "extended": ret += '\n' else: first = False logger.info(t) t_id = t[0] t_display = self.rt_display_url + 'Ticket/Display.html?id=' + t_id t_title = unicode(t[1], errors='replace') if self.output_format == "extended": ret += 'Ticket#: ' + t_id + '\n' ret += 'URL: ' + t_display + '\n' ret += 'Title: ' + t_title + '\n' elif self.output_format == "compact": ret += '#'+t_id+","+t_title+","+t_display+"\n" else: raise NoResponse('Nothing found!') except RTResourceError as e: logger.error(e.response.status_int) logger.error(e.response.status) logger.error(e.response.parsed) return ret def rtticket(self, ticket_id): ret = '\n' try: response = self.resource.get(path='ticket/' + ticket_id + '/show') if len(response.parsed) > 0: rsp_dict = {} for r in response.parsed: for t in r: rsp_dict[t[0]] = unicode(t[1], 'utf-8') ret += 'Ticket#: ' + ticket_id + '\n' t_display = self.rt_url + 'Ticket/Display.html?id=' + ticket_id ret += 'URL: ' + t_display + '\n' ret += 'Title: ' + rsp_dict['Subject'] + '\n' ret += 'Queue: ' + rsp_dict['Queue'] + '\n' ret += 'Owner: ' + rsp_dict['Owner'] + '\n' ret += 'Creator: ' + rsp_dict['Creator'] + '\n' ret += 'Status: ' + rsp_dict['Status'] + '\n' ret += 'Requestors: ' + rsp_dict['Requestors'] + '\n' ret += 'Created: ' + rsp_dict['Created'] + '\n' ret += 'LastUpdated: ' + rsp_dict['LastUpdated'] + '\n' #ret += ': ' + rsp_dict[''] + '\n' if 'Resolved' in rsp_dict: ret += 'Resolved: ' + rsp_dict['Resolved'] + '\n' else: raise NoResponse('Nothing found!') except RTResourceError as e: logger.error(e.response.status_int) logger.error(e.response.status) logger.error(e.response.parsed) #return unicode(ret, 'utf-8') return ret
class TktTestCase(unittest.TestCase): def setUp(self): self.resource = RTResource('http://rtkit.test/', None, None, AbstractAuthenticator) self.content = { 'content': { 'Queue': 1, 'Subject': 'New Ticket', 'Text': 'My useless\ntext on\nthree lines.', } } self.req_body = 'content=Queue: 1\nText: My useless\n text on\n three lines.\nSubject: New Ticket' self.req_headers_get = { 'connection': 'close', 'user-agent': 'rtkit-ua', 'host': 'rtkit.test', 'accept': 'text/plain', 'accept-encoding': 'identity', } self.req_headers_post = self.req_headers_get.copy() self.req_headers_post.update({ 'content-length': '76', 'content-type': 'application/x-www-form-urlencoded; charset=utf-8', }) @httprettified def test_http_error(self): HTTPretty.register_uri(HTTPretty.GET, 'http://rtkit.test/:GET:', status=404, body='Not Found') response = self.resource.get(':GET:', headers={'User-Agent': 'rtkit-ua', }) self.assertEqual(response.parsed, [[]]) self.assertEqual(response.status_int, 500) self.assertEqual(response.status, 'Not Found') @httprettified def assertPost(self, body, expected, content=None): HTTPretty.register_uri(HTTPretty.POST, 'http://rtkit.test/:POST:', body=body) response = self.resource.post( path=':POST:', payload=content or self.content, headers={'User-Agent': 'rtkit-ua', } ) self.assertEqual(response.parsed, expected.parsed) self.assertEqual(response.status_int, expected.status_int) self.assertEqual(response.status, expected.status) self.assertEqual(HTTPretty.last_request.method, HTTPretty.POST) self.assertEqual(HTTPretty.last_request.path, '/:POST:') self.assertEqual(HTTPretty.last_request.body, expected.req_body) self.assertEqual(dict(HTTPretty.last_request.headers), expected.req_headers) @httprettified def assertGet(self, body, expected): HTTPretty.register_uri(HTTPretty.GET, 'http://rtkit.test/:GET:', body=body) response = self.resource.get( path=':GET:', headers={'User-Agent': 'rtkit-ua', } ) self.assertEqual(response.parsed, expected.parsed) self.assertEqual(response.status_int, expected.status_int) self.assertEqual(response.status, expected.status) self.assertEqual(HTTPretty.last_request.method, HTTPretty.GET) self.assertEqual(HTTPretty.last_request.path, '/:GET:') self.assertEqual(HTTPretty.last_request.body, expected.req_body) self.assertEqual(dict(HTTPretty.last_request.headers), expected.req_headers) def test_create_tkt(self): expected = Expected( parsed=[[('id', 'ticket/1')]], status_int=200, status='200 Ok', req_body=self.req_body, req_headers=self.req_headers_post, ) self.assertPost( body='RT/3.8.10 200 Ok\n\n# Ticket 1 created.\n\n', expected=expected, ) def test_create_tkt_noqueue(self): expected = Expected( parsed=[], status_int=400, status='400 Could not create ticket. Queue not set', req_body=self.req_body, req_headers=self.req_headers_post, ) self.assertPost( body='RT/3.8.10 200 Ok\n\n# Could not create ticket.\n# Could not create ticket. Queue not set\n\n', expected=expected, ) def test_create_tkt_noperm(self): expected = Expected( parsed=[], status_int=400, status='400 No permission to create tickets in the queue \'___Admin\'', req_body=self.req_body, req_headers=self.req_headers_post, ) self.assertPost( body='RT/3.8.10 200 Ok\n\n# Could not create ticket.\n# No permission to create tickets in the queue \'___Admin\'\n\n', expected=expected, ) def test_read_tkt(self): expected = Expected( parsed=[[ ('id', 'ticket/1'), ('Queue', 'General'), ('Owner', 'Nobody'), ('Creator', 'pyrtkit'), ('Subject', 'pyrt-create4'), ('Status', 'open'), ('Priority', '5'), ('InitialPriority', '0'), ('FinalPriority', '0'), ('Requestors', ''), ('Cc', ''), ('AdminCc', ''), ('Created', 'Sun Jul 03 10:48:57 2011'), ('Starts', 'Not set'), ('Started', 'Not set'), ('Due', 'Not set'), ('Resolved', 'Not set'), ('Told', 'Wed Jul 06 12:58:00 2011'), ('LastUpdated', 'Thu Jul 07 14:42:32 2011'), ('TimeEstimated', '0'), ('TimeWorked', '25 minutes'), ('TimeLeft', '0'), ]], status_int=200, status='200 Ok', req_body='', req_headers=self.req_headers_get, ) self.assertGet( body='''RT/3.8.10 200 Ok id: ticket/1 Queue: General Owner: Nobody Creator: pyrtkit Subject: pyrt-create4 Status: open Priority: 5 InitialPriority: 0 FinalPriority: 0 Requestors: Cc: AdminCc: Created: Sun Jul 03 10:48:57 2011 Starts: Not set Started: Not set Due: Not set Resolved: Not set Told: Wed Jul 06 12:58:00 2011 LastUpdated: Thu Jul 07 14:42:32 2011 TimeEstimated: 0 TimeWorked: 25 minutes TimeLeft: 0 ''', expected=expected, ) def test_read_tkt_notfound(self): expected = Expected( parsed=[], status_int=404, status='404 Ticket 1 does not exist', req_body='', req_headers=self.req_headers_get, ) self.assertGet( body='RT/3.8.10 200 Ok\n\n# Ticket 1 does not exist.\n\n\n', expected=expected, ) def test_read_tkt_credentials(self): expected = Expected( parsed=[], status_int=401, status='401 Credentials required', req_body='', req_headers=self.req_headers_get, ) self.assertGet( body='RT/3.8.10 401 Credentials required\n', expected=expected, ) def test_update_tkt_syntax_error(self): self.req_headers_post.update({'content-length': '16'}) expected = Expected( parsed=[[('queue', 'You may not create requests in that queue.')]], status_int=409, status='409 Syntax Error', req_body='content=Queue: 3', req_headers=self.req_headers_post, ) self.assertPost( body='RT/3.8.10 409 Syntax Error\n\n# queue: You may not create requests in that queue.\n\n', expected=expected, content={'content': {'Queue': 3, }} ) def test_tkt_comment_with_attach(self): self.req_headers_post.update({ 'content-length': '760', 'content-type': 'multipart/form-data; boundary=xXXxXXyYYzzz', }) expected = Expected( parsed=[[]], status_int=200, status='200 Ok', req_body='--xXXxXXyYYzzz\r\nContent-Disposition: form-data; name="content"\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: 77\r\n\r\nAction: comment\nText: Comment with attach\nAttachment: x1.txt, x2.txt, 1x1.gif\r\n--xXXxXXyYYzzz\r\nContent-Disposition: form-data; name="attachment_2"; filename="rtkit/tests/attach/x2.txt"\r\nContent-Type: text/plain\r\nContent-Length: 15\r\n\r\nHello World!\n2\n\r\n--xXXxXXyYYzzz\r\nContent-Disposition: form-data; name="attachment_1"; filename="rtkit/tests/attach/x1.txt"\r\nContent-Type: text/plain\r\nContent-Length: 15\r\n\r\nHello World!\n1\n\r\n--xXXxXXyYYzzz\r\nContent-Disposition: form-data; name="attachment_3"; filename="rtkit/tests/attach/1x1.gif"\r\nContent-Type: image/gif\r\nContent-Length: 35\r\n\r\nGIF87a\x01\x00\x01\x00\x80\x00\x00\xcc\xcc\xcc\x96\x96\x96,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;\r\n--xXXxXXyYYzzz--\r\n', req_headers=self.req_headers_post, ) self.assertPost( body='RT/3.8.10 200 Ok\n\n# Message recorded\n\n', expected=expected, content={ 'content': { 'Action': 'comment', 'Text': 'Comment with attach', 'Attachment': 'x1.txt, x2.txt, 1x1.gif', }, 'attachment_1': file('rtkit/tests/attach/x1.txt'), 'attachment_2': file('rtkit/tests/attach/x2.txt'), 'attachment_3': file('rtkit/tests/attach/1x1.gif'), } ) def test_read_tkt_comment(self): expected = Expected( parsed=[[ ('id', '2831'), ('Ticket', '216'), ('TimeTaken', '0'), ('Type', 'Create'), ('Field', ''), ('OldValue', ''), ('NewValue', ''), ('Data', ''), ('Description', 'Ticket created by john.foo'), ('Content', 'this is a\nmultiline\nticket'), ('Creator', 'john.foo'), ('Created', '2013-02-14 18:00:45'), ('Attachments', '\n1315: untitled (38b)') ]], status_int=200, status='200 Ok', req_body='', req_headers=self.req_headers_get, ) self.assertGet( body='''RT/4.0.5-116-g591e06a 200 Ok # 2/2 (id/2831/total) id: 2831 Ticket: 216 TimeTaken: 0 Type: Create Field: OldValue: NewValue: Data: Description: Ticket created by john.foo Content: this is a multiline ticket Creator: john.foo Created: 2013-02-14 18:00:45 Attachments: 1315: untitled (38b) ''', expected=expected, )
#!/usr/bin/python #RT Ticket Creator by smelendy@umw v0.3 from rtkit.resource import RTResource from rtkit.authenticators import CookieAuthenticator from rtkit.errors import RTResourceError from rtkit import set_logging import logging import csv import getpass set_logging('debug') logger = logging.getLogger('rtkit') filecsv = raw_input("Please enter name of CSV file: ") user = getpass.getuser() passwd = getpass.getpass() resource = RTResource('http://localhost/REST/1.0/', user , passwd , CookieAuthenticator) with open(filecsv) as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for row in readCSV: content = { 'content': { 'Queue': ('%s' % row[0]), 'Subject': ('%s' % row[1]), 'Text': ('%s' % row[2]), 'Requestors': ('%s' % row[3]), 'Cc': ('%s' % row[4]), 'AdminCc' : ('%s' % row[5]), 'Owner': ('%s' % row[6]), 'Starts': ('%s' % row[7]), 'Due': ('%s' % row[8]), 'CF.{Jira Request}': ('%s' % row[9]), }
class TktTestCase(unittest.TestCase): def setUp(self): self.resource = RTResource('http://rtkit.test/', None, None, AbstractAuthenticator) self.content = { 'content': { 'Queue': 1, 'Subject': 'New Ticket', 'Text': 'My useless\ntext on\nthree lines.', } } self.req_body = 'content=Queue: 1\nText: My useless\n text on\n three lines.\nSubject: New Ticket' self.req_headers_get = { 'connection': 'close', 'user-agent': 'rtkit-ua', 'host': 'rtkit.test', 'accept': 'text/plain', 'accept-encoding': 'identity', } self.req_headers_post = self.req_headers_get.copy() self.req_headers_post.update({ 'content-length': '76', 'content-type': 'application/x-www-form-urlencoded; charset=utf-8', }) @httprettified def test_http_error(self): HTTPretty.register_uri(HTTPretty.GET, 'http://rtkit.test/:GET:', status=404, body='Not Found') response = self.resource.get(':GET:', headers={ 'User-Agent': 'rtkit-ua', }) self.assertEqual(response.parsed, [[]]) self.assertEqual(response.status_int, 500) self.assertEqual(response.status, 'Not Found') @httprettified def assertPost(self, body, expected, content=None): HTTPretty.register_uri(HTTPretty.POST, 'http://rtkit.test/:POST:', body=body) response = self.resource.post(path=':POST:', payload=content or self.content, headers={ 'User-Agent': 'rtkit-ua', }) self.assertEqual(response.parsed, expected.parsed) self.assertEqual(response.status_int, expected.status_int) self.assertEqual(response.status, expected.status) self.assertEqual(HTTPretty.last_request.method, HTTPretty.POST) self.assertEqual(HTTPretty.last_request.path, '/:POST:') self.assertEqual(HTTPretty.last_request.body, expected.req_body) self.assertEqual(dict(HTTPretty.last_request.headers), expected.req_headers) @httprettified def assertGet(self, body, expected): HTTPretty.register_uri(HTTPretty.GET, 'http://rtkit.test/:GET:', body=body) response = self.resource.get(path=':GET:', headers={ 'User-Agent': 'rtkit-ua', }) self.assertEqual(response.parsed, expected.parsed) self.assertEqual(response.status_int, expected.status_int) self.assertEqual(response.status, expected.status) self.assertEqual(HTTPretty.last_request.method, HTTPretty.GET) self.assertEqual(HTTPretty.last_request.path, '/:GET:') self.assertEqual(HTTPretty.last_request.body, expected.req_body) self.assertEqual(dict(HTTPretty.last_request.headers), expected.req_headers) def test_create_tkt(self): expected = Expected( parsed=[[('id', 'ticket/1')]], status_int=200, status='200 Ok', req_body=self.req_body, req_headers=self.req_headers_post, ) self.assertPost( body='RT/3.8.10 200 Ok\n\n# Ticket 1 created.\n\n', expected=expected, ) def test_create_tkt_noqueue(self): expected = Expected( parsed=[], status_int=400, status='400 Could not create ticket. Queue not set', req_body=self.req_body, req_headers=self.req_headers_post, ) self.assertPost( body= 'RT/3.8.10 200 Ok\n\n# Could not create ticket.\n# Could not create ticket. Queue not set\n\n', expected=expected, ) def test_create_tkt_noperm(self): expected = Expected( parsed=[], status_int=400, status= '400 No permission to create tickets in the queue \'___Admin\'', req_body=self.req_body, req_headers=self.req_headers_post, ) self.assertPost( body= 'RT/3.8.10 200 Ok\n\n# Could not create ticket.\n# No permission to create tickets in the queue \'___Admin\'\n\n', expected=expected, ) def test_read_tkt(self): expected = Expected( parsed=[[ ('id', 'ticket/1'), ('Queue', 'General'), ('Owner', 'Nobody'), ('Creator', 'pyrtkit'), ('Subject', 'pyrt-create4'), ('Status', 'open'), ('Priority', '5'), ('InitialPriority', '0'), ('FinalPriority', '0'), ('Requestors', ''), ('Cc', ''), ('AdminCc', ''), ('Created', 'Sun Jul 03 10:48:57 2011'), ('Starts', 'Not set'), ('Started', 'Not set'), ('Due', 'Not set'), ('Resolved', 'Not set'), ('Told', 'Wed Jul 06 12:58:00 2011'), ('LastUpdated', 'Thu Jul 07 14:42:32 2011'), ('TimeEstimated', '0'), ('TimeWorked', '25 minutes'), ('TimeLeft', '0'), ]], status_int=200, status='200 Ok', req_body='', req_headers=self.req_headers_get, ) self.assertGet( body='''RT/3.8.10 200 Ok id: ticket/1 Queue: General Owner: Nobody Creator: pyrtkit Subject: pyrt-create4 Status: open Priority: 5 InitialPriority: 0 FinalPriority: 0 Requestors: Cc: AdminCc: Created: Sun Jul 03 10:48:57 2011 Starts: Not set Started: Not set Due: Not set Resolved: Not set Told: Wed Jul 06 12:58:00 2011 LastUpdated: Thu Jul 07 14:42:32 2011 TimeEstimated: 0 TimeWorked: 25 minutes TimeLeft: 0 ''', expected=expected, ) def test_read_tkt_notfound(self): expected = Expected( parsed=[], status_int=404, status='404 Ticket 1 does not exist', req_body='', req_headers=self.req_headers_get, ) self.assertGet( body='RT/3.8.10 200 Ok\n\n# Ticket 1 does not exist.\n\n\n', expected=expected, ) def test_read_tkt_credentials(self): expected = Expected( parsed=[], status_int=401, status='401 Credentials required', req_body='', req_headers=self.req_headers_get, ) self.assertGet( body='RT/3.8.10 401 Credentials required\n', expected=expected, ) def test_update_tkt_syntax_error(self): self.req_headers_post.update({'content-length': '16'}) expected = Expected( parsed=[[('queue', 'You may not create requests in that queue.')]], status_int=409, status='409 Syntax Error', req_body='content=Queue: 3', req_headers=self.req_headers_post, ) self.assertPost( body= 'RT/3.8.10 409 Syntax Error\n\n# queue: You may not create requests in that queue.\n\n', expected=expected, content={'content': { 'Queue': 3, }}) def test_tkt_comment_with_attach(self): self.req_headers_post.update({ 'content-length': '760', 'content-type': 'multipart/form-data; boundary=xXXxXXyYYzzz', }) expected = Expected( parsed=[[]], status_int=200, status='200 Ok', req_body= '--xXXxXXyYYzzz\r\nContent-Disposition: form-data; name="content"\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: 77\r\n\r\nAction: comment\nText: Comment with attach\nAttachment: x1.txt, x2.txt, 1x1.gif\r\n--xXXxXXyYYzzz\r\nContent-Disposition: form-data; name="attachment_2"; filename="rtkit/tests/attach/x2.txt"\r\nContent-Type: text/plain\r\nContent-Length: 15\r\n\r\nHello World!\n2\n\r\n--xXXxXXyYYzzz\r\nContent-Disposition: form-data; name="attachment_1"; filename="rtkit/tests/attach/x1.txt"\r\nContent-Type: text/plain\r\nContent-Length: 15\r\n\r\nHello World!\n1\n\r\n--xXXxXXyYYzzz\r\nContent-Disposition: form-data; name="attachment_3"; filename="rtkit/tests/attach/1x1.gif"\r\nContent-Type: image/gif\r\nContent-Length: 35\r\n\r\nGIF87a\x01\x00\x01\x00\x80\x00\x00\xcc\xcc\xcc\x96\x96\x96,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;\r\n--xXXxXXyYYzzz--\r\n', req_headers=self.req_headers_post, ) self.assertPost(body='RT/3.8.10 200 Ok\n\n# Message recorded\n\n', expected=expected, content={ 'content': { 'Action': 'comment', 'Text': 'Comment with attach', 'Attachment': 'x1.txt, x2.txt, 1x1.gif', }, 'attachment_1': file('rtkit/tests/attach/x1.txt'), 'attachment_2': file('rtkit/tests/attach/x2.txt'), 'attachment_3': file('rtkit/tests/attach/1x1.gif'), }) def test_read_tkt_comment(self): expected = Expected( parsed=[[('id', '2831'), ('Ticket', '216'), ('TimeTaken', '0'), ('Type', 'Create'), ('Field', ''), ('OldValue', ''), ('NewValue', ''), ('Data', ''), ('Description', 'Ticket created by john.foo'), ('Content', 'this is a\nmultiline\nticket'), ('Creator', 'john.foo'), ('Created', '2013-02-14 18:00:45'), ('Attachments', '\n1315: untitled (38b)')]], status_int=200, status='200 Ok', req_body='', req_headers=self.req_headers_get, ) self.assertGet( body='''RT/4.0.5-116-g591e06a 200 Ok # 2/2 (id/2831/total) id: 2831 Ticket: 216 TimeTaken: 0 Type: Create Field: OldValue: NewValue: Data: Description: Ticket created by john.foo Content: this is a multiline ticket Creator: john.foo Created: 2013-02-14 18:00:45 Attachments: 1315: untitled (38b) ''', expected=expected, )
def test_rtrc(self): resource = RTResource.from_rtrc(auth=BasicAuthenticator, filename='rtkit/tests/rtrc/right.txt') self.assertEqual(resource.auth.username, 'RT_USERNAME') self.assertEqual(resource.auth.password, 'RT_PASSWORD') self.assertEqual(resource.auth.url, 'http://rt.server//REST/1.0/')
return False, size except Exception as e: print e return False, -1 from rtkit.resource import RTResource from rtkit.authenticators import CookieAuthenticator from rtkit.errors import RTResourceError from rtkit import set_logging import logging #set_logging('info') logger = logging.getLogger('rtkit') resource = RTResource(rt_url, rt_user, rt_pass, CookieAuthenticator) def close_ticket(id): print "Closing investigation %s" % id ticketpath = 'ticket/%s' % id content = { 'content': { 'Status': 'resolved', } } response = resource.post( path=ticketpath, payload=content, ) logger.info(response.parsed)
config.get('rt', 'last_fetched_timestamp')) except: logger.warn('Unable to parse feed timestamp - Defaulting to: ' + rt_format_ticket_time(stored_last_updated_activity) + ' UTC') syslog.syslog( syslog.LOG_WARNING, 'Unable to parse feed timestamp - Defaulting to: ' + rt_format_ticket_time(stored_last_updated_activity) + ' UTC') # Initialize web services # Source RT Feed resource = None feed = None try: resource = RTResource(config.get('rt', 'api_url_prefix'), config.get('rt', 'username'), config.get('rt', 'password'), CookieAuthenticator) feed = resource.get(path=config.get('rt', 'api_search_suffix')) except RTResourceError as e: logger.error('Cannot connect to RT server') syslog.syslog(syslog.LOG_ERR, 'Cannot connect to RT server') logger.error(e.response.status_int) syslog.syslog(syslog.LOG_ERR, e.response.status_int) logger.error(e.response.status) syslog.syslog(syslog.LOG_ERR, e.response.status) logger.error(e.response.parsed) syslog.syslog(syslog.LOG_ERR, e.response.parsed) sys.exit(1) except: logger.error('Cannot connect to RT server') syslog.syslog(syslog.LOG_ERR, 'Cannot connect to RT server')
import sys import logging from rtkit.resource import RTResource from rtkit.authenticators import BasicAuthenticator from rtkit.errors import RTResourceError from rtkit import set_logging set_logging("debug") logger = logging.getLogger("rtkit") resource = RTResource("http://rt.cla.umn.edu/REST/1.0/", sys.argv[1], sys.argv[2], BasicAuthenticator) try: response = resource.get( path="search/ticket?query=Owner=%s&user=%s&pass=%s" % (sys.argv[1], sys.argv[1], sys.argv[2]) ) for r in response.parsed: for t in r: logger.info(t) except RTResourceError as e: logger.error(e.response.status_int) logger.error(e.response.status) logger.error(e.response.parsed)
class RTTickets(object): """Container class for RTTickets""" def __init__(self, url, usr, pwd): self.__url = url self.__resource = RTResource(url + 'REST/1.0/', usr, pwd, CookieAuthenticator) def get_all_tickets(self): """Returns all the tickets""" try: query = ( "Queue%3D'SOC'%20OR%20Queue%3D'Investigations'%20OR%20Queue%3D'" + "Notifications'%20OR%20Queue%3D'Informations'%20OR%20Queue%3D'" + "Sub-Incidents'") response = self.__resource.get(path='search/ticket?query=' + query) ticket_list = list() if len(response.parsed) > 0: for text_list in response.parsed: for ticket_id, ticket_title in text_list: ticket = Ticket(ticket_id) ticket.url = ( self.__url + '/Ticket/Display.html?id=' + unicode(ticket_id, 'utf-8', errors='replace')) ticket.title = unicode(ticket_title, 'utf-8', errors='replace') ticket_list.append(ticket) return ticket_list else: raise NoResponseException('Nothing found!') except RTResourceError as error: raise NoResponseException(error) def get_ticket_by_id(self, identifier): """Returns a ticket with the given identifier""" try: response = self.__resource.get(path='/ticket/' + identifier + '/show') if len(response.parsed) > 0: rsp_dict = {} for resp in response.parsed: for tick in resp: rsp_dict[tick[0]] = unicode(tick[1], 'utf-8', errors='replace') ticket = Ticket(identifier) ticket.url = self.__url + '/Ticket/Display.html?id=' + identifier ticket.title = unicode(rsp_dict['Subject'], 'utf-8', errors='replace') ticket.queue = unicode(rsp_dict['Queue'], 'utf-8', errors='replace') ticket.owner = unicode(rsp_dict['Owner'], 'utf-8', errors='replace') ticket.creator = unicode(rsp_dict['Creator'], 'utf-8', errors='replace') ticket.status = unicode(rsp_dict['Status'], 'utf-8', errors='replace') ticket.requestors = unicode(rsp_dict['Requestors'], 'utf-8', errors='replace') ticket.created = unicode(rsp_dict['Created'], 'utf-8', errors='replace') ticket.last_updated = unicode(rsp_dict['LastUpdated'], 'utf-8', errors='replace') # froen mech waat daat mecht? if 'Resolved' in rsp_dict: ticket.resolved = rsp_dict['Resolved'] else: raise NoResponseException('Nothing found!') except RTResourceError as error: raise NoResponseException(error) def get_base_ticket_url(self): """Returns the base url of RT""" return self.__url + '/Ticket/Display.html?id='
def setUp(self): self.resource = RTResource("http://rtkit.test/", "USER", "PASS", QueryStringAuthenticator)
def __init__(self, url, usr, pwd): self.__url = url self.__resource = RTResource(url + 'REST/1.0/', usr, pwd, CookieAuthenticator)
def create_rt_from_pr(self, sender, subject, body, queue, gh_repo_full_name, gh_pr): full_rt_url = str(self.get_request_tracker_url()) + '/REST/1.0/' rt_sender = self.get_rt_sender(self.rt_use_generic_sender, self.rt_generic_sender, sender, self.rt_sender_email_domain) resource = RTResource(full_rt_url, self.rt_username, self.rt_password, CookieAuthenticator) content = { 'content': { 'id': 'ticket/new', 'Queue': queue, 'Subject' : subject, 'Requestor': rt_sender, 'CF-X-Hub-PR': gh_pr, 'CF-X-Hub-Repo': gh_repo_full_name, 'Text' : body.replace('\n', '\n '), } } response = None try: response = resource.post(path='ticket/new', payload=content,) except RTResourceError as e: error_msg = str(e.response.status_int) + '\n' error_msg += str(e.response.status) + '\n' error_msg += str(e.response.parsed) + '\n' log.error(error_msg) raise ValueError(error_msg) if response.status_int != 200: error_msg = 'HTTP status ' + str(response.status_int) + ' when attempting to contact ' + str(full_rt_url) + '\n' error_msg += str(response.status) + '\n' error_msg += str(response.parsed) + '\n' log.error(error_msg) raise ValueError(error_msg) # RT returns a 200 (indicating the ticket was created) yet something # else went wrong. Sometimes related to the custom field name being # nonexistent or the RT user not having enough permission to read/set # this field value. # Note that response.parsed is a nested list of tuples, # e.g. [[('id', 'ticket/587034')]] try: _tup = response.parsed[0][0] rt_ticket_number = _tup[1].replace('ticket/','') log.info('Successfully created RT "' + str(subject) + '" from PR initiated by ' + str(rt_sender)) log.info('URL: ' + str(self.get_request_tracker_url()) + '/Ticket/Display.html?id=' + str(rt_ticket_number)) log.info(response.parsed) return rt_ticket_number except IndexError, e: error_msg = 'Something went wrong when attempting to create the RT!\n' error_msg += 'Received: ' + str(response.body) + '\n' log.error(error_msg) raise ValueError(error_msg)
def form_valid(self, form): # initialize rt connection rt = RTResource(settings.RT_URL, settings.RT_USER, settings.RT_PW, BasicAuthenticator) results = [] for contact in form.cleaned_data["recipients"]: result = {} result["contact"] = contact # now compose the mail and send it as rt answer tmpl = contact.template ctx_dict = { "rcpt" : contact } message = render_to_string(tmpl.templateName, ctx_dict) # create response resp_data = { "content" : { "Action" : "correspond", "Text" : message.encode("utf8"), "Status" : "stalled", } } # handle attachments if len(tmpl.attachments.all()) > 0: attId = 1 names = [] for att in tmpl.attachments.all(): names.append(att.name) resp_data["attachment_{0}".format(attId)] = file(settings.ATTACHMENTS_ROOT + att.filepath) attId = attId + 1 resp_data["content"]["Attachment"] = ", ".join(names) # post it to rt # create a matching ticket data = { "content" : { "Queue" : settings.RT_QUEUE, "Owner" : settings.RT_TICKET_OWNER, "Subject" : contact.template.mailSubject, "Requestor" : (contact.contactPersonEmail if len(contact.contactPersonEmail) > 0 else contact.contactEMail), } } res = rt.post(path="ticket/new",payload=data) if res.status_int != 200: result["status"] = "failed" result["info"] = res.status results.append(result) continue tpath = None tid = None for k,v in res.parsed[0]: if k == "id": tpath = v break if tpath is None or tpath.find("/") < 0: result["status"] = "failed" result["info"] = "Answer contained no ticket id" results.append(result) continue else: tid = int(tpath.split("/")[1]) res = rt.post(path=(tpath + "/comment"),payload=resp_data) if res.status_int != 200: result["status"] = "failed" result["info"] = repr(res.parded) results.append(result) continue result["status"] = "ok" results.append(result) contact.lastMailed = datetime.date.today() contact.rtTicketId = tid contact.save() self.template_name = self.success_template_name return self.render_to_response(self.get_context_data(results=results))
def setUp(self): self.resource = RTResource('http://rtkit.test/', 'USER', 'PASS', BasicAuthenticator)
def check_url_create_investigation(incident, template, url, override, onlinecheck): mypath = os.path.dirname(os.path.realpath(sys.argv[0])) template = os.path.join(mypath, template) global ua global min_size global override_email global event_tag # RT set_logging('error') logger = logging.getLogger('rtkit') resource = RTResource(rt_url, rt_user, rt_pass, CookieAuthenticator) open_tickets = open_tickets_for_url(url) if open_tickets > 0: return "URL %s was already handled in ticket %s" % (url, open_tickets) if onlinecheck is True: online, size = is_online(url) if not online: return "URL %s is offline (size: %s)" % (url, size) with nostdout(): emails, text, asn = urlabuse.run_lookup(url) text = defang(urllib.quote(text)) d = {'details': text} try: f = open(template) subject = f.readline().rstrip() templatecontent = Template(f.read()) body = templatecontent.substitute(d) except: print "Couldn't open template file (%s)" % template sys.exit(1) f.close() if event_tag == "tlp:green": subject = "[TLP:GREEN] " + subject # Override emails destinations for test if override is True: emails = override_email asn_out = [] for x in asn: asn_out.append(",".join(x)) asn_out = "|".join(asn_out) subject = "%s (%s)" % (subject, asn_out) content = { 'content': { 'queue': 5, 'requestor': emails, 'subject': urllib.quote(subject), 'text': body, } } if debug: sys.exit(42) try: response = resource.post( path='ticket/new', payload=content, ) logger.info(response.parsed) for t in response.parsed: ticketid = t[0][1] except RTResourceError as e: logger.error(e.response.status_int) logger.error(e.response.status) logger.error(e.response.parsed) #update ticket link content = { 'content': { 'memberof': incident, } } try: ticketpath = "%s/links" % ticketid response = resource.post( path=ticketpath, payload=content, ) logger.info(response.parsed) return "Investigation created for URL %s" % (url) except RTResourceError as e: logger.error(e.response.status_int) logger.error(e.response.status) logger.error(e.repoinse.parsed)
'Subject': trigger_name, 'Text': desc, 'Priority': priorities[severity], 'CF.{Hosts}': ','.join(hosts), 'CF.{Items}': ','.join(items), 'CF.{Trigger}': trigger_name } } print(event_url) links = { 'content': { 'RefersTo': '{}'.format(event_url) } } rt = RTResource(api_url, 'root', 'password', CookieAuthenticator) ticket = rt.post(path='ticket/new', payload=ticket_content,) (label,ticket_id) = ticket.parsed[0][0] refers = rt.post(path=ticket_id + '/links', payload=links,) event_id = re.findall(r'eventid=(\d+)', event_url)[0] ticket_url = rt_url + 'Ticket/Display.html?id=' + ticket_id.split('/')[1] print(ticket_url) zh = ZabbixAPI('http://localhost/zabbix') zh.login(user='******', password='******') ack_message = 'Ticket created.\n' + ticket_url zh.event.acknowledge(eventids=event_id, message=ack_message)
def setUp(self): self.resource = RTResource("http://rtkit.test/", "USER", "PASS", BasicAuthenticator)
request.add_header('User-agent', ua) response = urllib2.urlopen(request) size = len(response.read()) if int(size) > min_size: return True, size else: return False, size except Exception as e: print e return False, -1 # RT set_logging('error') logger = logging.getLogger('rtkit') resource = RTResource(rt_url, rt_user, rt_pass, CookieAuthenticator) # Sphinx client = sphinxapi.SphinxClient() client.SetServer(sphinx_server, sphinx_port) client.SetMatchMode(2) def is_ticket_open(id): status = False try: ticket = "ticket/%s" % id response = resource.get(path=ticket) for r in response.parsed: l = {a: b for a, b in r} ticket_status = l["Status"]