Anda di halaman 1dari 25

http://saptechnical.com/Tutorials/ABAP/FTP/Index.

htm

FTP file transfer in Background


By Joffy John, Collabera

1) Creating RFC Destination for FTP.

Run program: RSFTP005.

The RFC destinations SAPFTP and SAPFTPA will be created automatically.

a) SAPFTP (for local system)

b) SAPFTPA (for running in Application server)(This is used for file transfer in background.

2) Code sample for developing FTP programs can be got from report program

a) RSFTP002

b) RSFTP007

c) RSFTP008

3) Sample code for getting customer details as tab delimited .TXT file in background.

*&---------------------------------------------------------------------*
*& Report ZCUSTOMER
*&
*&---------------------------------------------------------------------*
*&-Customer -All new/changed customer records created during the period.
*&---------------------------------------------------------------------*
*LedgerKey-------------Char(50)
*AccountName-----------Char(80)
*AccountReference -----Char(50)
*Address1 -------------Char(80)
*Address2 -------------Char(80)
*Town -----------------Char(50)
*County / State -------Char(50)
*Post Code / ZIP ------Char(20)
*Country---------------Char(2)
*AccountCurrencyCode --Char(3)
*ContactTelephone -----Char(20)
REPORT zcustomer.
TABLES: kna1,knb1.
TYPES: BEGIN OF st_customer,
ledgerkey TYPE char50,
name1 TYPE kna1-name1,
kunnr TYPE kna1-kunnr,
name2 TYPE kna1-name2,
stras TYPE kna1-stras,
ort01 TYPE kna1-ort01,
regio TYPE kna1-regio,
pstlz TYPE kna1-pstlz,
land1 TYPE kna1-land1,
waers TYPE knvv-waers,
telf1 TYPE kna1-telf1,
END OF st_customer.
TYPES : BEGIN OF st_cus,
ledgerkey(50) TYPE c, "LedgerKey
wrk_delim1 TYPE x ,
name1(80) TYPE c, "AccountName
wrk_delim2 TYPE x ,
kunnr(50) TYPE c, "AccountReference
wrk_delim3 TYPE x ,
name2(80) TYPE c, "Address1
wrk_delim4 TYPE x ,
stras(80) TYPE c, " Address2
wrk_delim5 TYPE x ,
ort01(50) TYPE c, " Town
wrk_delim6 TYPE x ,
regio(50) TYPE c, " County / State
wrk_delim7 TYPE x ,
pstlz(10) TYPE c, "Post Code / ZIP
wrk_delim8 TYPE x ,
land1(2) TYPE c, "Country
wrk_delim9 TYPE x ,
waers(3) TYPE c, "AccountCurrencyCode
wrk_delim10 TYPE x ,
telf1(20) TYPE c, "ContactTelephone
END OF st_cus .
DATA: wrk_file TYPE char200.
DATA: it_customer TYPE STANDARD TABLE OF st_customer,
wa_customer LIKE LINE OF it_customer.
DATA: it_dat TYPE STANDARD TABLE OF st_cus,
wa_dat LIKE LINE OF it_dat.
SELECTION-SCREEN BEGIN OF BLOCK b2 WITH FRAME TITLE text-001.
SELECT-OPTIONS:cust_no FOR kna1-kunnr,"customer no
com_code FOR knb1-bukrs,"company code
country FOR kna1-land1, "country
creat_on FOR kna1-erdat default sy-datum. "created or changed on
SELECTION-SCREEN END OF BLOCK b2.
START-OF-SELECTION.
IF creat_on-high IS INITIAL.
creat_on-high = creat_on-low.
ENDIF.
CONCATENATE sy-mandt '_1_' creat_on-low '_' creat_on-high '_Cust.txt' INTO
wrk_file.
PERFORM customer_data_select. "Customer Data File
PERFORM build_template_data.
PERFORM ftp_file_customer.
*&---------------------------------------------------------------------*
*& Form CUSTOMER_DATA_SELECT
*&---------------------------------------------------------------------*
* text
*----------------------------------------------------------------------*
* --> p1 text
* <-- p2 text
*----------------------------------------------------------------------*
FORM customer_data_select .
SELECT a~name1 a~name2 a~kunnr a~stras a~ort01 a~regio a~pstlz a~land1 a~telf1
"Details of the Customer based on KNA1.
FROM kna1 AS a
INNER JOIN knb1 AS b ON a~kunnr = b~kunnr
INTO CORRESPONDING FIELDS OF TABLE it_customer
WHERE a~kunnr IN cust_no
AND ( ( a~erdat IN creat_on OR a~updat IN creat_on ) OR
( b~erdat IN creat_on OR b~updat IN creat_on ) )
AND a~land1 IN country
AND b~bukrs IN com_code.
IF sy-subrc = 0.
LOOP AT it_customer INTO wa_customer.
SELECT SINGLE waers FROM knvv INTO wa_customer-waers
WHERE kunnr = wa_customer-kunnr..
wa_customer-ledgerkey = '12345'.
MODIFY it_customer FROM wa_customer.
ENDLOOP.
ENDIF.
ENDFORM. " CUSTOMER_DATA_SELECT
*&---------------------------------------------------------------------*
*& Form BUILD_TEMPLATE_DATA
*&---------------------------------------------------------------------*
* text
*----------------------------------------------------------------------*
* --> p1 text
* <-- p2 text
*----------------------------------------------------------------------*
FORM build_template_data .
LOOP AT it_customer INTO wa_customer.
MOVE-CORRESPONDING wa_customer TO wa_dat.
wa_dat-wrk_delim1 = '09'. "for adding tab after each field
wa_dat-wrk_delim2 = '09'.
wa_dat-wrk_delim3 = '09'.
wa_dat-wrk_delim4 = '09'.
wa_dat-wrk_delim5 = '09'.
wa_dat-wrk_delim6 = '09'.
wa_dat-wrk_delim7 = '09'.
wa_dat-wrk_delim8 = '09'.
wa_dat-wrk_delim9 = '09'.
wa_dat-wrk_delim10 = '09'.
APPEND wa_dat TO it_dat.
ENDLOOP.
ENDFORM. " BUILD_TEMPLATE_DATA
*&---------------------------------------------------------------------*
*& Form FTP_FILE_CUSTOMER
*&---------------------------------------------------------------------*
* text
*----------------------------------------------------------------------*
* --> p1 text
* <-- p2 text
*----------------------------------------------------------------------*
FORM ftp_file_customer .
DATA: l_user(30) TYPE c VALUE 'ZTEST', "user name of ftp server
l_pwd(30) TYPE c VALUE '1234', "password of ftp server
l_host(64) TYPE c VALUE '111.2.1.198', "ip address of FTP server
l_dest LIKE rfcdes-rfcdest VALUE 'SAPFTPA'."Background RFC destination
DATA: w_hdl TYPE i,
c_key TYPE i VALUE 26101957,
l_slen TYPE i.
*HTTP_SCRAMBLE: used to scramble the password provided in a format recognized by SAP.
SET EXTENDED CHECK OFF.
l_slen = STRLEN( l_pwd ).
CALL FUNCTION 'HTTP_SCRAMBLE'
EXPORTING
SOURCE = l_pwd
sourcelen = l_slen
key = c_key
IMPORTING
destination = l_pwd.
* To Connect to the Server using FTP
CALL FUNCTION 'FTP_CONNECT'
EXPORTING
user = l_user
password = l_pwd
host = l_host
rfc_destination = l_dest
IMPORTING
handle = w_hdl
EXCEPTIONS
OTHERS = 1. .
*FTP_R3_TO_SERVER:used to transfer the internal table data as a file to other system in the
character mode.
CALL FUNCTION 'FTP_R3_TO_SERVER'
EXPORTING
handle = w_hdl
fname = wrk_file "file path of destination system
character_mode = 'X'
TABLES
text = it_dat
EXCEPTIONS
tcpip_error = 1
command_error = 2
data_error = 3
OTHERS = 4.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4
RAISING invalid_output_file.
ENDIF.
*FTP_DISCONNECT: This is used to disconnect the connection between SAP and other system.
* To disconnect the FTP
CALL FUNCTION 'FTP_DISCONNECT'
EXPORTING
handle = w_hdl.
*RFC_CONNECTION_CLOSE:This is used to disconnect the RFC connection between SAP and other
system.
CALL FUNCTION 'RFC_CONNECTION_CLOSE'
EXPORTING
destination = l_dest
EXCEPTIONS
OTHERS = 1.
ENDFORM. " FTP_FILE_CUSTOMER

On running this report in background a file will be created in ftp server location.

----------------------------------------------------------------

https://wiki.scn.sap.com/wiki/display/Snippets/Sample+program+for+FTP+Transfer+of+Files+via+ABAP+Program

Sample program for FTP Transfer of Files via ABAP


Program
Skip to end of metadata

 Created by Former Member, last modified by Former Member on Jun 08, 2013
Go to start of metadata

The below program is a sample code on how to transfer files from a FTP Directory into SAP Application server directory. This program will :

(1) Read the files in a particular directory - FTP

(2) Copy the files in to the SAP directory - SAP Application Server

(3) Delete the original file from FTP server.

Additionally a Log table has been created which will track the status of the file.

Table structure - ZTBL_IPL_FTP as below :

FILE_NM ZDA_FILNAM CHAR 110 0 File Name for LPI Files

LOG_ID ZDA_LOG_LPI NUMC 4 0 Log Id for LPI File

FDATE SYDATUM DATS 8 0 Current Date of Application Server

FTIME SYUZEIT TIMS 6 0 Current Time of Application Server

STAT ZSTAT_LPI CHAR 2 0 Status of file

MESS BAPI_MSG CHAR 220 0 Message Text

Code as below :
Error rendering macro 'code': Invalid value specified for parameter 'lang'

REPORT zftptrasfr

NO STANDARD PAGE HEADING LINE-SIZE 255.


************************************************************************

*T Y P E S

************************************************************************

TYPES:

BEGIN OF x_cmdout,

line(100) TYPE c,

END OF x_cmdout.

TYPE-POOLS : slis.

************************************************************************

* D A T A

************************************************************************

*data specifications of FTP server

*Handler and Key

DATA: w_cmd(40) TYPE c,

w_hdl TYPE i,

w_logid TYPE zda_log_ipl VALUE 1,

w_key TYPE i VALUE 26101957,

w_slen TYPE i,

wa_iplftp TYPE ztbl_ipl_ftp,

it_iplftp TYPE STANDARD TABLE OF ztbl_ipl_ftp,

wa_cmdout TYPE x_cmdout,

it_cmdout TYPE STANDARD TABLE OF x_cmdout.

*Constant declarations

CONSTANTS: c_dest TYPE rfcdes-rfcdest VALUE 'SAPFTPA',

c_host(11) TYPE c VALUE '172.XX.X.XX',

c_ftp(6) TYPE c VALUE 'FTPDIRECTORY',

c_sap(16) TYPE c VALUE '/sap/inbound/SAPDIRECTORY'.

************************************************************************

* P A R A M E T E R S

************************************************************************

SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME TITLE text-001.

PARAMETERS: p_user(30) TYPE c LOWER CASE ,


p_pwd(30) TYPE c LOWER CASE ,

p_host(64) TYPE c LOWER CASE DEFAULT c_host ,

p_edi TYPE zedi, " 5-character domain containing EDI profiles

p_ftp TYPE e_dexcommfilepath LOWER CASE DEFAULT c_ftp,

p_sap TYPE esefilepath LOWER CASE DEFAULT c_sap.

SELECTION-SCREEN END OF BLOCK b1.

************************************************************************

*AT SELECTION SCREEN Events

************************************************************************

AT SELECTION-SCREEN OUTPUT.

LOOP AT SCREEN.

CASE screen-name.

WHEN 'P_PWD'."Set the password field as invisible

screen-invisible = '1'.

MODIFY SCREEN.

ENDCASE.

ENDLOOP.

************************************************************************

* S T A R T - O F - S E L E C T I O N

************************************************************************

START-OF-SELECTION.

*Connect to the FTP server.

PERFORM ftp_connect.

*Find all files in the directory and store inside the Log table

PERFORM log_files.

*Check for transfer of files to FTP.

IF it_iplftp[] IS INITIAL.

MESSAGE text-003 TYPE 'I'.

LEAVE LIST-PROCESSING.

ENDIF.
*Change the local save directory and download to SAP application server.

PERFORM move_files.

*Close the connection

PERFORM close_ftp.

************************************************************************

*END-OF-SELECTION

************************************************************************

END-OF-SELECTION.

*Display report.

PERFORM disp_res.

*&---------------------------------------------------------------------

*& Form FTP_CONNECT

*&---------------------------------------------------------------------

*Make a connection to the FTP server

*----------------------------------------------------------------------

FORM ftp_connect .

SET EXTENDED CHECK OFF.

w_slen = strlen( p_pwd ).

CALL FUNCTION 'HTTP_SCRAMBLE'

EXPORTING

source = p_pwd

sourcelen = w_slen

key = w_key

IMPORTING

destination = p_pwd.

CALL FUNCTION 'FTP_CONNECT'

EXPORTING

user = p_user

password = p_pwd

host = p_host

rfc_destination = c_dest

IMPORTING
handle = w_hdl

EXCEPTIONS

not_connected = 1

OTHERS = 2.

IF sy-subrc <> 0.

*Message will arise in case of any issues in connecting to the FTP server.

MESSAGE text-e01 TYPE 'I'.

LEAVE LIST-PROCESSING.

ENDIF.

ENDFORM. " FTP_CONNECT

*&---------------------------------------------------------------------

*& Form LOG_FILES

*&---------------------------------------------------------------------

*find all the files in the home directory

*----------------------------------------------------------------------

FORM log_files .

*Change directory to the FTP directory for LUPIN

CONCATENATE 'cd' p_ftp INTO w_cmd SEPARATED BY space.

CALL FUNCTION 'FTP_COMMAND'

EXPORTING

handle = w_hdl

command = w_cmd

compress = 'N'

TABLES

data = it_cmdout

EXCEPTIONS

tcpip_error = 1

command_error = 2

data_error = 3

OTHERS = 4.

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

REFRESH it_cmdout.

CLEAR w_cmd.
w_cmd = 'ls'.

CALL FUNCTION 'FTP_COMMAND'

EXPORTING

handle = w_hdl

command = w_cmd

compress = 'N'

TABLES

data = it_cmdout

EXCEPTIONS

tcpip_error = 1

command_error = 2

data_error = 3

OTHERS = 4.

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

*All customized checks for file to be placed here.

LOOP AT it_cmdout INTO wa_cmdout FROM 4.

*Check the command line for a file

CHECK wa_cmdout-line+68(4) EQ '.txt'.

*Move all the files to the FTP table

wa_iplftp-file_nm = wa_cmdout-line+39(33).

wa_iplftp-log_id = w_logid.

*Currently the transfer date/time will be taken

wa_iplftp-fdate = sy-datum."WA_CMDOUT-LINE+39(8).

wa_iplftp-ftime = sy-uzeit."WA_CMDOUT-LINE+48(6).

wa_iplftp-ernam = sy-uname.

APPEND wa_iplftp TO it_iplftp.

ENDLOOP.

REFRESH it_cmdout.
ENDFORM. " LOG_FILES

*&---------------------------------------------------------------------

*& Form MOVE_FILES

*&---------------------------------------------------------------------

FORM move_files .

DATA : l_indx TYPE i.

CLEAR w_cmd.

CONCATENATE 'lcd' p_sap INTO w_cmd SEPARATED BY space.

*Change the local directory to the sap inbound directory

CALL FUNCTION 'FTP_COMMAND'

EXPORTING

handle = w_hdl

command = w_cmd

compress = 'N'

TABLES

data = it_cmdout

EXCEPTIONS

command_error = 1

tcpip_error = 2.

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

REFRESH it_cmdout.

*Move each file from FTP to SAP inbound directory

LOOP AT it_iplftp INTO wa_iplftp WHERE stat EQ space OR

stat EQ 'CR'.

l_indx = sy-tabix.

CLEAR w_cmd.

REFRESH it_cmdout.

CONCATENATE 'get' wa_iplftp-file_nm INTO w_cmd SEPARATED BY space.


CALL FUNCTION 'FTP_COMMAND'

EXPORTING

handle = w_hdl

command = w_cmd

compress = 'N'

TABLES

data = it_cmdout

EXCEPTIONS

command_error = 1

tcpip_error = 2.

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

READ TABLE it_cmdout INTO wa_cmdout INDEX 2.

IF sy-subrc EQ 0.

IF wa_cmdout-line CS 'command successful'.

wa_iplftp-stat = 'CR'.

wa_iplftp-mess = text-004.

ELSE.

wa_iplftp-stat = 'EF'.

wa_iplftp-mess = text-005.

ENDIF.

ENDIF.

MODIFY it_iplftp FROM wa_iplftp INDEX l_indx.

*delete from FTP

CLEAR w_cmd.

CONCATENATE 'delete' wa_iplftp-file_nm INTO w_cmd SEPARATED BY space.

CALL FUNCTION 'FTP_COMMAND'

EXPORTING

handle = w_hdl

command = w_cmd

compress = 'N'

TABLES

data = it_cmdout

EXCEPTIONS
command_error = 1

tcpip_error = 2.

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

ENDLOOP.

*Insert all table entries.

INSERT ztbl_ipl_ftp FROM TABLE it_iplftp.

IF sy-subrc NE 0.

MESSAGE text-006 TYPE 'I'.

ENDIF.

ENDFORM. " MOVE_FILES

*&---------------------------------------------------------------------

*& Form CLOSE_FTP

*&---------------------------------------------------------------------

FORM close_ftp .

CALL FUNCTION 'FTP_DISCONNECT'

EXPORTING

handle = w_hdl.

CALL FUNCTION 'RFC_CONNECTION_CLOSE'

EXPORTING

destination = c_dest

EXCEPTIONS

OTHERS = 1.

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

ENDFORM. " CLOSE_FTP

*&---------------------------------------------------------------------

*& Form DISP_RES

*&---------------------------------------------------------------------

*Display the output


*----------------------------------------------------------------------

FORM disp_res .

DATA : l_layout TYPE slis_layout_alv.

l_layout-colwidth_optimize = 'X'.

*Display table contents of updated files

CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'

EXPORTING

i_callback_program = sy-repid

i_structure_name = 'ZTBL_IPL_FTP'

is_layout = l_layout

TABLES

t_outtab = it_iplftp

EXCEPTIONS

program_error = 1

OTHERS = 2.

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

ENDFORM. " DISP_RES


 abap
 ftp
 file
 transfer

1 Comment

1.
Former Member
This Program will check file name on ftp server and after Execute ur program. if ur filename is already there that time u got message 'FILE
ALLREADY EXIST.....' and file is not there then ur program will Execute.

* Object Name : Y_NI_DATA_MST


* Author/Company Name : Nikunj Patel / NASH Industries *
* Transport Request :
* Creation Date : 26.12.2014*
*&--------------------------------------------------------------------*
* Description: Table Data Download To CSV Format Via SAP to FTP Server(FTP://xxx.xxx.xxx.xxx)*
**
*&--------------------------------------------------------------------*
* Dependencies *
*&--------------------------------------------------------------------*
* Modification History *
* Modified Date: 03.01.2015 --> File Download Validation
*&--------------------------------------------------------------------*
* Date Programmer Client Ref No. Description Correction *
**
*&--------------------------------------------------------------------*
**
**
*&--------------------------------------------------------------------*
*&---------------------------------------------------------------------*
*& Report Y_NI_DATA_MST
*&
*&---------------------------------------------------------------------*
*&---------------------------------------------------------------------*
*
* MATNR CHAR 18 Material Number
* MTART CHAR 4 Material Type
* MBRSH CHAR 1 Industry sector
* MATKL CHAR 9 Material Group
* BISMT CHAR 18 Old material number
* MEINS UNIT 3 Base Unit of Measure
* BSTME UNIT 3 Purchase Order Unit of Measure
REPORT y_ni_data_mst.
TABLES: mara. "General Material Data
"Internal Table for General Material Data.
TYPES: BEGIN OF ty_mara,
matnr TYPE mara-matnr, " Material Number
mtart TYPE mara-mtart, " Material Type
mbrsh TYPE mara-mbrsh, " Industry sector
matkl TYPE mara-matkl, " Material Group
bismt TYPE mara-bismt, " Old material number
meins TYPE mara-meins, " Base Unit of Measure
bstme TYPE mara-bstme, " Purchase Order Unit of Measure
END OF ty_mara.
DATA: it_mara TYPE TABLE OF ty_mara WITH HEADER LINE.
"Internal Table for taking all fields of the above table in one line
"separated by Comma.
TYPES: BEGIN OF ty_text,
text(250),
END OF ty_text.
DATA:it_text TYPE TABLE OF ty_text WITH HEADER LINE.
CONSTANTS: c_key TYPE i VALUE 26101957,
c_dest TYPE rfcdes-rfcdest VALUE 'SAPFTPA'.
DATA: g_dhdl TYPE i, " Handle
g_dlen TYPE i, " password length
g_dpwd(30). " For storing password
DATA: p_user(30) TYPE c VALUE 'XXXX', "User-name of ftp server
p_pwd(30) TYPE c VALUE 'XXXXX', "Password of ftp server
p_host(64) TYPE c VALUE 'xxx.xxx.xxx.xxx'. "IP-ADDRESS of FTP server
"Selection Screen
SELECTION-SCREEN:BEGIN OF BLOCK b1 WITH FRAME TITLE text-001.
PARAMETERS: p_chg_dt TYPE mara-ersda DEFAULT sy-datum, "Created On 20150102
p_lst_dt TYPE mara-laeda DEFAULT sy-datum. "Date of Last Change
PARAMETERS: file_dt TYPE sy-datum OBLIGATORY DEFAULT sy-datum. "The Date when the file was uploaded SELECTION-SCREEN:END
OF BLOCK b1.
"Password not visible.
AT SELECTION-SCREEN OUTPUT.
LOOP AT SCREEN.
IF screen-name = 'P_PWD'.
screen-invisible = '1'.
MODIFY SCREEN.
ENDIF.
ENDLOOP.
g_dpwd = p_pwd. " Stored Password
"Start of selection
START-OF-SELECTION.
DATA: wrk_file TYPE char200.
CONCATENATE sy-mandt '_0' '_MARA_' sy-datum '.csv' INTO wrk_file. "File Name
PERFORM material_data_select. "Material Data
PERFORM build_template_data. "Concatenate Data
PERFORM ftp_file_material. "FTP Connection
*&---------------------------------------------------------------------*
*& Form MATERIAL_DATA_SELECT
*&---------------------------------------------------------------------*
* text
*----------------------------------------------------------------------*
* --> p1 text
* <-- p2 text
*----------------------------------------------------------------------*
FORM material_data_select .
"To fetch the data records from the table T777A.
SELECT matnr mtart mbrsh matkl bismt meins bstme
FROM mara
INTO TABLE it_mara
WHERE ersda < p_chg_dt
AND laeda <= p_lst_dt .
"Sort the internal table by build.
IF NOT it_mara[] IS INITIAL.
SORT it_mara BY matnr.
ENDIF.
ENDFORM. " MATERIAL_DATA_SELECT
*&---------------------------------------------------------------------*
*& Form BUILD_TEMPLATE_DATA
*&---------------------------------------------------------------------*
* text
*----------------------------------------------------------------------*
* --> p1 text
* <-- p2 text
*----------------------------------------------------------------------*
FORM build_template_data .
"Concatenate all the fields of above internal table records in one line
"separated by Comma.
LOOP AT it_mara.
CONCATENATE 'MARA' it_mara-matnr it_mara-mtart
it_mara-mbrsh it_mara-matkl
it_mara-bismt it_mara-meins
it_mara-bstme
INTO it_text-text SEPARATED BY '|'.
APPEND it_text.
CLEAR it_text.
ENDLOOP.
ENDFORM. " BUILD_TEMPLATE_DATA
*&---------------------------------------------------------------------*
*& Form FTP_FILE_MATERIAL
*&---------------------------------------------------------------------*
* text
*----------------------------------------------------------------------*
* --> p1 text
* <-- p2 text
*----------------------------------------------------------------------*
FORM ftp_file_material .
" To get the length of the password.
g_dlen = strlen( g_dpwd ).
" Below Function module is used to Encrypt the Password.
CALL FUNCTION 'HTTP_SCRAMBLE'
EXPORTING
source = g_dpwd " Actual password
sourcelen = g_dlen
key = c_key
IMPORTING
destination = g_dpwd. " Encyrpted Password
* Connects to the FTP Server as specified by user.
CALL FUNCTION 'SAPGUI_PROGRESS_INDICATOR'
EXPORTING
text = 'Connecting to FTP Server'.
* Below function module is used to connect the FTP Server.
* It Accepts only Encrypted Passwords.
* This Function module will provide a handle to perform different
* operations on the FTP Server via FTP Commands.
CALL FUNCTION 'FTP_CONNECT'
EXPORTING
user = p_user " FTP USER-NAME
password = g_dpwd " FTP PASSWORD
host = p_host " FTP IP-ADDRESS
rfc_destination = c_dest " RFC Destination 'SAPFTP'
IMPORTING
handle = g_dhdl
EXCEPTIONS
not_connected.
IF sy-subrc NE 0.
FORMAT COLOR COL_NEGATIVE.
WRITE:/ 'Error in Connection'.
ELSE.
WRITE:/ 'FTP Connection is opened '.
ENDIF.
IF sy-subrc = 0."When FTP connection established Successfully
DATA : path(58) ."Path that points to the FTP User's Home Directory
DATA:extension(4).
extension = '.csv' .
CONCATENATE sy-mandt '_0' '_MARA_' file_dt extension INTO path .
CALL FUNCTION 'FTP_SERVER_TO_R3'"For Reading a file from the FTP Server to the SAP System
EXPORTING
handle = g_dhdl
fname = path
character_mode = 'X'"'C'
* TABLES
* text = it_final"Final Internal table That contains the string from text file read EXCEPTIONS
tcpip_error = 1
command_error = 2
data_error = 3
OTHERS = 4.
IF sy-subrc = 0. " FTP_SERVER_TO_R3
WRITE: / 'File is Already Exist...' COLOR 6.
* PERFORM map_data."Maps data from the FTP file to an Internal Table
CALL FUNCTION 'FTP_DISCONNECT'"For Disconnecting the connected FTP Session
EXPORTING
handle = g_dhdl
EXCEPTIONS
OTHERS = 1.
ELSEIF sy-subrc <> 0."If File is not read successfully "FTP_SERVER_TO_R3
**Transferring the data from internal table to FTP Server.
CALL FUNCTION 'FTP_R3_TO_SERVER'
EXPORTING
handle = g_dhdl
fname = wrk_file " FILE NAME 'MATERIAL_DATA.txt'
character_mode = 'X'
TABLES
text = it_text[] " CONCATENATED MATERIAL DATA
EXCEPTIONS
tcpip_error = 1
command_error = 2
data_error = 3
OTHERS = 4.
IF sy-subrc <> 0."FTP_R3_TO_SERVER
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ELSE.
WRITE:/ 'File has created on FTP Server'.
ENDIF. "END:FTP_R3_TO_SERVER
CALL FUNCTION 'SAPGUI_PROGRESS_INDICATOR'
EXPORTING
text = 'File has created on FTP Server'.
*To Disconnect the FTP Server.
CALL FUNCTION 'FTP_DISCONNECT'
EXPORTING
handle = g_dhdl.
*To Disconnect the Destination.
CALL FUNCTION 'RFC_CONNECTION_CLOSE'
EXPORTING
destination = c_dest
EXCEPTIONS
OTHERS = 1.
ENDIF."END:FTP_SERVER_TO_R3
ENDIF. "END:When FTP connection established Successfully
ENDFORM. " FTP_FILE_MATERIA

-------------------------------------------------------------------------
REPORT zftp_backgroud_app.

DATA:BEGIN OF mtab_data OCCURS 0,


line(132) TYPE c,
END OF mtab_data.

DATA:l_host(64) TYPE c VALUE 'XXX.XXX.XXX.XXX',


cmd(80) TYPE c,
cmd1(80) TYPE c,
compress(20) TYPE c ,
cmd2(80) TYPE c,
pwd(30) TYPE c,
key TYPE i VALUE 26101957,
slen TYPE i,
mi_handle TYPE i.

pwd = 'password'.

cmd1 = 'put d:\test\test2.txt'.

cmd = 'ascii'.
cmd2 = 'cd /tmp'.

compress = 'N'.

SET EXTENDED CHECK OFF.


slen = strlen( pwd ).

AUTHORITY-CHECK OBJECT 'S_ADMI_FCD'


ID 'S_ADMI_FCD'
FIELD 'SFTP'.
IF sy-subrc <> 0.
MESSAGE 'no_authorization' TYPE 'E'.
EXIT.
ENDIF.

CALL FUNCTION 'HTTP_SCRAMBLE'


EXPORTING
source = pwd
sourcelen = slen
key = key
IMPORTING
destination = pwd.

CALL FUNCTION 'FTP_CONNECT'


EXPORTING
user = 'root'
password = pwd
host = l_host
rfc_destination = 'SAPFTPA' "'ZRFC_PV' "'SAPHTTPA'
IMPORTING
handle = mi_handle
EXCEPTIONS
not_connected = 1
OTHERS = 2.

IF cmd2 NE ' '.


CALL FUNCTION 'FTP_COMMAND'
EXPORTING
handle = mi_handle
command = cmd2
compress = compress
TABLES
data = mtab_data
EXCEPTIONS
tcpip_error = 1
command_error = 2
data_error = 3
OTHERS = 4.
LOOP AT mtab_data.
* WRITE AT / mtab_data.
ENDLOOP.
REFRESH mtab_data.
ENDIF.

IF cmd NE ' '.


CALL FUNCTION 'FTP_COMMAND'
EXPORTING
handle = mi_handle
command = cmd
TABLES
data = mtab_data
EXCEPTIONS
tcpip_error = 1
command_error = 2
data_error = 3
OTHERS = 4.
LOOP AT mtab_data.
* WRITE AT / mtab_data.
ENDLOOP.
REFRESH mtab_data.
ENDIF.

IF cmd1 NE ' '.


CALL FUNCTION 'FTP_COMMAND'
EXPORTING
handle = mi_handle
command = cmd1
TABLES
data = mtab_data
EXCEPTIONS
tcpip_error = 1
command_error = 2
data_error = 3
OTHERS = 4.
LOOP AT mtab_data.
* WRITE AT / mtab_data.
ENDLOOP.
REFRESH mtab_data.
ENDIF.

CALL FUNCTION 'FTP_DISCONNECT'


EXPORTING
handle = mi_handle
EXCEPTIONS
OTHERS = 1.

CALL FUNCTION 'RFC_CONNECTION_CLOSE'


EXPORTING
destination = 'SAPHTTPA' "'SAPFTP' " 'ZRFC_PV' "'SAPHTTPA'
EXCEPTIONS
OTHERS = 1.

----------------------------------------------------------------------------------------------------------------------

https://www.samplecodeabap.com/sftp-sap-ecc-abap/

SFTP from SAP using Winscp Client


April 6, 2014 · ABAP · 1 Comment

Tagged: code library, external call, interface, sftp, snippet

We use FTP to transfer sales order information to Hauliers; this is important piece of information for them to plan their resources (Drivers,
Truck etc.). We are using FTP on site-to-site VPN to make communication secure. For infrastructure reasons we are moving away from
site-to-site VPN and requirement is to use SFTP.
SAP ECC does not support sftp this is how I managed to achieve sftp communication using open source Winscp sftp client. Note that we
have SAP server installed on Windows 2003 server and you will have to adapt some steps for other server OS.

Step 1: Download and install Winscp client.

Download Winscp portable executables from http://winscp.net/eng/download.php . It’s a zip file, with an exe and com file. Unzip the
content and put it on server from where your SAP can execute them. I have kept mine in externexe/sftp folder. One first execution it will
automatically create ini file so don’t worry if you haven’t got ini file.

Step 2: Check installation and connectivity

Before we start with SAP side of development let’s check if this client is working.

Usually Winscp client opens up a session with server where you execute commands and close it when done. But here we want to open
session, execute commands and close session all in one go and fortunately Winscp does support this.

A simple dir command along with open session and exit command look like this

winscp.com /command "option batch abort" "open ftp://username:password@host_ip" "dir" "exit"

Option batch abort prevent session to seek for user input if anything goes wrong. For example, if your user id don’t have authorisation on
sftp server then Winscp client will prompt for Retry which will not be desirable if we are executing command from SAP. You can execute
multiple commands here just add them to list before exit in double quotes.

A file transfer command from a specific directory on client (F:/data) to specific directory on sftp server (in) will look like this.

winscp.com /command "option batch abort" "open ftp://username:password@host_ip"


"lcd F:\Data" "cd in" "put data.txt" "exit"

Step 3: Create command in SM69 which will call Winscp.com

Make sure to check Additional parameters allowed.


Press save.

To test the command from SAP press execute and input “open “sftp://username:password@host_ip”” “dir” “exit” in additional
parameters and execute.

You should get same output which you got in command prompt. Notice variable return code. Zero value signifies successful execution.
Step 4: Calling external command ZFTP using function module SXPG_COMMAND_EXECUTE.

This is sample code will give you an idea how to call external command we just created. You will have to make some changes to make it
work at your place.

1 METHOD execute_all_commands.

3 DATA : lv_additional_parameters TYPE string ,

4 lv_additional_param_func TYPE sxpgcolist-parameters .

5
* Create additional parameters strings based on username, password and host ip
6
IF me->username IS INITIAL .
7
RAISE EXCEPTION TYPE zcx_sfp
8
EXPORTING
9
textid = zcx_sfp=>user_name_empty .
10 ENDIF.
11

12 IF me->password IS INITIAL .

13 RAISE EXCEPTION TYPE zcx_sfp

14 EXPORTING
15 textid = zcx_sfp=>password_empty .

16 ENDIF.

17
IF me->host_ip IS INITIAL .
18
RAISE EXCEPTION TYPE zcx_sfp
19
EXPORTING
20
textid = zcx_sfp=>password_empty .
21
ENDIF.
22

23 * winscp.com /command "open "sftp://username:password@host_ip"" "dir" "exit"


24

25 * Create open command


26 CONCATENATE '"open'

27 ' "sftp://'

28 me->username

':'
29
me->password
30
'@'
31
me->host_ip
32
'""'
33 INTO lv_additional_parameters .
34

35 * Add user commands

36 CONCATENATE lv_additional_parameters

37 me->additional_commmands

38 INTO lv_additional_parameters

SEPARATED BY space .
39

40
* Add exit command in the end
41
CONCATENATE lv_additional_parameters
42
'"exit"'
43
INTO lv_additional_parameters
44 SEPARATED BY space .
45

46 IF STRLEN( lv_additional_parameters ) > 255 .

47 RAISE EXCEPTION TYPE zcx_sfp

48 EXPORTING

49 textid = zcx_sfp=>command_too_long .
50 ENDIF.

51

52

53 DATA : lv_status TYPE extcmdexex-status ,

lv_exitcode TYPE extcmdexex-exitcode ,


54
li_return TYPE lca_tracefile_tab .
55

56
lv_additional_param_func = lv_additional_parameters .
57

58
CALL FUNCTION 'SXPG_COMMAND_EXECUTE'
59
EXPORTING
60 commandname = me->command_name
61 additional_parameters = lv_additional_param_func

62 IMPORTING

63 status = lv_status

64 exitcode = lv_exitcode

TABLES
65
exec_protocol = li_return
66
EXCEPTIONS
67
no_permission = 1
68
command_not_found = 2
69 parameters_too_long = 3
70 security_risk = 4

71 wrong_check_call_interface = 5

72 program_start_error = 6

73 program_termination_error = 7

x_error = 8
74
parameter_expected = 9
75
too_many_parameters = 10
76
illegal_command = 11
77
wrong_asynchronous_parameters = 12
78 cant_enq_tbtco_entry = 13
79 jobcount_generation_error = 14

80 OTHERS = 15.

81

82 IF sy-subrc <> 0 OR lv_exitcode <> 0.

83 RAISE EXCEPTION TYPE zcx_sfp

EXPORTING
84
85 textid = zcx_sfp=>error_sftp

86 exit_code = lv_exitcode

status = lv_status
87
sftp_log = li_return .
88
ENDIF.
89

90
return = li_return .
91

92
ENDMETHOD.
93

94

95

96

97

98

99

100

--------------------------------------------------------------------------------------------------------------------

Anda mungkin juga menyukai