• Scheduling a Python job in Linux

    Author
    Topic
    #475749

    I’m trying to schedule a python script to run via crontab and it’s not working. This is on Citrix’s XenServer platform which is Linux.

    The script runs fine from the command prompt, but when I run it via cron i get an error:

    Code:
    File "./sshkill.py", line 3
    ps -u root -f | grep "ssh grpadmin@192.168.200.20" | while read psline; do
    ^
    SyntaxError: invalid syntax
    

    The script is:

    Code:
    #!/bin/sh
    ps -u root -f | grep "ssh [EMAIL="grpadmin@192.168.200.20"]grpadmin@192.168.200.20[/EMAIL]" | while read psline; do
    pid=`echo $psline | awk '{print $2}'`
    ppid=`echo $psline | awk '{print $3}'`
    if test $ppid -eq '1' ; then
    kill $pid
    fi
    done 
    

    and the crontab entry I have is:

    Code:
    2 * * * * /usr/bin/python /usr/bin/sshkill.py > /tmp/sshkill.txt 2>&1
    

    Any ideas?

    Viewing 6 reply threads
    Author
    Replies
    • #1273965

      Does Cron support redirect ?

      cheers, Paul

    • #1274007

      What you posted is not a python script, it is a shell script (that is what the “#!/bin/sh” on the first line means). No wonder python doesn’t like it.

    • #1274036

      I had pulled the script from a forum posting, and a different post in the thread mentioned something about python, so I assumed…

      That being said, I still get the error, even changing the crontab entry to /bin/bash. Other posts in the thread say they’ve gotten it running, so I must be missing something.

    • #1274124

      Try this: change the name of the file to sshkill and then change your cron command to:

      Code:
      2 * * * * /usr/bin/sshkill > /tmp/sshkill.txt 2>&1

      Also, make sure that your script is executable. You can do this as follows (signed in as root):

      Code:
      chmod a+x /usr/bin/sshkill

      Then to test the command to make sure it runs, from the command prompt enter:

      Code:
      sshkill

      Only once the command works from the command line can you expect it to run via cron.

    • #1274178

      Script runs from command prompt fine. I gave up for a little while and when I came back it had run at 11:02. I was trying to schedule it to run every 2 minutes, but it seems to be running at 2 minutes past the hour?

    • #1274187

      You have specified minute 2 of every hour on every day etc. Try this – all minutes with an interval of 2.
      0-59/2 * * * *

      cheers, Paul

    • #1274192

      That’s got it! Thanks all.

    Viewing 6 reply threads
    Reply To: Scheduling a Python job in Linux

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: