Esempio n. 1
0
def connect():
    global qmgr
    conn_info = '%s(%s)' % (args.host, args.port)
    if (not args.use_client_auth and not args.use_ssl):
        qmgr = pymqi.connect(args.queue_manager, args.channel, conn_info)
    elif (args.use_client_auth and not args.use_ssl):
        qmgr = pymqi.connect(args.queue_manager, args.channel, conn_info,
                             args.username, args.password)
    elif (args.use_ssl):
        cd = pymqi.CD()
        cd.ChannelName = bytes(args.channel, encoding='utf8')
        cd.ConnectionName = bytes(conn_info, encoding='utf8')
        cd.ChannelType = pymqi.CMQC.MQCHT_CLNTCONN
        cd.TransportType = pymqi.CMQC.MQXPT_TCP
        cd.SSLCipherSpec = bytes(args.cipherspec, encoding='utf8')
        sco = pymqi.SCO()
        sco.KeyRepository = bytes(args.server_cert, encoding='utf8')
        qmgr = pymqi.QueueManager(None)
        if (not args.use_client_auth):
            qmgr.connect_with_options(args.queue_manager, cd=cd, sco=sco)
        else:
            qmgr.connect_with_options(args.queue_manager,
                                      cd=cd,
                                      sco=sco,
                                      user=bytes(args.username,
                                                 encoding='utf8'),
                                      password=bytes(args.password,
                                                     encoding='utf8'))
    print("connection succesful")
Esempio n. 2
0
 def test_connect_without_credentials(self):
     """ Connecting without user credentials provided should not succeed.
     """
     try:
         pymqi.connect(self.name, self.channel, "{}({})".format(self.host, self.port))
     except pymqi.MQMIError, e:
         if e.reason == CMQC.MQRC_NOT_AUTHORIZED:
             pass  # That's OK, we actually expect it
         else:
             raise
Esempio n. 3
0
 def test_connect_without_credentials(self):
     """ Connecting without user credentials provided should not succeed.
     """
     try:
         pymqi.connect(self.name, self.channel,
                       '{}({})'.format(self.host, self.port))
     except pymqi.MQMIError, e:
         if e.reason == CMQC.MQRC_NOT_AUTHORIZED:
             pass  # That's OK, we actually expect it
         else:
             raise
Esempio n. 4
0
def get_normal_connection(config):
    """
    Get the connection either with a username and password or without
    """
    if config.username and config.password:
        log.debug("connecting with username and password")
        queue_manager = pymqi.connect(
            config.queue_manager_name, config.channel, config.host_and_port, config.username, config.password
        )
    else:
        log.debug("connecting without a username and password")
        queue_manager = pymqi.connect(config.queue_manager_name, config.channel, config.host_and_port)

    return queue_manager
Esempio n. 5
0
def check_wmq():
    queue_manager = ''
    channel = ''
    host = ''
    port = ''
    queue_name = ''
    conn_info = '%s(%s)' % (host, port)
    user = ''
    password = '******'

    #pega hora da conexão
    now = datetime.now()
    timestamp = datetime.timestamp(now)
    try:
        #faz a conexão com a fila
        qmgr = pymqi.connect(queue_manager, channel, conn_info, user, password)
        queue = pymqi.Queue(qmgr, queue_name)
        qmgr.disconnect()

        arq = open(path + 'log_check_wmq_cal_sendlistedequitytocal_inp.csv',
                   'a')
        arq.write('%s;%s;conectado;status ok;\n' %
                  (re.match("(\d+).(\d+)", str(timestamp)).group(1),
                   re.match("([\d\-\s:]+).(\d+)", str(now)).group(1)))
        arq.close
    except Exception as erro:
        arq = open(path + 'log_check_wmq_cal_sendlistedequitytocal_inp.csv',
                   'a')
        arq.write('%s;%s;erro;%s;\n' %
                  (re.match("(\d+).(\d+)", str(timestamp)).group(1),
                   re.match("([\d\-\s:]+).(\d+)", str(now)).group(1), erro))
        arq.close
    def __init__(self):

        conn_info = '%s(%s)' % (host, port)
        self.qmgr = pymqi.connect(queue_manager, channel, conn_info)
        self.get_queue = pymqi.Queue(self.qmgr, queue_name)
        gqdesc = od(ObjectName=queue_name)
        self.browse_q = Queue(self.qmgr, gqdesc, CMQC.MQOO_BROWSE)
Esempio n. 7
0
def consume():
    conn_info = "%s(%s)" % (common.HOST, common.PORT)

    qmgr = pymqi.connect(common.QUEUE_MANAGER, common.CHANNEL, conn_info,
                         common.USERNAME, common.PASSWORD)

    queue = pymqi.Queue(qmgr, common.QUEUE)

    range = 10

    for i in zrange(range):
        try:
            message = queue.get()
            print("got a new message: {}".format(message))
        except Exception as e:
            if not re.search("MQRC_NO_MSG_AVAILABLE", e.errorAsString()):
                print(e)
                queue.close()
                qmgr.disconnect()
                return
            else:
                pass

    queue.close()
    qmgr.disconnect()
Esempio n. 8
0
def submit(queue_data):
    queue_dict = json.loads(queue_data)
    machine_id = queue_dict['machine_id']
    message_type = queue_dict['machine_type']
    token = queue_dict['token']
    qmgr = pymqi.connect('qmr', 'CLIENT.QM_ORANGE', 'machine_ip_port')
    que = pymqi.Queue(qmgr, machine_id)
Esempio n. 9
0
def func2(num):
    now_time = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')[:-3]
    # print (time.asctime())
    start_time = time.time()
    line = """any text
	"""

    req_id = uuid4().hex

    " ***************** QA1 Env *****************"
    host = "your host name for queue manager"
    port = "port name for queue manager"
    channel = "channel name foe queue manager 01N"
    queue_manager = "queue manager name.MQ"
    queue_name = "request queue where you want to send a message"
    " *******************************************"

    conn_info = "%s(%s)" % (host, port)
    qmgr = pymqi.connect(queue_manager, channel, conn_info)
    queue = pymqi.Queue(qmgr, queue_name)
    queue.put(formated_line)

    queue.close()
    qmgr.disconnect()
    total_time = int((time.time() - start_time) * 1000)
    events.request_success.fire(request_type='transaction name',
                                name='request',
                                response_time=total_time,
                                response_length=0)
Esempio n. 10
0
def name():
    """
        Discover a queue managers name.
    """

    try:

        if not mqstate.channel:
            click.secho(
                'No channel provided, defaulting to SYSTEM.DEF.SVRCONN',
                dim=True)
            mqstate.channel = 'SYSTEM.DEF.SVRCONN'

        qmgr = pymqi.connect(queue_manager='',
                             channel=mqstate.channel,
                             conn_info=mqstate.get_host())
        qmgr_name = qmgr.inquire(pymqi.CMQC.MQCA_Q_MGR_NAME)

        click.secho(f'Queue Manager name: {mq_string(qmgr_name)}', fg='green')
        qmgr.disconnect()

    except pymqi.MQMIError as ce:

        # Some other error condition.
        raise ce
Esempio n. 11
0
def connect(recv_mq):
    qmgr = pymqi.connect(recv_mq["recv_queue_manager"],
                         recv_mq["recv_channel"],
                         recv_mq["ip"] + "(" + str(recv_mq["port"]) + ")",
                         "username", "password")
    global queue
    queue = pymqi.Queue(qmgr, recv_mq["recv_queue"])
 def start_manager_connection(self):
     queue_manager = self.conn_details.get('queue_manager')
     channel = self.conn_details.get('channel')
     host = self.conn_details.get('host')
     port = self.conn_details.get('port')
     conn_info = '%s(%s)' % (host, port)
     return pymqi.connect(queue_manager, channel, conn_info)
Esempio n. 13
0
def probe_mq(mgr: str,
             channel: str,
             queue_name: str,
             host: str = None,
             port: str = None,
             action: str = "put_get",
             number_of_messages: int = 1,
             configuration: Configuration = None) -> int:
    """
    Probe to test MQ via putting and getting random messages
        "probes": [
            {
                "type": "probe",
                "name": "Check the a MQ is running",
                "tolerance": 0,
                "provider": {
                    "type": "python",
                    "module": "ibmcloud.middleware.probes",
                    "func": "probe_mq",
                    "arguments": {
                        "mgr": "HAEXAMPLE",
                        "channel": "HAQMCH",
                        "queue_name":"EXAMPLE.QUEUE",
                        "action": "put"
                        "number_of_messages": 1
                    }
                }
            }
        ]
    attr mgr str: queue manager name
    attr channel str: channel name
    attr host str: host name IP or Hostname
    attr port str: Port number to be passed as string
    attr queue_name str : Queue name it must be created before running this test
    attr action str: put/get/put_get
    attr number_of_messages int: number of messages to be sent
    :return: number of errors
    """
    _host = None
    _port = None
    if configuration is None:
        _host = host
        _port = port
    else:
        _host = configuration['mq_host'] if host is None else host
        _port = configuration['mq_port'] if port is None else port
    qmgr = pymqi.connect(mgr, channel, '%s(%s)' % (_host, _port))
    if action == "put" or action == "put_get":
        putq = pymqi.Queue(qmgr, queue_name)
        for _ in range(number_of_messages):
            putq.put('Hello from Python!')
        putq.close()

    if action == "get" or action == "put_get":
        getq = pymqi.Queue(qmgr, 'EXAMPLE.QUEUE')
        for _ in range(number_of_messages):
            getq.get()
        getq.close()
    return 0
Esempio n. 14
0
 def test_successful_connect_without_optional_credentials(self):
     """Connecting without user credentials should succeed for a queue
     manager that has optional user/password connection authentication. 
     """
     qmgr = pymqi.connect(self.name, self.channel,
                          '{}({})'.format(self.host, self.port))
     self.assertTrue(qmgr.is_connected)
     qmgr.disconnect()
Esempio n. 15
0
 def test_successful_connect_without_optional_credentials(self):
     """Connecting without user credentials should succeed for a queue
     manager that has optional user/password connection authentication. 
     """
     qmgr = pymqi.connect(self.name, self.channel, '{}({})'.format(
             self.host, self.port))
     self.assertTrue(qmgr.is_connected)
     qmgr.disconnect()
Esempio n. 16
0
def channels(prefix):
    """
        Show channels.
    """

    mqstate.validate(['host', 'port', 'channel'])

    args = {pymqi.CMQCFC.MQCACH_CHANNEL_NAME: str(prefix)}
    qmgr = pymqi.connect(mqstate.qm_name, mqstate.channel, mqstate.get_host(),
                         mqstate.username, mqstate.password)
    pcf = pymqi.PCFExecute(qmgr)

    try:

        click.secho(
            'Showing channels with prefix: \'{0}\'...\n'.format(prefix),
            dim=True)
        response = pcf.MQCMD_INQUIRE_CHANNEL(args)

    except pymqi.MQMIError as sce:

        if sce.comp == pymqi.CMQC.MQCC_FAILED and sce.reason == pymqi.CMQC.MQRC_UNKNOWN_OBJECT_NAME:
            click.secho('No channels matched prefix [%s]'.format(prefix),
                        fg='red')

        else:
            raise sce

    else:

        t = get_table_handle([
            'Name',
            'Type',
            'MCA UID',
            'Conn Name',
            'Xmit Queue',
            'Description',
            'SSL Cipher',
        ])

        for channel_info in response:
            t.append_row([
                channel_info.get(pymqi.CMQCFC.MQCACH_CHANNEL_NAME, '').strip(),
                channel_type_to_name(
                    channel_info.get(pymqi.CMQCFC.MQIACH_CHANNEL_TYPE)),
                channel_info.get(pymqi.CMQCFC.MQCACH_MCA_USER_ID, ''),
                channel_info.get(pymqi.CMQCFC.MQCACH_CONNECTION_NAME,
                                 '').strip(),
                channel_info.get(pymqi.CMQCFC.MQCACH_XMIT_Q_NAME, '').strip(),
                channel_info.get(pymqi.CMQCFC.MQCACH_DESC, '').strip(),
                # channel_info.get(pymqi.CMQCFC.MQCACH_PASSWORD, '(unknown)').strip(),
                channel_info.get(pymqi.CMQCFC.MQCACH_SSL_CIPHER_SPEC,
                                 '').strip(),
                # channel_info.get(pymqi.CMQCFC.MQCACH_SSL_PEER_NAME, '').strip(),
            ])
        click.secho(t.get_string())

    qmgr.disconnect()
Esempio n. 17
0
def execute(cmd, args, service_name, wait):
    """
        Execute an arbitrary command.

        \b
        Examples:
            python punch-q.py command execute -c /bin/ping -a "-c 1 192.168.0.1"
            python punch-q.py -C pq.yml command execute --cmd "/bin/ping" --args "-c 5 192.168.0.8" --wait 8
    """

    # Generate a service name if none was provided
    if not service_name:
        service_name = uuid.uuid4()

    # Cleanup the service name to remove spaces and dashes and limit to 16 chars
    service_name = str(service_name).replace('-', '').replace(' ', '')[0:16]

    # information
    click.secho('Cmd: {0}'.format(cmd), bold=True)
    click.secho('Arg: {0}'.format(args), bold=True)
    click.secho('Service Name: {0}\n'.format(service_name))

    qmgr = pymqi.connect(mqstate.qm_name, mqstate.channel, mqstate.get_host(),
                         mqstate.username, mqstate.password)

    # create the service
    click.secho('Creating service...', dim=True)
    args = {
        pymqi.CMQC.MQCA_SERVICE_NAME: service_name,
        pymqi.CMQC.MQIA_SERVICE_CONTROL: pymqi.CMQC.MQSVC_CONTROL_MANUAL,
        pymqi.CMQC.MQIA_SERVICE_TYPE: pymqi.CMQC.MQSVC_TYPE_COMMAND,
        pymqi.CMQC.MQCA_SERVICE_START_COMMAND: str(cmd),
        pymqi.CMQC.MQCA_SERVICE_START_ARGS: str(args)
    }
    pcf = pymqi.PCFExecute(qmgr)
    pcf.MQCMD_CREATE_SERVICE(args)

    # start the service
    click.secho('Starting service...', fg='green')
    args = {pymqi.CMQC.MQCA_SERVICE_NAME: service_name}

    pcf = pymqi.PCFExecute(qmgr)
    pcf.MQCMD_START_SERVICE(args)

    click.secho('Giving the service {0} second(s) to live...'.format(wait),
                dim=True)
    time.sleep(wait)

    # delete service
    click.secho('Cleaning up service...', dim=True)
    args = {pymqi.CMQC.MQCA_SERVICE_NAME: service_name}

    pcf = pymqi.PCFExecute(qmgr)
    pcf.MQCMD_DELETE_SERVICE(args)

    qmgr.disconnect()

    click.secho('Done', fg='green')
Esempio n. 18
0
def ping():
    """
        Ping a queue manager.
    """

    mqstate.validate(['host', 'port'])

    qmgr = pymqi.connect(mqstate.qm_name, mqstate.channel, mqstate.get_host(),
                         mqstate.username, mqstate.password)

    pcf = pymqi.PCFExecute(qmgr)
    pcf.MQCMD_PING_Q_MGR()
    click.secho('Queue manager command server is responsive.', fg='green')

    # Attempt to determine the MQ command level.
    mq_params = pcf.MQCMD_INQUIRE_Q_MGR(
        {pymqi.CMQCFC.MQCMD_INQUIRE_SYSTEM: '*'})

    # Get the queue manager status
    mq_status = pcf.MQCMD_INQUIRE_Q_MGR_STATUS()[0]

    # A number of these are not in CMQC, so this comment is a reference:
    # MQCA_INSTALLATION_DESC: 2115
    # MQCA_INSTALLATION_NAME: 2116
    # MQCA_INSTALLATION_PATH: 2117
    # MQCACF_LOG_PATH: 3074
    # MQCACF_Q_MGR_START_DATE: 3175
    # MQCACF_Q_MGR_START_TIME: 3176

    click.secho('Queue Manager Status:', bold=True)
    click.secho('---------------------', bold=True)
    click.secho('Command Level:             {0}'.format(
        mq_params[0][pymqi.CMQC.MQIA_COMMAND_LEVEL]),
                bold=True)
    click.secho('Queue Manager Name:        {0}'.format(
        mq_status.get(pymqi.CMQC.MQCA_Q_MGR_NAME, '(unknown)')),
                bold=True)
    click.secho('Installation Name:         {0}'.format(
        mq_status.get(2116, '(unknown)')),
                bold=True)
    click.secho('Installation Path:         {0}'.format(
        mq_status.get(2117, '(unknown)')),
                bold=True)
    click.secho('Installation Description:  {0}'.format(
        mq_status.get(2115, '(unknown)')),
                bold=True)
    click.secho('Log Path:                  {0}'.format(
        mq_status.get(3074, '(unknown)')),
                bold=True)
    click.secho('Queue Manager Start Time:  {0}'.format(' '.join(
        [mq_status.get(3175, '').strip(),
         mq_status.get(3176, '').strip()])),
                bold=True)
    click.secho('\n')

    click.secho('Successfully queried queue manager status.', fg='green')

    qmgr.disconnect()
Esempio n. 19
0
 def test_connect_with_wrong_credentials(self):
     # Modify original valid password to some bogus value
     bogus_password = self.password + '_Wr0nG_Pa$$w0rd'
     with self.assertRaises(pymqi.MQMIError) as errorcontext:
         qmgr = pymqi.connect(self.name, self.channel, '{}({})'.format(
             self.host, self.port), self.user, bogus_password)
         exception = errorcontext.exception
         self.assertEqual(exception.reason, CMQC.MQRC_NOT_AUTHORIZED)
         self.assertFalse(qmgr.is_connected)
Esempio n. 20
0
 def __init__(cls, **kwargs):
     '''Create IBM MQ Connection'''
     keys = util.DICT2KEYS(kwargs, 'manager', 'channel', 'host', 'port',
                           'queue', 'user', 'pwd')
     queue_manager, channel, host, port, queue_name, user, password = keys
     conn_info = '%s(%s)' % (host, port)
     cls.qmgr = pymqi.connect(queue_manager, channel, conn_info, user,
                              password)
     cls.queue = pymqi.Queue(cls.qmgr, queue_name)
Esempio n. 21
0
 def test_connect_with_wrong_credentials(self):
     # Modify original valid password to some bogus value
     bogus_password = self.password + '_Wr0nG_Pa$$w0rd'
     with self.assertRaises(pymqi.MQMIError) as errorcontext:
         qmgr = pymqi.connect(self.name, self.channel,
                              '{}({})'.format(self.host, self.port),
                              self.user, bogus_password)
         exception = errorcontext.exception
         self.assertEqual(exception.reason, CMQC.MQRC_NOT_AUTHORIZED)
         self.assertFalse(qmgr.is_connected)
Esempio n. 22
0
def pop(queue, save_to, skip_confirmation):
    """
        Pop a message off the queue.
    """

    if not skip_confirmation:
        click.secho(
            'WARNING: This action will REMOVE the message from the selected queue!\n'
            +
            'Consider the --save-to flag to save the message you are about to pop.',
            fg='yellow')
        if not click.confirm('Are you sure?'):
            click.secho('Did not receive confirmation, bailing...')
            return

    qmgr = pymqi.connect(mqstate.qm_name, mqstate.channel, mqstate.get_host(),
                         mqstate.username, mqstate.password)

    try:

        queue = pymqi.Queue(qmgr, str(queue))
        request_md = pymqi.MD()
        message = queue.get(None, request_md)

    except pymqi.MQMIError as dme:

        if dme.comp == pymqi.CMQC.MQCC_FAILED and dme.reason == pymqi.CMQC.MQRC_NO_MSG_AVAILABLE:
            click.secho('No messages to pop from the queue.', fg='yellow')
            return

        else:
            raise dme

    t = get_table_handle(
        ['Date', 'Time', 'User', 'Format', 'App Name', 'Data'], markdown=False)
    t.append_row([
        mq_string(request_md.PutDate),
        mq_string(request_md.PutTime),
        mq_string(request_md.UserIdentifier),
        mq_string(request_md.Format),
        mq_string(request_md.PutApplName),
        mq_string(message),
    ])

    click.secho('')
    click.secho(t.get_string())

    # save to file if we got a file argument
    if save_to:
        save_to.write(message)
        click.secho(f'\nSaved message data to file: {save_to.name}',
                    fg='green')

    queue.close()
    qmgr.disconnect()
Esempio n. 23
0
    def test_failing_connect_without_required_credentials(self):
        """Connecting without user credentials provided should not succeed for
        a queue manager that requires user/password connection authentication.
        """

        with self.assertRaises(pymqi.MQMIError) as errorcontext:
            qmgr = pymqi.connect(self.name, self.channel,
                                 '{}({})'.format(self.host, self.port))
            exception = errorcontext.exception
            self.assertEqual(exception.reason, CMQC.MQRC_NOT_AUTHORIZED)
            self.assertFalse(qmgr.is_connected)
Esempio n. 24
0
    def get_connection(qmgr_name):
        servers=[{"qmgr":'TESTQM1', "channel":'SYSTEM.DEF.SVRCONN', "ip":"127.0.0.1(1414)"},
                 {"qmgr":'TESTQM2', "channel":'SYSTEM.DEF.SVRCONN', "ip":"127.0.0.1(1415)"},
                 {"qmgr":'TESTQM3', "channel":'SYSTEM.DEF.SVRCONN', "ip":"127.0.0.1(1416)"}]

        hit = filter(lambda x: x['qmgr'] == qmgr_name, servers)
        if len(hit):
            hit = hit[0]
            print "connecting to", qmgr_name
            try:
                conn = pymqi.connect(hit['qmgr'],hit['channel'],hit['ip'])
            except pymqi.MQMIError, e:
                if e.reason == CMQC.MQRC_CONNECTION_BROKEN:
                    print "Connection to qmgr broken attempting reconnect"
                    return pymqi.connect(hit['qmgr'],hit['channel'],hit['ip'])
                else:
                    print "Connection failed with ", e.reason
                    raise e
            print "successfully connected to", qmgr_name
            return conn
Esempio n. 25
0
def push(queue, source_file, source_string):
    """
        Push a message onto the queue.
    """

    if source_file is None and source_string is None:
        click.secho('Please provide either a source file or a source string.',
                    fg='red')
        return

    if source_file and source_string:
        click.secho(
            'Both a source file and string was specified. Only one is allowed.',
            fg='red')
        return

    if source_file:
        message = source_file.read()
    else:
        message = source_string.encode()

    click.secho(f'Pushing message onto queue: {queue}', dim=True)
    click.secho(f'Message (truncated): {message[:150]}', dim=True)

    qmgr = pymqi.connect(mqstate.qm_name, mqstate.channel, mqstate.get_host(),
                         mqstate.username, mqstate.password)

    try:

        put_mqmd = pymqi.MD()
        put_mqmd.Format = pymqi.CMQC.MQFMT_STRING

        # https://github.com/dsuch/pymqi/blob/master/code/examples/put_get_correl_id.py#L69-L71
        put_opts = pymqi.PMO(Options=pymqi.CMQC.MQPMO_NO_SYNCPOINT +
                             pymqi.CMQC.MQPMO_FAIL_IF_QUIESCING)

        mqqueue = pymqi.Queue(qmgr, str(queue))
        mqqueue.put(message, put_mqmd, put_opts)

    except pymqi.MQMIError as dme:

        # if we are not allowed to GET on this queue, mention that and quit
        if dme.comp == pymqi.CMQ.MQCC_FAILED and dme.reason == pymqi.CMQC.MQRC_PUT_INHIBITED:
            click.secho('PUT not allowed on queue with current credentials.',
                        fg='red')
            return

        else:
            raise dme

    mqqueue.close()
    qmgr.disconnect()

    click.secho('Message successfully pushed onto the queue.', fg='green')
Esempio n. 26
0
    def test_failing_connect_without_required_credentials(self):
        """Connecting without user credentials provided should not succeed for
        a queue manager that requires user/password connection authentication.
        """

        with self.assertRaises(pymqi.MQMIError) as errorcontext:
            qmgr = pymqi.connect(self.name, self.channel, '{}({})'.format(
                self.host, self.port))
            exception = errorcontext.exception
            self.assertEqual(exception.reason, CMQC.MQRC_NOT_AUTHORIZED)
            self.assertFalse(qmgr.is_connected)
Esempio n. 27
0
 def query_qmgr():
     global qmgr, pcf
     queue_manager = "QM01"
     channel = "CHANNEL.1"
     host = "127.0.0.1"
     port = "1434"
     conn_info = "%s(%s)" % (host, port)
     qmgr = pymqi.connect(queue_manager, channel, conn_info)
     pcf = pymqi.PCFExecute(qmgr)
     query_func()
     qmgr.disconnect()
def attempt_connect():
    try:
        queue_manager = 'QM1'
        channel = 'SYSTEM.ADMIN.SVRCONN'
        host = '127.0.0.1'
        port = '1414'
        conn_info = '%s(%s)' % (host, port)
        qmgr = pymqi.connect(queue_manager, channel, conn_info)
        qmgr.disconnect()
        print("Connection Successful " + newname)
    except Exception:
        print("Connection Failed " + newname)
Esempio n. 29
0
def send_mq(xml):
    '''
    @发送MQ方法
    '''
    try:
        #conf = config_all()
        qmgr = pymqi.connect(MQ_MANAGER, MQ_CHANNEL, MQ_IP(MQ_PORT))
        putq = pymqi.Queue(qmgr, MQ_LABEL)
        putq.put(xml)
        return 'MQ发送成功!'
    except Exception:
        return 'MQ发送失败,失败原因:%s' % traceback.format_exc()
Esempio n. 30
0
    def connect_with_credencials(self,
                                 user: str,
                                 pwd: str,
                                 qmgr: str = None,
                                 channel: str = None,
                                 host: str = None,
                                 port: int = None) -> int:
        """
        Connection to IBM MQ, using credentials.

        *Args:*\n
            _qmgr       - queue manager name;\n
            _channel    - channel for connection;\n
            _host       - host name for connection;\n
            _port       - port used for connection;\n
            _user       - user name for connection;\n
            _pwd        - user password for connection;\n

        *Returns:*\n
            Returns ID of the new connection. The connection is set as active.

        *Example:*\n
            | Connect With Credentials |  'QM1'  | 'DEV.APP.SVRCONN' |  '127.0.0.1' | '1414' | 'scott' | 'tiger'
        """

        try:
            if qmgr is None:
                qmgr = self.qmgr
            if channel is None:
                channel = self.channel
            if host is None:
                host = self.host
            if port is None:
                port = self.port

            print(
                '[PyMQI::connect_with_credencials]:: Connecting using : user=[',
                user, '], pwd=[', pwd, '], qmgr=[', qmgr, '], channel=[',
                channel, '], host=[', host, '], port=[', port, ']...')
            self.conn_info = '%s(%s)' % (host, port)
            self.connection = pymqi.connect(qmgr, channel, self.conn_info,
                                            user, pwd)
            print(
                '[PyMQI::connect_with_credencials]:: Connecting established successfully.'
            )
            print('')
            return 0

        except pymqi.MQMIError as err:
            raise Exception("[PyMQI::connect_with_credencials] Error:",
                            str(err))
Esempio n. 31
0
    def connect(self, user, password):
        """
        connect
		與IBM MQ Server建立連線。
        """
        pymqi.queue_manager = self.queue_manager
        pymqi.channel = self.channel
        pymqi.host = self.host
        pymqi.port = self.port
        pymqi.queue_name = self.queue_name
        pymqi.conn_info = self.conn_info
        self.user = user
        self.password = password
        self.qmgr = pymqi.connect(self.queue_manager, self.channel,
                                  self.conn_info, user, password)
Esempio n. 32
0
def ping():
    """
        Ping a queue manager.
    """

    mqstate.validate(['host', 'port', 'qm_name', 'channel'])

    qmgr = pymqi.connect(mqstate.qm_name, mqstate.channel, mqstate.get_host(),
                         mqstate.username, mqstate.password)

    pcf = pymqi.PCFExecute(qmgr)
    pcf.MQCMD_PING_Q_MGR()
    click.secho('Queue manager command server is responsive.', fg='green')

    # Attempt to determine the MQ command level.
    mq_params = pcf.MQCMD_INQUIRE_Q_MGR({pymqi.CMQCFC.MQCMD_INQUIRE_SYSTEM: '*'.encode()})

    # Get the queue manager status
    mq_status = pcf.MQCMD_INQUIRE_Q_MGR_STATUS()[0]

    # A number of these are not in CMQC.py, so
    # this comment is a reference from the C headers
    # resolving some of the constants.
    #
    # MQCA_INSTALLATION_DESC: 2115
    # MQCA_INSTALLATION_NAME: 2116
    # MQCA_INSTALLATION_PATH: 2117
    # MQCACF_LOG_PATH: 3074
    # MQCACF_Q_MGR_START_DATE: 3175
    # MQCACF_Q_MGR_START_TIME: 3176

    click.secho('Queue Manager Status:', bold=True)
    click.secho('---------------------', bold=True)
    click.secho(f'Command Level:             {mq_params[0][pymqi.CMQC.MQIA_COMMAND_LEVEL]}', bold=True)
    click.secho('Queue Manager Name:        ' +
                f'{mq_string(mq_status.get(pymqi.CMQC.MQCA_Q_MGR_NAME, "(unknown)"))}', bold=True)
    click.secho(f'Installation Name:         {mq_string(mq_status.get(2116, "(unknown)"))}', bold=True)
    click.secho(f'Installation Path:         {mq_string(mq_status.get(2117, "(unknown)"))}', bold=True)
    click.secho(f'Installation Description:  {mq_string(mq_status.get(2115, "(unknown)"))}', bold=True)
    click.secho(f'Log Path:                  {mq_string(mq_status.get(3074, "(unknown)"))}', bold=True)
    click.secho('Queue Manager Start Time:  ' +
                f'{mq_string(mq_status.get(3175, ""))} {mq_string(mq_status.get(3176, ""))}', bold=True)
    click.secho('\n')

    click.secho('Successfully queried queue manager status.', fg='green')

    qmgr.disconnect()
Esempio n. 33
0
def users(channel):
    """
        Discover users.

        This command attempts to brute force MQ users for a specific channel.
        The channel name itself is taken from this sub command, and not the
        global --channel flag used for configuration.
    """

    click.secho('Brute forcing users on channel: {0}'.format(channel))

    wordlist = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                            'wordlists/', 'mq_users.txt')

    with open(wordlist, 'r') as f:
        wordlist = f.readlines()

    # Iterate the word list we have
    for user in wordlist:

        username, password = user.strip().split(':')

        print(username + ':' + password)

        try:
            qmgr = pymqi.connect(mqstate.qm_name, channel, mqstate.get_host(),
                                 username, password)
            pcf = pymqi.PCFExecute(qmgr)
            pcf.MQCMD_PING_Q_MGR()

            click.secho('Combination "{0}:{1}" authenticated.'.format(
                username, password),
                        fg='green',
                        bold=True)

            qmgr.disconnect()

        except pymqi.MQMIError as ce:

            # unknown channel
            if ce.reason == pymqi.CMQC.MQRC_NOT_AUTHORIZED:
                continue

            # Some other error condition.
            raise ce
Esempio n. 34
0
    def connect_in_client_mode(self,
                               qmgr: str = None,
                               channel: str = None,
                               host: str = None,
                               port: int = None) -> int:
        """
        Connection to IBM MQ, using client mode.

        *Args:*\n
            _qmgr       - queue manager name;\n
            _channel    - channel for connection;\n
            _host       - host name for connection;\n
            _port       - port used for connection;\n

        *Returns:*\n
            Returns ID of the new connection. The connection is set as active.

        *Example:*\n
            | Connect In Client Mode  |  'QM1'  | 'DEV.APP.SVRCONN' |  '127.0.0.1' | '1414'
        """

        try:
            if qmgr is None:
                qmgr = self.qmgr
            if channel is None:
                channel = self.channel
            if host is None:
                host = self.host
            if port is None:
                port = self.port

            print(
                '[PyMQI::connect_in_client_mode]:: Connecting using : qmgr=[',
                qmgr, '], channel=[', channel, '], host=[', host, '], port=[',
                port, ']...')
            self.conn_info = '%s(%s)' % (host, port)
            self.connection = pymqi.connect(qmgr, channel, self.conn_info)
            print(
                '[PyMQI::connect_in_client_mode]:: Connecting established successfully.'
            )
            print('')
            return 0
        except pymqi.MQMIError as err:
            raise Exception("[PyMQI::connect_in_client_mode] Error:", str(err))
Esempio n. 35
0
def publish():
    conn_info = "%s(%s)" % (common.HOST, common.PORT)

    qmgr = pymqi.connect(common.QUEUE_MANAGER, common.CHANNEL, conn_info,
                         common.USERNAME, common.PASSWORD)

    queue = pymqi.Queue(qmgr, common.QUEUE)

    for i in range(10):
        try:
            message = 'Hello from Python! Message {}'.format(i)
            log.info("sending message: {}".format(message))
            queue.put(message.encode())
        except Exception as e:
            log.info("exception publishing: {}".format(e))
            queue.close()
            qmgr.disconnect()
            return

    queue.close()
    qmgr.disconnect()
    def _ibm_queue_configure(self, host, port, queue_manager, channel):
        """ To configure IBM Queue"""

        host = str(host)
        port = str(port)
        channel = str(channel)
        if not queue_manager:
            raise AssertionError(
                "queue_manager argument is required.!! Please check and pass queue_manager value"
            )
        if not channel:
            raise AssertionError(
                "channel argument is required.!! Please check and pass channel value"
            )
        conn_info = "%s(%s)" % (host, port)
        qmgr = None
        try:
            qmgr = pymqi.connect(queue_manager, channel, conn_info)
        except Exception as e:
            raise AssertionError("Exception : {}".format(e))
        return qmgr
Esempio n. 37
0
        queue_type = CMQC.MQQT_LOCAL
    elif queueTypeName == "alias":
        queue_type = CMQC.MQQT_ALIAS
    elif queueTypeName == "remote":
        queue_type = CMQC.MQQT_REMOTE
    elif queueTypeName == "cluster":
        queue_type = CMQC.MQQT_CLUSTER
    elif queueTypeName == "model":
        queue_type = CMQC.MQQT_MODEL
    args = {CMQC.MQCA_Q_NAME: prefix,
            CMQC.MQIA_Q_TYPE: queue_type,
            CMQCFC.MQIACF_Q_ATTRS: CMQCFC.MQIACF_ALL,}
 
    qmgr = None 
    try: 
        qmgr = pymqi.connect(qmgrName,channelName,"%s(%s)" % (hostName,portNumber))
        pcf = pymqi.PCFExecute(qmgr)
    
        response = pcf.MQCMD_INQUIRE_Q(args)
        for queue in response:
            queue_name = queue[CMQC.MQCA_Q_NAME]
            definition_type = queue.get(CMQC.MQIA_DEFINITION_TYPE,"all")
            usageType = queue.get(CMQC.MQIA_USAGE,"all")
            if (((definitionTypeName == "all") or 
             (definitionTypeName == "predefined" and definition_type == CMQC.MQQDT_PREDEFINED) or
             (definitionTypeName == "permanent_dynamic" and definition_type == CMQC.MQQDT_PERMANENT_DYNAMIC) or
             (definitionTypeName == "shared_dynamic" and definition_type == CMQC.MQQDT_SHARED_DYNAMIC) or
             (definitionTypeName == "temporary_dynamic" and definition_type == CMQC.MQQDT_TEMPORARY_DYNAMIC)) and
             ((usageTypeName == "all") or
             (usageTypeName == "normal" and usageType == CMQC.MQUS_NORMAL) or
             (usageTypeName == "transmission" and usageType == CMQC.MQUS_TRANSMISSION))):
Esempio n. 38
0
	def connect(self):
		print "Connecting to \t%s,\n QueueManagerName =\t%s,\n Channel =\t%s\n" % (self.connectionString, self.queue_manager, self.channel)
		self.qmgr = pymqi.connect(self.queue_manager, self.channel, self.connectionString)
Esempio n. 39
0
	putq.put(message)


if __name__ == "__main__":

	# TAOTODO: Read these settings from the conf
	qchannel		= None #'SYSTEM.DEF.SVRCONN'
	qmanager_name	= '*SMAINQM' #'QMA'
	qname 			= 'IVR.SERVICEREQUEST.RQ'#'Q1'
	qserver			= '10.2.16.71' #'localhost(1414)'

	# Set up connection
	print colored('Establishing connection','green')
	print colored('   server     : ','yellow') + qserver
	print colored('   queue mgr  : ','yellow') + qmanager_name
	print colored('   queue name : ','yellow') + qname
	qmgr = pymqi.connect(qmanager_name, qchannel, qserver)
	###qmgr = QueueManager(qmanager_name)
	
	# Now do something with the queue manager
	if len(sys.argv)>1:
		# push a message to the queue
		print colored("Pushing...","cyan")
		push_queue( qmgr, qname, ' '.join(sys.argv[2:]))
	else:
		print colored("Recieving...","cyan")
		print get_queue( qmgr, qname )

	# disconnect from the queue server
	pymqi.disconnect(qmgr)
import pymqi

qmgr = pymqi.connect('QM.1', 'SVRCONN.CHANNEL.1', '192.168.1.121(1434)')

getq = pymqi.Queue(qmgr, 'TESTQ.1')
print("Here's the message:", getq.get())
Esempio n. 41
0
 def connect(self):
     self.manager = pymqi.connect(self.queue_manager_name, self.channel_name, self.conn_info)
     for queue in self.queues_list:
         self._add_queue(queue)
Esempio n. 42
0
# See discussion and more examples at http://packages.python.org/pymqi/examples.html
# or in doc/sphinx/examples.rst in the source distribution.

import pymqi

queue_manager = "QM01"
channel = "SVRCONN.1"
host = "192.168.1.135"
port = "1434"
conn_info = "%s(%s)" % (host, port)

user = '******'
password = '******'

qmgr = pymqi.connect(queue_manager, channel, conn_info, user, password)
qmgr.disconnect()
Esempio n. 43
0
def main(argv):
    # MQ connection Variables            
    queue_manager = ''
    channel = ''
    host = ''
    port = ''
    file_loc = ''

    try:
        opts, args = getopt.getopt(argv, "hm:c:i:p:f:", ["qmgr=", "channel=", "host=", "port=", "fileloc="])
        if not opts:
            print ' '
            print '! There are missing arguements, the required inputs are:'
            print ' '
            print '  mqaut.exe -m <queue_manager> -c <channel> -i <hostname> -p <port> -f </file/path/to/aut.AUT>'
            sys.exit(2)
    except getopt.GetoptError:
        print ' '
        print '! There are missing arguements, the required inputs are:'
        print ' '
        print '  mqaut.exe -m <queue_manager> -c <channel> -i <hostname> -p <port> -f </file/path/to/aut.AUT>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print ' '
            print ' The required inputs are:'
            print ' '
            print ' mqaut.exe -m <queue_manager> -c <channel> -i <hostname> -p <port> -f </file/path/to/aut.AUT>'
            sys.exit()
        elif opt in ("-m", "--qmgr"):
            queue_manager = arg
        elif opt in ("-c", "--channel"):
            channel = arg
        elif opt in ("-i", "--host"):
            host = arg
        elif opt in ("-p", "--port"):
            port = arg
        elif opt in ("-f", "--fileloc"):
            file_loc = arg

    print '#---------------------------------------------------------#'
    print '#------------------ CONNECTION DETAILS -------------------#'
    print ' - Queue Manager: ', queue_manager
    print ' - Channel: ', channel
    print ' - Hostname: ', host
    print ' - Port: ', port
    print ' - File Path: ', file_loc
    print '#---------------------------------------------------------#'
    print ' '

    # connect to queue manager
    conn_info = "%s(%s)" % (host, port)
    # print ' - conn info: ', conn_info
    try:
        print '! Attempting Queue Manager Connection'
        qmgr = pymqi.connect(queue_manager, channel, conn_info)
    except pymqi.MQMIError, e:
        if e.comp == CMQC.MQCC_FAILED and e.reason == CMQC.MQRC_HOST_NOT_AVAILABLE:
            print ' !! Error in the provided connection details - hostname or port'
            print '  - completion code: ', e.comp
            print '  - reason code:', e.reason
            sys.exit(1)
        elif e.comp == CMQC.MQCC_FAILED and e.reason == CMQC.MQRC_Q_MGR_NAME_ERROR:
            print ' !! Error in provided queue manager name'
            print '  - completion code: ', e.comp
            print '  - reason code:', e.reason
            sys.exit(1)
        elif e.comp == CMQC.MQCC_FAILED and e.reason == CMQC.MQRC_UNKNOWN_CHANNEL_NAME:
            print ' !! Error in provided channel name'
            print '  - completion code: ', e.comp
            print '  - reason code:', e.reason
            sys.exit(1)
        else:
            print ' * an unexpected error occured, please check your connection details'
            print '  - completion code: ', e.comp
            print '  - reason code:', e.reason
            sys.exit(1)
Esempio n. 44
0
	def mq_connect(self):
		self.qmgr = pymqi.connect(self.queue_manager, self.channel, self.conn_info)
		return self.qmgr
Esempio n. 45
0
 def get_conn(self):
     return pymqi.connect(self.name, self.channel, "{}({})".format(self.host, self.port), self.user, self.password)
Esempio n. 46
0
# See discussion and more examples at http://packages.python.org/pymqi/examples.html
# or in doc/sphinx/examples.rst in the source distribution.

import pymqi
import CMQC

queue_manager = "QM01"
channel = "SVRCONN.1"
host = "192.168.1.135"
port = "1434"
queue_name = "TEST.1"
message = "Hello from Python!"
alternate_user_id = "myuser"
conn_info = "%s(%s)" % (host, port)

qmgr = pymqi.connect(queue_manager, channel, conn_info)

od = pymqi.OD()
od.ObjectName = queue_name
od.AlternateUserId = alternate_user_id

queue = pymqi.Queue(qmgr)
queue.open(od, CMQC.MQOO_OUTPUT | CMQC.MQOO_ALTERNATE_USER_AUTHORITY)
queue.put(message)

queue.close()
qmgr.disconnect()
Esempio n. 47
0
# See discussion and more examples at http://packages.python.org/pymqi/examples.html
# or in doc/sphinx/examples.rst in the source distribution.

import pymqi

queue_manager = "QM01"
qmgr = pymqi.connect(queue_manager)

qmgr.disconnect()
            portNumber = int(a)
        elif o in ("-a", "--channel-name-conn"):
            channelNameConn = a
        elif o in ("-t", "--channel-name"):
            channelNameTest = a
        else:
            assert False, "unhandled option"
    if not (hostName and portNumber and channelNameTest and qmgrName and channelNameConn):
        usage()
        exit_with_state(STATE_UNKNOWN)
#    if len(channelNameConn) > MQ_CHANNEL_NAME_LENGTH:
#        print "UNKNOWN - Channel name are too long."
    conn_info="%s(%s)" % (hostName,portNumber)
    global qmgr
    try:
        qmgr = pymqi.connect(qmgrName,channelNameConn,conn_info)
    except pymqi.MQMIError, e:
        print "UNKNOWN - unable to connect to Qmanager, reason: %s" % (e)
        exit_with_state(STATE_UNKNOWN)
    channel_name = ''
    try:
        pcf = pymqi.PCFExecute(qmgr)
        channel_names = pcf.MQCMD_INQUIRE_CHANNEL({CMQCFC.MQCACH_CHANNEL_NAME: channelNameTest})
        if channel_names[0]:
            channel_name = channel_names[0][CMQCFC.MQCACH_CHANNEL_NAME].rstrip()
            channel_type = channel_names[0][CMQCFC.MQIACH_CHANNEL_TYPE]
        else:
            print("CRITICAL - Channel %s does not exists." % (channelNameTest))
            exit_with_state(STATE_UNKNOWN)
    except pymqi.MQMIError,e :
        print("UNKNOWN - Can not list MQ channels. reason: %s" % (e))