Ejemplo n.º 1
0
    def test_config_parameter(self):
        # rstrip test
        conn2 = pyrfc.Connection(config={'rstrip': False},
                                 **config._sections['connection'])
        hello = u'Hällo SAP!' + u' ' * 245
        result = conn2.call('STFC_CONNECTION', REQUTEXT=hello)
        self.assertEqual(result['ECHOTEXT'], hello,
                         "Test with rstrip=False (input length=255 char)")
        result = conn2.call('STFC_CONNECTION', REQUTEXT=hello.rstrip())
        self.assertEqual(result['ECHOTEXT'], hello,
                         "Test with rstrip=False (input length=10 char)")
        conn2.close()

        # return_import_params
        result = self.conn.call('STFC_CONNECTION', REQUTEXT=hello)
        with self.assertRaises(KeyError):
            imp_var = result['REQUTEXT']
        conn3 = pyrfc.Connection(config={'return_import_params': True},
                                 **config._sections['connection'])
        result = conn3.call('STFC_CONNECTION', REQUTEXT=hello.rstrip())
        imp_var = result['REQUTEXT']
        conn3.close()
Ejemplo n.º 2
0
 def test_call_over_closed_connection(self):
     conn = pyrfc.Connection(config={"rstrip": False}, **config_sections["coevi51"])
     conn.close()
     assert conn.alive == False
     hello = u"Hällo SAP!"
     try:
         result = conn.call("STFC_CONNECTION", REQUTEXT=hello)
     except pyrfc.RFCError as ex:
         print(ex.args)
         assert (
             ex.args[0]
             == "Remote function module STFC_CONNECTION invocation rejected because the connection is closed"
         )
Ejemplo n.º 3
0
 def test_incomplete_params(self):
     incomplete_params = params.copy()
     for p in ['ashost', 'gwhost', 'mshost']:
         if p in incomplete_params:
             del incomplete_params[p]
     try:
         pyrfc.Connection(**incomplete_params)
     except pyrfc.RFCError as ex:
         error = get_error(ex)
     assert error['code'] == 20
     assert error['key'] == 'RFC_INVALID_PARAMETER'
     assert error['message'][0] in ['Parameter ASHOST, GWHOST, MSHOST or SERVER_PORT is missing.',
                  'Parameter ASHOST, GWHOST or MSHOST is missing.']
Ejemplo n.º 4
0
 def __init__(self):
     self.config = ReadConfig(host="127.0.0.1")
     self.conn = None
     while self.conn is None:
         try:
             self.conn = pyrfc.Connection(
                 ashost=self.config.get("ahost"),
                 sysnr=self.config.get("sysnr"),
                 client=self.config.get("client"),
                 user=self.config.get("rfcuser")["username"],
                 passwd=self.config.get("rfcuser")["passwd"])
         except pyrfc._exception.CommunicationError as e:
             continue
         except Exception as e:
             raise Exception(str(e))
Ejemplo n.º 5
0
def getData(sapConnection):
    conn_bw = pyrfc.Connection(ashost=sapConnection.ashost,
                               sysnr=sapConnection.sysnr,
                               client=sapConnection.client,
                               user=sapConnection.user,
                               passwd=sapConnection.passwd)

    T_ZCHAIN_AF_INFO = ''
    T_ZCHAIN_AF_LOG = ''
    chain_monitor_rfc = conn_bw.call('ZCHAIN_MONITOR',
                                     I_LOG_DATE=getYesterday(),
                                     T_ZCHAIN_AF_INFO=T_ZCHAIN_AF_INFO)

    conn_bw.close()
    return chain_monitor_rfc['T_ZCHAIN_AF_INFO']
Ejemplo n.º 6
0
 def test_incomplete_params(self):
     incomplete_params = params.copy()
     for p in ["ashost", "gwhost", "mshost"]:
         if p in incomplete_params:
             del incomplete_params[p]
     try:
         pyrfc.Connection(**incomplete_params)
     except pyrfc.RFCError as ex:
         error = get_error(ex)
     assert error["code"] == 20
     assert error["key"] == "RFC_INVALID_PARAMETER"
     assert error["message"][0] in [
         "Parameter ASHOST, GWHOST, MSHOST or SERVER_PORT is missing.",
         "Parameter ASHOST, GWHOST or MSHOST is missing.",
     ]
Ejemplo n.º 7
0
 def setup_method(self, test_method):
     """ A connection to an SAP backend system
           Instantiating an :class:`pyrfc.Connection` object will
           automatically attempt to open a connection the SAP backend.
           :param config: Configuration of the instance. Allowed keys are:
                 ``dtime``
                   returns datetime types (accepts strings and datetimes), default is False
                 ``rstrip``
                   right strips strings returned from RFC call (default is True)
                 ``return_import_params``
                   importing parameters are returned by the RFC call (default is False)
           :type config: dict or None (default)
     """
     self.conn = pyrfc.Connection(**params)
     assert self.conn.alive
Ejemplo n.º 8
0
def read_table():
    conn = pyrfc.Connection(**conn_params)

    option_parameter = [{"TEXT": "COUNTRYFR EQ 'US' "}]

    result = conn.call('RFC_READ_TABLE',
                       QUERY_TABLE="SPFLI",
                       DELIMITER=",",
                       OPTIONS=option_parameter)

    # 获取 FIELDS 表参数
    fields = tablib.Dataset()
    fields.dict = result['FIELDS']
    print(fields)

    # 获取 DATA 标参数
    data = tablib.Dataset()
    data.dict = result['DATA']
    print(data)
Ejemplo n.º 9
0
 def test_many_connections(self):
     # If too many connections are established, the following error will occur (on interactive python shell)
     #
     #CommunicationError: Error 1: [RFC_COMMUNICATION_FAILURE]
     #LOCATION    CPIC (TCP/IP) on local host with Unicode
     #ERROR       max no of 100 conversations exceeded
     #TIME        Tue Sep 18 11:09:35 2012
     #RELEASE     720
     #COMPONENT   CPIC (TCP/IP) with Unicode
     #VERSION     3
     #RC          466
     #MODULE      r3cpic_mt.c
     #LINE        14345
     #COUNTER     1
     # ABAP:
     for i in range(150):
         conn2 = pyrfc.Connection(**params)
         conn2.close(
         )  # Use explicit close() here. If ommitted, the server may block an open connection attempt
Ejemplo n.º 10
0
def rfcCall(sapConnection, item):
    try:
        conn_bw = pyrfc.Connection(ashost=sapConnection.ashost,
                                   sysnr=sapConnection.sysnr,
                                   client=sapConnection.client,
                                   user=sapConnection.user,
                                   passwd=sapConnection.passwd)

        result = conn_bw.call(item['rfcName'],
                              I_LOGID=item['LOG_ID'],
                              I_CHAIN=item['CHAIN_ID'],
                              I_TYPE=item['TYPE'],
                              I_VARIANT=item['VARIANTE'],
                              I_INSTANCE=item['INSTANCE'],
                              I_JOB_COUNT=item['JOB_COUNT'])
        conn_bw.close()
    except Exception as e:
        print(e)
        return '{"error": "' + str(e) + '"}'
    else:
        return result
Ejemplo n.º 11
0
def run_error():
    for method in methods:
        for messagetype in messagetypes:
            with pyrfc.Connection(**params_connection) as connection:
                ex = None
                try:
                    print "Call RFC_RAISE_ERROR with METHOD={} / MESSAGETYPE={}".format(
                        method, messagetype),
                    connection.call("RFC_RAISE_ERROR",
                                    METHOD=str(method),
                                    MESSAGETYPE=messagetype)
                    raise RFCError("No error occured.")
                except RFCError as e:
                    ex = e
                alive = True
                try:
                    connection.call("RFC_PING")
                except ExternalRuntimeError as ert:
                    alive = False
                except CommunicationError as ce:
                    print "<CommErr>",
                    alive = False
                print "... alive={}".format(alive)
                result["{}_{}".format(method, messagetype)] = (ex, alive)
Ejemplo n.º 12
0
 def test_no_connection_params(self):
     try:
         pyrfc.Connection()
     except pyrfc.RFCError as ex:
         assert ex.args[0] == "Connection parameters missing"
Ejemplo n.º 13
0
 def setup_method(self, test_method):
     self.conn = pyrfc.Connection(**params)
     assert self.conn.alive
Ejemplo n.º 14
0
import pyrfc

from rfc_connection.qcb import user, passwd, ashost, sysnr, client

rfcConnection = pyrfc.Connection(ashost=ashost,
                                 sysnr=sysnr,
                                 client=client,
                                 user=user,
                                 passwd=passwd)
print("SAP RFC [QCB] connected.")


def getData():
    conn_bw = rfcConnection

    T_ZCHAIN_AF_INFO = ''
    T_ZCHAIN_AF_LOG = ''
    chain_monitor_rfc = conn_bw.call('ZCHAIN_MONITOR',
                                     I_LOG_DATE='20190401',
                                     T_ZCHAIN_AF_INFO=T_ZCHAIN_AF_INFO)
    return chain_monitor_rfc['T_ZCHAIN_AF_INFO']


def rfcCall(rfcName, item):
    conn_bw = rfcConnection
    result = conn_bw.call(rfcName,
                          I_LOGID=item['LOG_ID'],
                          I_CHAIN=item['CHAIN_ID'],
                          I_TYPE=item['TYPE'],
                          I_VARIANT=item['VARIANTE'],
                          I_INSTANCE=item['INSTANCE'],
Ejemplo n.º 15
0
 def __init__(self):
     self.conn = pyrfc.Connection(ashost=ASHOST,
                                  sysnr=SYSNR,
                                  client=CLIENT,
                                  user=USER,
                                  passwd=PASSWD)
Ejemplo n.º 16
0
import pyrfc
'''

important urls:

http://www.alexbaker.me/code/python-and-sap-part-1-connecting-to-sap
http://sap.github.io/PyRFC/client.html
https://github.com/SAP/PyRFC

'''

ASHOST = '10.58.5.229'
CLIENT = '200'
SYSNR = '01'
USER = '******'
PASSWD = 'Abcd1234'
SAPROUTER = ''

with pyrfc.Connection(ashost=ASHOST, sysnr=SYSNR, client=CLIENT, \
                        user=USER, passwd=PASSWD, saprouter=SAPROUTER) as conn:
    result = conn.call('STFC_CONNECTION', REQUTEXT=u'Hello SAP!')
    print(result)
Ejemplo n.º 17
0
struct_name = u'ZHHS_COL2'
field_name = u'COL3'


def get_structure(con):
    type_desc = con.type_desc_get(struct_name)
    return any(field['name'] == field_name for field in type_desc.fields)


def function_call(con):
    table = con.call(function_name)['EX_ZHHT_COL2']
    struct = table[0]
    return field_name in struct.keys()


def invalidate(con):
    con.func_desc_remove(connection_info['sysid'], function_name)
    con.type_desc_remove(connection_info['sysid'], table_name)
    con.type_desc_remove(connection_info['sysid'], struct_name)
    #con.reset_server_context()
    #con.type_desc_remove('DSP', type_name)
    #con.reopen()


if __name__ == '__main__':
    c1 = pyrfc.Connection(**connection_info)
    print 'STRUCTURE', get_structure(c1)  #, 'RFC', function_call(c1)
    raw_input('Structure changed now. Press Enter to continue...')
    invalidate(c1)
    print 'STRUCTURE', get_structure(c1)  #, 'RFC', function_call(c1)
Ejemplo n.º 18
0
    def login(self):
        lang = str(self.entry_lang.get())
        mshost = str(self.entry_msgsrvr.get())
        sysid = str(self.entry_system.get())
        group = str(self.entry_group.get())
        client = str(self.entry_client.get())
        snc_ptnr = str(self._entry_snc_partnername.get())
        #SSO or supply user id's
        if self._checkbutton_onoff.get() == 0:
            #Non SSO
            user = str(self.entry_user.get())
            passwd = str(self.entry_pw.get())
            params = {
                'client': client,
                'user': user,
                'passwd': passwd,
                'lang': lang,
                'mshost': mshost,
                'sysid': sysid,
                'group': group
            }
        else:
            #SSO: SNC_PARTNERNAME is obtained from table SNCSYSACL. SNC_LIB is oobtained by nwrfclib from system environment variable SNC_LIB
            params = {
                'client': client,
                'snc_partnername': snc_ptnr,
                'lang': lang,
                'mshost': mshost,
                'sysid': sysid,
                'group': group
            }

        try:
            #Login to SAP
            SAP_conn = pyrfc.Connection(**params)
            #Store last used values for later use
            conn = sqlite3.connect(self._parent_gui.get_ini_db_name())
            c = conn.cursor()
            c.execute(
                "INSERT OR REPLACE INTO SETTINGS (KEY, VALUE) VALUES (?,?)",
                ('CLIENT', str(self.entry_client.get())))
            c.execute(
                "INSERT OR REPLACE INTO SETTINGS (KEY, VALUE) VALUES (?,?)",
                ('LANGU', str(self.entry_lang.get())))
            c.execute(
                "INSERT OR REPLACE INTO SETTINGS (KEY, VALUE) VALUES (?,?)",
                ('MSG_SERVER', str(self.entry_msgsrvr.get())))
            c.execute(
                "INSERT OR REPLACE INTO SETTINGS (KEY, VALUE) VALUES (?,?)",
                ('SYSTEM', str(self.entry_system.get())))
            c.execute(
                "INSERT OR REPLACE INTO SETTINGS (KEY, VALUE) VALUES (?,?)",
                ('GROUP', str(self.entry_group.get())))
            c.execute(
                "INSERT OR REPLACE INTO SETTINGS (KEY, VALUE) VALUES (?,?)",
                ('SNC_PARTNERNAME', str(self._entry_snc_partnername.get())))
            conn.commit()
            conn.close()
            #Pass back the SAP object to parent GUI
            self._parent_gui.set_SAP_connection(SAP_conn)
            self._publisher.dispatch(
                "information",
                "SAP login to " + sysid + '\\' + client + ' successful')
            self._publisher.dispatch("system", sysid + '\\' + client)
            #Finish up
            self.destroy()
            return

        except (LogonError) as e:
            tk.messagebox.showerror(
                'Error',
                'Unable to login to SAP' + '\n' + e.key + ' : ' + e.message)
            #self._parent_gui.set_SAP_connection(None)
            return
Ejemplo n.º 19
0
 def setUpClass(cls):
     cls.conn = pyrfc.Connection(**config._sections['connection'])
Ejemplo n.º 20
0
def function_call():
    with pyrfc.Connection(**connection_info) as con:
        return con.call(function_name)
Ejemplo n.º 21
0
def check(cfg_entry):
    global conn
    conn = pyrfc.Connection(ashost=cfg_entry['ashost'],
                            sysnr=cfg_entry['sysnr'],
                            client=cfg_entry['client'],
                            user=cfg_entry['user'],
                            passwd=cfg_entry['passwd'],
                            loglevel=cfg_entry['loglevel'],
                            lang=cfg_entry['lang'])
    login()

    logs = {}  # type: Dict[str, Dict[str, List]]
    sap_data = {}  # type: Dict[str, List]

    # This loop is used to collect all information from SAP
    for ms_name, mon_name in mon_list(cfg_entry):
        path = ms_name + SEPARATOR + mon_name
        if not to_be_monitored(path, True):
            continue

        tree = mon_tree(cfg_entry, ms_name, mon_name)
        for node in tree:
            if not to_be_monitored(node['PATH']):
                continue
            #sys.stdout.write("%s\n" % node["PATH"])

            status_details = ''  # type: Union[str, Tuple[str, Any]]
            perfvalue = '-'
            uom = '-'

            # Use precalculated states
            state = {
                'VALUE': node['ACTUALVAL'],
                'SEVERITY': node['ACTUALSEV'],
            }

            if state['VALUE'] not in STATE_VALUE_MAP:
                sys.stdout.write('UNHANDLED STATE VALUE\n')
                sys.exit(1)

            #
            # Handle different object classes individually
            # to get details about them
            #

            if monitor_types and node['MTCLASS'] not in monitor_types:
                continue  # Skip unwanted classes if class filtering is enabled

            if node['MTCLASS'] == MTE_PERFORMANCE:
                perfvalue, this_uom = mon_perfdata(cfg_entry, node)
                uom = this_uom if this_uom else uom

            elif node['MTCLASS'] == MTE_SINGLE_MSG:
                status_details = "%s: %s" % mon_msg(cfg_entry, node)

            elif node['MTCLASS'] == MTE_MSG_CONTAINER:

                alerts = mon_alerts(cfg_entry, node)
                logs = process_alerts(cfg_entry, logs, ms_name, mon_name, node,
                                      alerts)
                if len(alerts) > 0:
                    last_alert = alerts[-1]
                    dt = parse_dt(last_alert["ALERTDATE"],
                                  last_alert["ALERTTIME"])
                    alert_state, alert_msg = alert_details(
                        cfg_entry, last_alert)
                    last_msg = '%s: %s - %s' % (dt, STATE_VALUE_MAP[
                        alert_state['VALUE']][1], alert_msg)

                    status_details = '%d Messages, Last: %s' % (len(alerts),
                                                                last_msg)
                else:
                    status_details = 'The log is empty'

            elif node['MTCLASS'] not in SKIP_MTCLASSES:
                # Add an error to output on unhandled classes
                status_details = "UNHANDLED MTCLASS", node['MTCLASS']

            if node['MTCLASS'] not in SKIP_MTCLASSES:
                sid = node["MTSYSID"].strip() or 'Other'
                context = node["MTMCNAME"].strip() or 'Other'
                path = node["PATH"]

                sap_data.setdefault(sid, [])
                sap_data[sid].append(
                    "%s\t%d\t%3d\t%s\t%s\t%s\t%s" %
                    (context, state['VALUE'], state['SEVERITY'], path,
                     perfvalue, uom, status_details))

    for host, host_sap in sap_data.items():
        sys.stdout.write('<<<<%s%s>>>>\n' %
                         (cfg_entry.get("host_prefix", ""), host))
        sys.stdout.write('<<<sap:sep(9)>>>\n')
        sys.stdout.write('%s\n' % '\n'.join(host_sap))
    sys.stdout.write('<<<<>>>>\n')

    for host, host_logs in logs.items():
        sys.stdout.write('<<<<%s>>>>\n' % host)
        sys.stdout.write('<<<logwatch>>>\n')
        for log, lines in host_logs.items():
            sys.stdout.write('[[[%s]]]\n' % log)
            if lines:
                sys.stdout.write('\n'.join(lines) + '\n')
        sys.stdout.write('<<<<>>>>\n')

    logout()
    conn.close()
Ejemplo n.º 22
0
def invalidate():
    with pyrfc.Connection(**connection_info) as con:
        con.func_desc_remove(connection_info['sysid'], function_name)
        con.type_desc_remove(connection_info['sysid'], table_name)
        con.type_desc_remove(connection_info['sysid'], struct_name)
Ejemplo n.º 23
0
 def test_collect(self):
     self.engine.get_user_connection(user, passwd)
     poolsize_pre = self.engine._size
     normal_conn = pyrfc.Connection(user=user, passwd=passwd, **params)
     self.engine.collect(user, normal_conn)
     self.assertEqual(poolsize_pre + 1, self.engine._size)
Ejemplo n.º 24
0
    def test_str(self):
        conn = pyrfc.Connection()

        ssl_storage = SSLCertStorage(conn, 'STR', 'TEST')
        self.assertEquals(str(ssl_storage), 'SSL Storage STR/TEST')
Ejemplo n.º 25
0
def get_sap_connection(sap_logon_params):
    conn = pyrfc.Connection(**sap_logon_params)

    return conn
Ejemplo n.º 26
0
 def __init__(self, ASHOST, SYSNR, CLIENT, USER, PASSWD, SAPROUTER):
     self.conn = pyrfc.Connection(ashost=ASHOST, sysnr=SYSNR, client=CLIENT,
                                  user=USER, passwd=PASSWD, saprouter=SAPROUTER);
Ejemplo n.º 27
0
def dest_connection():
    conn = pyrfc.Connection(**conn_params)
    result = conn.call("STFC_CONNECTION", REQUTEXT="hello SAP")

    print(result["ECHOTEXT"])
        filename = u'/home/local/X5/olga.guzeva/logs/' + queue_params['I_QUEUENAME'] + '_' + datetime.now().strftime('%Y%m%d') + '_log.log', level = logging.INFO)

    # Подключение к HDFS
    client = hdfs.Config().get_client('dev')

    logging.info('************Start program************')

    print_params()
    
    # загружаем конфиг с параметрами для подключения
    config = configparser.ConfigParser()
    config.read('/home/local/X5/olga.guzeva/cfg/sapnwrfc.cfg')
    cfg_sap = config['SAP_ER1']
    
    # Устанавливаем коннект и печатаем статус
    conn = pyrfc.Connection(**cfg_sap)
    result = conn.call('STFC_CONNECTION', REQUTEXT='Hello SAP!')
    logging.info(result)
    logging.info('Connaction alive = ' + str(conn.alive))
    
    # Получаем структуру возвращаемого датасета
    # logging.info(datetime.now())
    logging.info('Getting details...')
    details = get_details()
    
    # Открываем очередь
    # logging.info(datetime.now())
    logging.info('Openning queue...')
    open_result = open_queue()
    
    # DataFrame будет хранить строки для записи в один файл размером с блок на Hadoop
Ejemplo n.º 29
0
 def setUpClass(cls):
     # print "Os cwd", os.getcwd()
     # print "Config", config
     ## print config._sections.items()
     cls.conn = pyrfc.Connection(**config._sections['connection'])
Ejemplo n.º 30
0
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 26 09:15:05 2017

@author: kvan
"""

import pyrfc
#import Connection
conn = pyrfc.Connection(ashost='10.0.0.1',
                        sysnr='00',
                        client='100',
                        user='******',
                        passwd='secret')