Skip to Content
Author's profile photo Former Member

Automatizing tasks with Python

Hi everybody!

Since few weeks ago I am working in a project where I have to carry on some repetitive tasks on a SAP system (a Production clone).

First of these tasks is check if SAP is up and running (if not, I have to restart it) so I’ve developed a python script to automatize it and now I would like to share it with you.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import shlex
CMD_SAP_CHECK = "startrfc -3 -u < USER > -p < PASSWORD > -c < CLIENT > -l < LANG > " \
                "-h < SAPMSGSERVER > -s < INST.NUM > -F SUBST_START_BATCHJOB " \
CMD_SAP_START = "startsap < SAPMSGSERVER > all"
CMD_SAP_STOP = "stopsap < SAPMSGSERVER > all"
def execute(cmd):
        args = shlex.split(cmd)
        process = subprocess.Popen(args, stderr=subprocess.PIPE)
        return process
    except Exception, error:
        print "ERROR: ", error
if __name__ == "__main__":
    process = execute(CMD_SAP_CHECK)
    if process.returncode != 0:
        log = open("checksap.log", "w")
        log.write("    RC: %d\n" % process.returncode)
        log.write("STDERR:\n%s" %

If the script is able to launch the background job it will return return code 0.

If not, it will return another number and it will write stderr output to checksap.log file:

    RC: 1
Group       Error group 104
Message     Name or password is incorrect (repeat logon)

Then, it will stop SAP system and after that, start it again.

Some notes:

  • It must be executed with <SID>ADM user
  • It was developed with Python 2.6 under AIX but it should work in any OS platform (I’ve checked it in Windows with Python 2.4 and it worked just changing startrfc path).
  • I used to launch another report instead of SAPMSM66 but after reading this post [1] I’ve started to use it.
  • This script was simplified for this post. My production script is part of a bigger development and it is more elaborated. Just consider it as an example.
  • This is my first post. Not sure if I should have been posted in my own SCN Blog or in this space. Advice please. Anyway, I hope it is useful for someone.

[1] SM66 – a small tip that can make a big difference

Assigned Tags

      Be the first to leave a comment
      You must be Logged on to comment or reply to a post.