Executing Operating System Commands from ABAP
Sep 13, 2013
Sometimes certain processes has to be run at Application Server level and the results has to be used within SAP system. They could be some simple OS commands or Shell scripts that does works like backup of files or database. In this article we are going to see how to achieve that.
SM69 is the trasaction where the commands that can be called from within the SAP system are defined. We can define our own command by clicking the Create button on the toolbar. When you click the Create button, the following screen appears.
Here we are creating a command named ZLS which will call the
operating system command of ls
which will list the files in the
current directory. Fill in the Operating System Command field
and if you have parameters to pass to that command specify that
in Parameters field.
Once you have created the command, you can run it from anywhere
using ABAP function module SXPG_COMMAND_EXECUTE
. The result
of the command is returned as a table of structure BTCXPM
which
contains the two fields: LENGTH
, MESSAGE
which are quite self
explanatory.
REPORT ZEXEC_EXT_COMM.
data:
l_command type sxpglogcmd value 'ZLS',
lt_result type standard table of btcxpm,
ls_result type btcxpm.
call function 'SXPG_COMMAND_EXECUTE'
exporting
commandname = l_command
* ADDITIONAL_PARAMETERS =
* OPERATINGSYSTEM = SY-OPSYS
* TARGETSYSTEM = SY-HOST
* DESTINATION =
* STDOUT = 'X'
* STDERR = 'X'
* TERMINATIONWAIT = 'X'
* TRACE =
* DIALOG =
* IMPORTING
* STATUS =
* EXITCODE =
TABLES
EXEC_PROTOCOL = lt_result
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 <> 0.
message 'Unable to execute command' type 'E'.
endif.
loop at lt_result into ls_result.
write:/5 ls_result-message.
endloop.
The function module SXPG_COMMAND_EXECUTE
will execute the command in
the Application Server and it will return the result as a table. This
table will contain the messages that command would’ve produced in the
console output.
Now you can process the table and find what you really wanted. In this case we are just printing the list of files in the current directory.