SAP-FTP/SFTP, SXPG_CALL_SYSTEM, OPEN DATASET, CG3Y CG3Z

Function: SXPG_CALL_SYSTEM

With this function module, you can:
Check the permissions of the user to execute the command
Excuting an order
In order to determine on which system the command should be executed, the function module uses the current host system and the user’s current operating system type by default. Since the function module supports RFC, it is possible to use the RFC interface (Remote Function Call Interface) to run the function module in different SAP application servers. Then, execute the external command accordingly in the host system of another SAP server.
SXPG_CALL_SYSTEM checks the commands specified in the call before executing the call. If there is a command with the same OS type in the system field “SY-OPSYS”, it is executed with this definition. It checks for a command definition with the same OS type as in the system field sy-opsys. A syntax group is a SAP construct used to group operating systems that use the same syntax for commands and filenames. If a command’s operating system type matches an identified syntax group, the command’s definition is used.
If no matching definition is found for the syntax group, the function module searches for a definition with operating system type ANYOS (executable on all supported operating systems). If this definition is found, it is used.
Otherwise, exception COMMAND_NOT_FOUND will be triggered.

  • Upload and read files to SAP service

T-code: AL11

AL11 user_dir creation

Step 1: point configure

step 2, fill in relevant information and save


Note: There is a directory in AL11 that is recorded but does not actually exist. DIR_ZEROLI2 does not actually exist on the server. When we double-click it, an error message will be thrown.
When we use the open dataset statement to create a file in this directory, it will not succeed.

Create a folder on the server

  • Method 1: Create SM69 or SM49 with transaction code


Step 1: Create a command in SM69, support dos or unix command, save it first and then execute it, here is of course the command to create a folder, /c stands for command


Save it after creation, and you can view the result in t-code al11.

  • Method 2: Create in code

Call the system command with a function.

DATA: command1(64) TYPE c.
 
DATA: BEGIN OF tabl OCCURS 0,
        line(200),
       END OF tabl.
 
DATA: lt_string TYPE STANDARD TABLE OF string,
      lv_strin TYPE string.
 
COMMAND1(9) = 'mkdir -p '.
COMMAND1 + 9(55) = 'z_**********'.
 
CALL 'SYSTEM' ID 'COMMAND' FIELD COMMAND1
              ID 'TAB' FIELD TABL-*SYS*.
 
BREAK-POINT ID z_**********.

Open dataset permissions to access shared files (Windows)

Workgroup shared files

Step 1: Test environment: A machine Laoxiang: XP system (the machine where the shared folder is located); B machine Lupkid: Win7 system (the machine where the SAP gui is located); C machine Vmecc: Win2003 (VMware installed on B machine, and C machine is also SAP server).

Ensure that AB and AC can ping each other and AC can ping each other
Step 2: Test code:

TYPE-POOLS: z07tp.
 
DATA: gw_rec TYPE z07tp_rec,
      gt_rec TYPE STANDARD TABLE OF z07tp_rec.
 
CONSTANTS: cn_fname(8) TYPE c VALUE 'CUST07AD'.
 
CONSTANTS: cn_path(20) TYPE c VALUE '\Laoxiang\zerotest\'.
 
SELECTION-SCREEN BEGIN OF BLOCK blk1 WITH FRAME TITLE text-001.
PARAMETERS: pr_file(40) TYPE c.
SELECTION-SCREEN END OF BLOCK blk1.
 
INITIALIZATION.
  pr_file = cn_fname.
 
START-OF-SELECTION.
  CONCATENATE cn_path pr_file INTO pr_file.
  OPEN DATASET pr_file IN TEXT MODE FOR INPUT ENCODING DEFAULT.
  IF sy-subrc <> 0.
    WRITE: /text-002.
    EXIT.
  ENDIF.
  DO.
    READ DATASET pr_file INTO gw_rec.
    IF sy-subrc <> 0.
      EXIT.
    ENDIF.
    APPEND gw_rec TO gt_rec.
  ENDDO.
 
END-OF-SELECTION.
  CLOSE DATASET pr_file.
  

SFTP file transfer uses the function SXPG_COMMAND_LIST_GET in the program to execute external operation commands. The sample code is as follows (in the code, a selection box pops up to let the user choose which external command to use)

* &------------------------------------------- --------------------------*
* & Report ZTESTJI003
* &
* &---------------------------------------------- -----------------------*
* &
* &
* &---------------------------------------------- -----------------------*

REPORT ztestji003.

DATA: BEGIN OF command_list OCCURS 0.

        INCLUDE STRUCTURE sxpgcolist.

DATA: END OF command_list.

DATA: BEGIN OF exec_protocol OCCURS 0.

        INCLUDE STRUCTURE btcxpm.

DATA: END OF exec_protocol.

DATA: status LIKE btcxp3-exitstat,

      commandname LIKE sxpgcolist-name VALUE '*',

      sel_no LIKE sy-tabix.

* GET LIST OF EXTERNAL COMMANDS

CALL FUNCTION 'SXPG_COMMAND_LIST_GET'
  EXPORTING
    commandname = commandname
    operatingsystem = sy-opsys
  TABLES
    command_list = command_list
  EXCEPTIONS
    OTHERS = 1.

IF sy-subrc EQ 0.

  CALL FUNCTION 'POPUP_WITH_TABLE_DISPLAY'
    EXPORTING
      endpos_col = 100
      endpos_row = 20
      startpos_col = 2
      startpos_row = 2
      titletext = 'choose a COMMAND TO execute'
    IMPORTING
      choise = sel_no
    TABLES
      valuetab = command_list
    EXCEPTIONS
      break_off = 1
      OTHERS = 2.

  IF sy-subrc EQ 0.

    READ TABLE command_list INDEX sel_no.

* CHECK AUTHORIZATION

    CALL FUNCTION 'SXPG_COMMAND_CHECK'
      EXPORTING
        commandname = command_list-name
        operatingsystem = sy-opsys
      EXCEPTIONS
        no_permission = 1
        command_not_found = 2
        parameters_too_long = 3
        security_risk = 4
        wrong_check_call_interface = 5
        x_error = 6
        too_many_parameters = 7
        parameter_expected = 8
        illegal_command = 9
        communication_failure = 10
        system_failure = 11
        OTHERS = 12.

    CASE sy-subrc.

      WHEN 0.

        CALL FUNCTION 'SXPG_COMMAND_EXECUTE'
          EXPORTING
            commandname = command_list-name
          TABLES
            exec_protocol = exec_protocol
          EXCEPTIONS
            no_permission = 1
            command_not_found = 2
            parameters_too_long = 3
            security_risk = 4
            wrong_check_call_interface = 5
            program_start_error = 6
            program_termination_error = 7
            x_error = 8
            parameter_expected = 9
            too_many_parameters = 10
            illegal_command = 11
            wrong_asynchronous_parameters = 12
            cant_enq_tbtco_entry = 13
            jobcount_generation_error = 14
            OTHERS = 15.

        IF sy-subrc EQ 0.

          WRITE:/ command_list-name, 'ran successfully'.

        ELSE.

          WRITE:/ 'error WITH command', command_list-name.

        ENDIF.

      WHEN1.

        WRITE: /'you are NOT authorized TO run', command_list-name.

      WHEN OTHERS.

        WRITE: /'error with FUNCTION with command', command_list-name.

    ENDCASE.

  ENDIF.
  "popup_with_table_display

ENDIF. "sxpg_command_list_get

New file: Note: At this time, it is necessary to distinguish whether the file is an ASC file or a BIN file, and whether it is UTF-8 unicode encoding.

OPEN DATASET dname FOR OUTPUT IN TEXT MODE ENCODING UTF-8.

OPEN DATASET filename FOR OUTPUT IN BINARY MODE.

For TEXT files, UTF-8 needs to be distinguished, and the filename here needs to pay attention to case.

 OPEN DATASET LV_PATH FOR OUTPUT IN BINARY MODE. " Create in binary form
  IF SY-SUBRC <> 0.
    RET_CD = ''.
    ERR_MSG = 'Attachment creation failed'.
    CLOSE DATASET LV_PATH.
    RETURN.
  ENDIF.
  TRANSFER LV_DATA TO LV_PATH. " write content
  CLOSE DATASET LV_PATH.

For the binary file, I first converted it to the RAWSTRING type, and then transferred it. I didn’t do it well when I used the loop to do it. The specific method is to use one more function:

bytecount = xstrlen( lv_file ).
CALL FUNCTION 'SCMS_BINARY_TO_XSTRING'
  EXPORTING
    input_length = bytecount
* FIRST_LINE = 0
*LAST_LINE = 0
 IMPORTING
   BUFFER = lv_data
  tables
    binary_tab = t_rawdata.

The function group of SCMS_CONV and the class of cl_bcs_convert are basically the same.

For TEXT text: (it can be processed directly in the loop cycle)

OPEN DATASET dname FOR OUTPUT IN TEXT MODE ENCODING UTF-8.
  LOOP AT it_ascii.
    TRANSFER it_ascii TO dname.
    TRANSFER cl_abap_char_utilities=>cr_lf TO dname.
  ENDLOOP.
  CLOSE DATASET dname.**

Read the file:

OPEN DATASET filename FOR INPUT IN BINARY MODE.
  READ DATASET filename INTO lv_data.
CLOSE DATASET filename.

Delete Files:

 OPEN DATASET LV_PATH FOR OUTPUT IN BINARY MODE. " Attempt to open the file
  IF SY-SUBRC <> 0. When " is not 0, it means that the file does not exist, return directly
    CLOSE DATASET LV_PATH.
    RETURN.
  ENDIF.
  DELETE DATASET LV_PATH. " creates in binary form
  IF SY-SUBRC <> 0.
    RET_CD = ''.
    ERR_MSG = 'Attachment deletion failed'.
    CLOSE DATASET LV_PATH.
    RETURN.
  ENDIF.
*****************************Close file stream****************** ***********
  CLOSE DATASET LV_PATH.

Besides that:

Open the file for appending:

OPEN DATASET <dsn> FOR APPENDING IN TEXT MODE ENCODING DEFAULT .
 FTP (File transfer protocol) is a standard network protocol that can be used to transfer files on the Internet. The SAP system provides some standard functions, which are placed in the function group SFTP to transfer files between the FTP server and SAP. There are many implementation cases in this way. Assuming that the data in SAP is to be placed on the FTP server, you can put the data into a file in a certain path of the application server in a point-to-point way, and then use the standard FTP function for file transfer; you can also use PI for data integration, PI There is a dedicated FTP adapter. It is also possible to automatically create two TCP/IP RFC connections named SAPFTP and SAPFTPA by executing the SAP standard program RSFTP005.

These are some reports related to FTP:

RSFTP001 – SAPFTP Version Check

RSFTP002 – Execute FTP commands

RSFTP003 – Testing

RSFTP004 – FTP Copy

RSFTP005 – SAPFTP check

RSFTP006 – List of FTP commands

RSFTP007 – Test FB: FTP_SERVER_TO_r3 / FTP_R3_TO_SERVER read FTP data to R3 / write R3 data to FTP.

RSFTP008 – Test FB:FTP_CLIENT_TO_R3 / FTP_R3_TO_CLIENT read FTP data to…

There are two ways to copy files from FTP, one is to copy files directly, and the other is to read file data from FTP to the internal table first, copy and then write to a file at a specified location, but this function only supports text format files (< em>.TXT,.DAT), generally not recommended.

related functions:

1) FTP_CONNECT: connect to FTP through account.

2) FTP_COMMAND: Execute FTP operation commands (note that all commands in the program must be lowercase).

1cd: Specify the local folder path;

cd: Specify the FTP folder path;

put : upload files;

get : download the file;

3) FTP_SERVER_TO_R3: Read the specified text file data on FTP to the internal table.

4) FTP_DISCONNECT: Close the FTP connection.

?
REPORT ZR_EXAMPLE_07 .
DATA: KEY TYPE I VALUE 26101957,
    TRFCDEST LIKE RFCDES-RFCDEST,
    THANDLE TYPE I.
 
INCLUDE:<ICON>.
* Define the input interface
SELECTION-SCREEN:BEGIN OF BLOCK FTPLOGIN WITH FRAME TITLE TEXT-001.
PARAMETERS: P_USER(45) LOWER CASE OBLIGATORY MEMORY ID USR,
           P_PWD(45) MODIF ID PWD LOWER CASE OBLIGATORY MEMORY ID PWD,
           P_HOST(15) MEMORY ID HOS OBLIGATORY,
           FTP_PATH(30) MEMORY ID FPOS OBLIGATORY.
SELECTION-SCREEN:END OF BLOCK FTPLOGIN.
 
SELECTION-SCREEN:BEGIN OF BLOCK UPLOAD WITH FRAME TITLE TEXT-002.
PARAMETERS: P_UPPATH(45),
         P_FILE(20) .
SELECTION-SCREEN: BEGIN OF LINE.
SELECTION-SCREEN: PUSHBUTTON 1(20) PUBU USER-COMMAND UPLOAD.
SELECTION-SCREEN: END OF LINE.
SELECTION-SCREEN:END OF BLOCK UPLOAD.
 
SELECTION-SCREEN:BEGIN OF BLOCK DOWNLOAD WITH FRAME TITLE TEXT-003.
PARAMETERS: DL_PATH(45),
           DL_FILE(20) .
SELECTION-SCREEN: BEGIN OF LINE.
SELECTION-SCREEN: PUSHBUTTON 1(20) GEBU USER-COMMAND DOWNLOAD.
SELECTION-SCREEN: PUSHBUTTON 24(30) SHBU USER-COMMAND ITAB_DL.
SELECTION-SCREEN: END OF LINE.
SELECTION-SCREEN:END OF BLOCK DOWNLOAD.
 
AT SELECTION-SCREEN OUTPUT.
* Encrypt the password input field
  PERFORM MASK_PWD.
 
* Add text and icons to each button
  WRITE ICON_OUTGOING_OBJECT AS ICON TO PUBU.
  CONCATENATE PUBU 'Upload FTP' INTO PUBU SEPARATED BY SPACE.
 
  WRITE ICON_INCOMING_OBJECT AS ICON TO GEBU.
  CONCATENATE GEBU 'FTP download' INTO GEBU SEPARATED BY SPACE.
 
  WRITE ICON_WRITE_FILE AS ICON TO SHBU.
  CONCATENATE SHBU 'Internal table download' INTO SHBU SEPARATED BY
SPACE.
 
AT SELECTION-SCREEN.
  PERFORM FTPCONNECT.
  IF SY-SUBRC <> 0.
 MESSAGE I001(00) WITH 'Can''t connect to FTP!'.
 EXIT.
  ENDIF.
 
  MESSAGE S001(00) WITH 'FTP connect OK!'.
  CASE SY-UCOMM.
 WHEN 'ONLI'.
   PERFORM FTP DISCONNECT.
   EXIT.
  ENDCASE.

?
?
* Execute FTP functions
  PERFORM FTP_EXECUTE.
* Close FTP connection
  PERFORM FTP DISCONNECT.
*-------------------------------------------------- ----------------------------*
* Change the display properties of the password input box to achieve password protection *
*-------------------------------------------------- ----------------------------*
FORM MASK_PWD.
  LOOP AT SCREEN .
 IF SCREEN-NAME = 'P_PWD'.
   SCREEN-INVISIBLE = '1'.
   MODIFY SCREEN .
   CONTINUE.
 ENDIF.
  ENDLOOP.
ENDFORM. "
 
*-------------------------------------------------- ----------------------------*
* Connect to the FTP server via IP, username, and password *
*-------------------------------------------------- ----------------------------*
FORM FTPCONNECT.
  DATA: THOSTS(45), TUSERS(45), TPWORD(45).
  THOSTS = P_HOST.
  TUSERS = P_USER.
  TPWORD = P_PWD.
* Encrypt and analyze the password value
  CALL 'AB_RFC_X_SCRAMBLE_STRING' " System Function
 ID 'SOURCE' FIELD TPWORD
 ID 'KEY' FIELD KEY
 ID 'SCR' FIELD 'X'
 ID 'DESTINATION' FIELD TPWORD
 ID 'DSTLEN' FIELD 64.
 
* Define the RFC connection target, which is different when the foreground and background are executed
  IF SY-BATCH = 'X'.
 TRFCDEST = 'SAPFTPA'.
  ELSE.
 TRFCDEST = 'SAPFTP'.
  ENDIF.
 
*This function can define the account password when there is a gateway, and there is no such setting for general company internal access
  CALL FUNCTION 'FTP_CONNECT'
 EXPORTING
   USER = TUSERS
   PASSWORD = TPWORD
   HOST = THOSTS
   RFC_DESTINATION = TRFCDEST
IMPORTING
  HANDLE = THANDLE
EXCEPTIONS
  NOT_CONNECTED = 1
  OTHERS = 2.
ENDFORM. " FTPCONNECT
* &---------------------------------------------- -----------------------
* & amp; close SAP at the end of setup
* &---------------------------------------------- -----------------------
FORM FTP DISCONNECT.
  CALL FUNCTION 'FTP_DISCONNECT'
    EXPORTING
         HANDLE = THANDLE.
ENDFORM. " FTPDISCONNECT
* &---------------------------------------------- -----------------------*
* & amp; Upload or download FTP files through SAP execution commands
* &---------------------------------------------- -----------------------*
FORM FTP_EXECUTE.
  DATA:TSUBRC LIKE SY-SUBRC.
  DATA: BEGIN OF COM OCCURS 0,
      CMD(100) TYPE C,
    END OF COM.
  DATA: BEGIN OF RES OCCURS 0,
      LINE(100) TYPE C,
    END OF RES.
 
* Specify the FTP folder path
  IF NOT FTP_PATH IS INITIAL.
 CONCATENATE 'cd' FTP_PATH INTO COM-CMD SEPARATED BY ' '.
 APPEND COM.
  ENDIF.
 
  CASE SY-UCOMM.
 WHEN 'UPLOAD'.
*Specify the upload folder path and upload file command
   CONCATENATE 'lcd' P_UPPATH INTO COM-CMD SEPARATED BY ' '.
   APPEND COM.
   CONCATENATE 'put' P_FILE INTO COM-CMD SEPARATED BY ' '.
   APPEND COM.
 
 WHEN 'DOWNLOAD'.
* Specify the download folder path and download file command
   CONCATENATE 'lcd' DL_PATH INTO COM-CMD SEPARATED BY ' '.
   APPEND COM.
   CONCATENATE 'get' DL_FILE INTO COM-CMD SEPARATED BY ' '.
   APPEND COM.
  ENDCASE.
 
  LOOP AT COM FROM 1.
 IF COM-CMD <> ''.
* Execute FTP commands
   CALL FUNCTION 'FTP_COMMAND'
        EXPORTING
             HANDLE = THANDLE
             COMCOMMAND = COM-CMD
        TABLES
             DATA = RES
        EXCEPTIONS
             TCPIP_ERROR = 1
             COMMAND_ERROR = 2
             DATA_ERROR = 3
             OTHERS = 4.
 
* When the execution fails, return the data and exit
   IF SY-SUBRC <> 0.
     CASE SY-UCOMM.
       WHEN 'UPLOAD'.
         MESSAGE E001(00) WITH 'FTP UPLOAD FAIL!'.
       WHEN 'DOWNLOAD'.
         MESSAGE E001(00) WITH 'FTP DOWNLOAD FAIL!'.
     ENDCASE.
     EXIT.
   ELSE.
 
*Judging the program execution logic and receipt information according to the function codes of different buttons, when selecting the function of downloading from the internal table, transfer to the subroutine
     CASE SY-UCOMM.
       WHEN 'UPLOAD'.
         MESSAGE S001(00) WITH 'FTP UPLOAD SUCCESS!'.
       WHEN 'DOWNLOAD'.
         MESSAGE S001(00) WITH 'FTP DOWNLOAD SUCCESS!'.
       WHEN 'ITAB_DL'.
         PERFORM DL_ITAB USING THANDLE DL_PATH DL_FILE.
     ENDCASE.
   ENDIF.
 ENDIF.
  ENDLOOP.
 
  CLEAR: COM,RES,TSUBRC.
  REFRESH: COM,RES.
ENDFORM. " FTPPUTFILE

?
?
*-------------------------------------------------- --------------------*
* Read FTP text type file data to internal table *
*-------------------------------------------------- --------------------*
FORM DL_ITAB USING THANDLE TYPE I
                VALUE(FILEPATH) TYPE C
                FILENAME TYPE C.
  DATA: BEGIN OF BLOB OCCURS 0,
       LINE(255) TYPE C,
     END OF BLOB.
*The connection string defines the specific path of the local file
CONCATENATE FILEPATH FILENAME INTO FILEPATH.
 
* Read FTP text type file data to internal table
*If the read FTP file is a non-text file (*.txt,*.dat), an error will occur
  CALL FUNCTION 'FTP_SERVER_TO_R3'
    EXPORTING
         HANDLE = THANDLE
         FNAME = FILENAME
    TABLES
         BLOBBLOB = BLOB.
 
* Exit the program and return an error when reading the file fails
  IF SY-SUBRC <> 0.
 MESSAGE E001(00) WITH 'Read FTP File FAIL!'.
 EXIT.
  ENDIF.
 
*Download the internal table data to a local file
  CALL FUNCTION 'WS_DOWNLOAD'
    EXPORTING
         FILENAME=FILEPATH
         FILETYPE = 'DAT'
    TABLES
         DATA_TAB = BLOB
    EXCEPTIONS
         FILE_OPEN_ERROR = 1
         FILE_WRITE_ERROR = 2
         INVALID_FILESIZE = 3
         INVALID_TABLE_WIDTH = 4
         INVALID_TYPE = 5.
 
*receipt error when writing data to local file fails
  IF SY-SUBRC <> 0.
 MESSAGE E001(00) WITH 'FTP Download By Internal table FAIL!'.
  ELSE.
 MESSAGE S001(00) WITH 'FTP Download By Internal table SUCCESS!'.
  ENDIF.
ENDFORM.

?

CG3Y CG3Z
Ordinary upload and download functions

Transaction code: CG3Y
For example, to download the above file to the local

3. Upload files
Transaction code CG3Z
Follow the steps to complete.

CG3Y/CG3Z Program Migration