We use some essential cookies to make our website work.

We use optional cookies, as detailed in our cookie policy, to remember your settings and understand how you use our website.

pcmanbob
Posts: 13765
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: cron/bash job to run when ip s not responding to ping

Wed Aug 21, 2019 5:07 pm

So I took a look at jbudd's bash script but it would not work for me it just kept pinging way past 10 pings

so I re-wrote it and it now works.

Code: Select all

#!/bin/bash


PINGTARGET=google.com     # Where to ping.
iterations=10             # How many times
maxerrors=2               # More than this is a fail

function resetnetwork() {
   echo "Too many errors"        # Put your network reset code here
   #python /home/pi/test.py      # uncomment this line to make you python code run
}

errcnt=0                                             # initialises errcnt (as an integer)
i=0                                                  # initialises loop counter (as an integer)

while (( $i < $iterations ))                         # run loop 10 times

do
   echo "run ping"                                   # Debug!
   if ( ! ping -c 1 "$PINGTARGET" >/dev/null 2>&1 )  # ( .. ) Denotes run the command in a subshell and set $? . ! tests non-zero
   then
      errcnt=$(($errcnt+1))                          # Increment $errcnt
   fi
   i=$(( $i+1 ))                                     # Increment loop counter
   echo $errcnt                                      # Debug!
   echo $i                                           # Debug!   
   sleep 1                                           # delay to slow the program down 

   if (( $errcnt > $maxerrors ))
   then
      resetnetwork                                    # Call the function
      break                                           # It failed, don't bother checking any more
   fi
done
echo "finished"                                       # Debug! 
So any line commented as debug can be removed it just there so you can see the program working while testing.
you need to check the line that runs your python code for correct directory path and name and then uncomment it.

once you have tested this at the command line then you can try running it from cron I would suggest running it at 5min intervals at the minimum, or you may find your router is still rebooting when the next test comes round causing it to reboot your router over and over.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

aerosmith9110
Posts: 27
Joined: Fri Aug 16, 2019 10:41 pm

Re: cron/bash job to run when ip s not responding to ping

Wed Aug 21, 2019 8:05 pm

Thanks... will also explore that option...


I will check later after work :) it is 4am here now getting ready to work...

jbudd
Posts: 2115
Joined: Mon Dec 16, 2013 10:23 am

Re: cron/bash job to run when ip s not responding to ping

Wed Aug 21, 2019 11:11 pm

pcmanbob wrote:
Wed Aug 21, 2019 5:07 pm
So I took a look at jbudd's bash script but it would not work for me it just kept pinging way past 10 pings
so I re-wrote it and it now works.
Well I must admit I dont often use the (( )) without $'s syntax for arithmetic in Bash, but it seems to work for me. I wonder if it's dependent on environment settings.
@pcmanbob can you try this snippet on your Pi?
cat foobar
#! /bin/bash
(( iterations = 10 ))
(( i = 0 ))
while (( i < iterations ))
do
echo $i
(( i ++ ))
done
bash --version
./foobar


I have bash version 5.0.3(1)-release
The script foobar prints
0
1
2
3
4
5
6
7
8
9
(and exits!)

Edit - same output on bash 4.4.12(1)-release (Stretch) too

@aerosmith9110: Your router reset code starts with the "Hashbang" line #! /usr/bin/python3.
If the file is executable (chmod +x filename) then you can call it from a bash script just by name, without "python"
Over and out

aerosmith9110
Posts: 27
Joined: Fri Aug 16, 2019 10:41 pm

Re: cron/bash job to run when ip s not responding to ping

Wed Aug 21, 2019 11:51 pm

Thanks. I really really would like to try to incorporate the reboot code to pcmanbob's code. I think it is awesome and less prone to issues at it isn't calling other scripts ( which I think is less susceptible to issues ) and what is nice about it is pinging multiple IPs. What I did during my test was to make it => 70% success and it will reboot.. logic was if say I have 5 ip and one of them is really dead then router will still not reboot ( actually happened a couple of days ago when 1.1.1.1 was down. ). Also pinging website don't seem to work for me as the router is responding to pings! might be router is responding to the DNS queries and giving ping replies ( router and not the website ).

jbudd
Posts: 2115
Joined: Mon Dec 16, 2013 10:23 am

Re: cron/bash job to run when ip s not responding to ping

Thu Aug 22, 2019 12:21 am

It should be possible to make it work in Python, shell script or any language you like.

The error message you posted before was after subprocess.call(["python", "reboot_router2.py"])
That is calling a different script.

Looking at the error message itself:
File "reboot_router2.py", line 53, in get_client_proof
client_proof.append(client_key_digest ^ signature_digest)
TypeError: unsupported operand type(s) for ^: 'str' and 'str'
The ^ operator is a bitwise XOR. It only makes sense if the two operands are bits (or integers) and it's complaining that they are both strings. No idea why!

Edit - I see that your "code to integrate" has

Code: Select all

client_proof.append(client_key_digest[i] ^ signature_digest[i]) 
while the error message shows 
client_proof.append(client_key_digest ^ signature_digest)
Maybe that's just the forum editing out markup tags

It works from the command line - How do you call it? python reboot_router2.py or just reboot_router2.py?
Over and out

jbudd
Posts: 2115
Joined: Mon Dec 16, 2013 10:23 am

Re: cron/bash job to run when ip s not responding to ping

Thu Aug 22, 2019 12:40 am

Also pinging website don't seem to work for me
You are right, you should use IP addresses not domains since DNS queries will fail if the router is down.
Over and out

aerosmith9110
Posts: 27
Joined: Fri Aug 16, 2019 10:41 pm

Re: cron/bash job to run when ip s not responding to ping

Thu Aug 22, 2019 1:55 am

jbudd wrote:
Thu Aug 22, 2019 12:21 am
It should be possible to make it work in Python, shell script or any language you like.

The error message you posted before was after subprocess.call(["python", "reboot_router2.py"])
That is calling a different script.

Looking at the error message itself:
File "reboot_router2.py", line 53, in get_client_proof
client_proof.append(client_key_digest ^ signature_digest)
TypeError: unsupported operand type(s) for ^: 'str' and 'str'
The ^ operator is a bitwise XOR. It only makes sense if the two operands are bits (or integers) and it's complaining that they are both strings. No idea why!

Edit - I see that your "code to integrate" has

Code: Select all

client_proof.append(client_key_digest[i] ^ signature_digest[i]) 
while the error message shows 
client_proof.append(client_key_digest ^ signature_digest)
Maybe that's just the forum editing out markup tags

It works from the command line - How do you call it? python reboot_router2.py or just reboot_router2.py?

python reboot_router2.py

but code is for python3...
so i did an alias python = python3
so basically = python3 reboot_router2.py

if it is any help I got script from here:

https://github.com/mkorz/b618reboot

and I am sure it is working... I am just having a hard time incorporating it to pcmanbob..

jbudd
Posts: 2115
Joined: Mon Dec 16, 2013 10:23 am

Re: cron/bash job to run when ip s not responding to ping

Thu Aug 22, 2019 8:16 am

It works from the command line - How do you call it? python reboot_router2.py or just reboot_router2.py?
python reboot_router2.py

but code is for python3...
so i did an alias python = python3
so basically = python3 reboot_router2.py
I wonder if the error is a python 2 vs 3 issue. Just grasping at a straw.

A script file has a hashbang line to indicate which program should be used to run it.
#! /bin/bash
#! /usr/bin/python3
#! /usr/bin/perl
#! /usr/bin/python
etc.

Your router reset program has #! /usr/bin/python3 but I believe that if you call it with "python reboot_router2.py" then "python" overrides python3... except that you have an alias to override "python".

It seems a bit tenuous and convoluted. Does the alias exist when you call the program from another script? Will it exist if you run everything from cron?

Best practice is to execute the file directly with it's pathname "/home/pi/reboot_router.pi", not specifying the interpreter. Then you can be sure to use python3 even from another script or from cron.
Over and out

pcmanbob
Posts: 13765
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: cron/bash job to run when ip s not responding to ping

Thu Aug 22, 2019 9:39 am

jbudd.

tried you test script this is the result

Code: Select all

pi@StretchTest:~ $ ./test.sh
cat: foobar: No such file or directory
0
1
2
3
4
5
6
7
8
9
GNU bash, version 4.4.12(1)-release (arm-unknown-linux-gnueabihf)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
./test.sh: line 11: ./foobar: No such file or directory
I also ran you original script again , it does run but I think the reason i though it was not is it runs in about 2 seconds with no indication that it has run successfully, by adding a simple echo at the end I could see it had actually run , but running in such a short time may not be good if the server being tested happens to be busy.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

pcmanbob
Posts: 13765
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: cron/bash job to run when ip s not responding to ping

Thu Aug 22, 2019 9:55 am

aerosmith9110 wrote:
Thu Aug 22, 2019 1:55 am

so i did an alias python = python3
You should not do this it will mess up your system as some parts require python 2 , if you alias it to python 3 they may not run leading to a broken OS

if you can I would re-flash your sd card and leave python / plython3 aliasing alone and just call your router reboot code using

Code: Select all

 python3 /home/pi/reboot_router2.py

When I get a chance I will look at calling your code from within my python code, without actually integrating it .
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

jbudd
Posts: 2115
Joined: Mon Dec 16, 2013 10:23 am

Re: cron/bash job to run when ip s not responding to ping

Thu Aug 22, 2019 10:44 am

Thanks pcmanbob. That's a relief!

On my pi the script runs pretty fast too, which is good, except if I choose a server which does not respond to ping, when it waits for ping to time out each time.
There is a command line flag to set the timeout duration, I can't recall it offhand.

Incidentally, the first ip address to ping is your router. Could be the router is up but it's internet connection is down. I get that sometimes.

It's actually pretty easy to modify my script to use an array of IP addresses aerosmith9110. It makes sense to stick with python though if you can get it to work.
Over and out

aerosmith9110
Posts: 27
Joined: Fri Aug 16, 2019 10:41 pm

Re: cron/bash job to run when ip s not responding to ping

Thu Aug 22, 2019 11:30 am

I will remove the alias. I think i saw it reading tutorials somewhere.

pcmanbob
Posts: 13765
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: cron/bash job to run when ip s not responding to ping

Thu Aug 22, 2019 11:41 am

jbudd wrote:
Thu Aug 22, 2019 10:44 am
Thanks pcmanbob. That's a relief!
I have just found the first copy I made from your posted script , and it just runs indefinably, so I guess something got corrupted when I copied it from the web page , but I could not see anything when I looked at it in my editor ! , have deleted it now so I don't end up trying to use it again.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

pcmanbob
Posts: 13765
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: cron/bash job to run when ip s not responding to ping

Thu Aug 22, 2019 12:29 pm

So after some research on why sys.exit was used to call main I think we can remove that and just call main instead.

So have integrated to 2 lots of python code , I know the ping test part of it works ok but I can test it once the reboot code is added because I don't have all the modules installed, or the router to talk to.

So here's the code I would test it at the command line first using the command , were filename is what ever you saved the code as.

Code: Select all

python3 filename.py

Code: Select all

#!/usr/bin/python3
#""" reboots the Huawei 618 router (and potentially others with similar firmware)  """

import subprocess
import xml.etree.ElementTree as ET
import sys
import uuid
import hashlib
import hmac
from time import sleep
from binascii import hexlify
import requests
from config import ROUTER, USER, PASSWORD

#**************************************** code that does router reset **************************

def generate_nonce():
    """ generate random clientside nonce """
    return uuid.uuid4().hex + uuid.uuid4().hex


def setup_session(client, server):
    """ gets the url from the server ignoring the respone, just to get session cookie set up """
    url = "http://%s/" % server
    response = client.get(url)
    response.raise_for_status()
    # will have to debug this one as without delay here it was throwing a buffering exception on one of the machines
    sleep(1)


def get_server_token(client, server):
    """ retrieves server token """
    url = "http://%s/api/webserver/token" % server
    token_response = client.get(url).text
    root = ET.fromstring(token_response)

    return root.findall('./token')[0].text


def get_client_proof(clientnonce, servernonce, password, salt, iterations):
    """ calculates server client proof (part of the SCRAM algorithm) """
    msg = "%s,%s,%s" % (clientnonce, servernonce, servernonce)
    salted_pass = hashlib.pbkdf2_hmac(
        'sha256', password, bytearray.fromhex(salt), iterations)
    client_key = hmac.new(b'Client Key', msg=salted_pass,
                          digestmod=hashlib.sha256)
    stored_key = hashlib.sha256()
    stored_key.update(client_key.digest())
    signature = hmac.new(msg.encode('utf_8'),
                         msg=stored_key.digest(), digestmod=hashlib.sha256)
    client_key_digest = client_key.digest()
    signature_digest = signature.digest()
    client_proof = bytearray()
    i = 0
    while i < client_key.digest_size:
        client_proof.append(client_key_digest[i] ^ signature_digest[i])
        i = i + 1

    return hexlify(client_proof)


def login(client, server, user, password):
    """ logs in to the router using SCRAM method of authentication """
    setup_session(client, server)
    token = get_server_token(client, server)
    url = "http://%s/api/user/challenge_login" % server
    request = ET.Element('request')
    username = ET.SubElement(request, 'username')
    username.text = user
    clientnonce = generate_nonce()
    firstnonce = ET.SubElement(request, 'firstnonce')
    firstnonce.text = clientnonce
    mode = ET.SubElement(request, 'mode')
    mode.text = '1'
    headers = {'Content-type': 'text/html',
               '__RequestVerificationToken': token[32:]}
    response = client.post(url, data=ET.tostring(
        request, encoding='utf8', method='xml'), headers=headers)
    scram_data = ET.fromstring(response.text)
    servernonce = scram_data.findall('./servernonce')[0].text
    salt = scram_data.findall('./salt')[0].text
    iterations = int(scram_data.findall('./iterations')[0].text)
    verification_token = response.headers['__RequestVerificationToken']
    login_request = ET.Element('request')
    clientproof = ET.SubElement(login_request, 'clientproof')
    clientproof.text = get_client_proof(
        clientnonce, servernonce, password, salt, iterations).decode('UTF-8')
    finalnonce = ET.SubElement(login_request, 'finalnonce')
    finalnonce.text = servernonce
    headers = {'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
               '__RequestVerificationToken': verification_token}

    url = "http://%s/api/user/authentication_login" % server
    result = client.post(url, data=ET.tostring(
        login_request, encoding='utf8', method='xml'), headers=headers)
    verification_token = result.headers['__RequestVerificationTokenone']

    return verification_token


def reboot(client, server, user, password):
    """ reboots the router :) """
    verification_token = login(client, server, user, password)
    url = "http://%s/api/device/control" % server
    headers = {'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
               '__RequestVerificationToken': verification_token}
    client.post(
        url, data='<?xml version:"1.0" encoding="UTF-8"?><request><Control>1</Control></request>', headers=headers)


def main():
    """ main method """
    client = requests.Session()
    reboot(client, ROUTER, USER, PASSWORD)






#****************************************  code that does the ping testing ***************

SITES = ["google.com", "raspberrypi.org" , "no-ip.com", "grc.com", "youtube.com"]

DELAY_BETWEEN_PINGS = 1    # delay in seconds
DELAY_BETWEEN_TESTS = 120  # delay in seconds I would suggest 120-180 seconds or more
DELAY_AFTER_ROUTER_REBOOT = 180  # delay in seconds probably needs to be 180-240 seconds

# issue Linux ping command to determine internet connection status
def ping(site):
  
  cmd = "/bin/ping -c 1 " + site
  try:
    output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
  except subprocess.CalledProcessError:
    
    print (site,"bad") # can be removed
    return 0
  else:
    print (site,"good") # can be removed
    return 1
    
def ping_sites(site_list, wait_time, times):
  successful_pings = 0
  attempted_pings = times * len(site_list)
  for t in range(0, times):
    for s in site_list:
      successful_pings += ping(s)
      sleep(wait_time)
  
  return successful_pings / float(attempted_pings)   # return percentage successful     
  


while True:
  
  success = ping_sites(SITES, DELAY_BETWEEN_PINGS, 2)
  print (success)
  if success <= 0.8:  
    print ("Internet is DOWN")
    
    main()
    
    sleep(DELAY_AFTER_ROUTER_REBOOT)
  else:
    print ("Internet is OK")
    
sleep(DELAY_BETWEEN_TESTS)
now if it works at the command line it might still not work from cron , because cron is a different environment and it may not be able in import your router settings from the config file, in which case it may be simpler to add the settings to the program, and dispense with the config file.

So if it fails to run with some error please post the error back here in its entirety. I would say we have a 50/50 chance of it working first try ;)
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

aerosmith9110
Posts: 27
Joined: Fri Aug 16, 2019 10:41 pm

Re: cron/bash job to run when ip s not responding to ping

Sat Aug 24, 2019 12:23 am

pcmanbob wrote:
Thu Aug 22, 2019 12:29 pm
So after some research on why sys.exit was used to call main I think we can remove that and just call main instead.

So have integrated to 2 lots of python code , I know the ping test part of it works ok but I can test it once the reboot code is added because I don't have all the modules installed, or the router to talk to.

So here's the code I would test it at the command line first using the command , were filename is what ever you saved the code as.

Code: Select all

python3 filename.py

Code: Select all

#!/usr/bin/python3
#""" reboots the Huawei 618 router (and potentially others with similar firmware)  """

import subprocess
import xml.etree.ElementTree as ET
import sys
import uuid
import hashlib
import hmac
from time import sleep
from binascii import hexlify
import requests
from config import ROUTER, USER, PASSWORD

#**************************************** code that does router reset **************************

def generate_nonce():
    """ generate random clientside nonce """
    return uuid.uuid4().hex + uuid.uuid4().hex


def setup_session(client, server):
    """ gets the url from the server ignoring the respone, just to get session cookie set up """
    url = "http://%s/" % server
    response = client.get(url)
    response.raise_for_status()
    # will have to debug this one as without delay here it was throwing a buffering exception on one of the machines
    sleep(1)


def get_server_token(client, server):
    """ retrieves server token """
    url = "http://%s/api/webserver/token" % server
    token_response = client.get(url).text
    root = ET.fromstring(token_response)

    return root.findall('./token')[0].text


def get_client_proof(clientnonce, servernonce, password, salt, iterations):
    """ calculates server client proof (part of the SCRAM algorithm) """
    msg = "%s,%s,%s" % (clientnonce, servernonce, servernonce)
    salted_pass = hashlib.pbkdf2_hmac(
        'sha256', password, bytearray.fromhex(salt), iterations)
    client_key = hmac.new(b'Client Key', msg=salted_pass,
                          digestmod=hashlib.sha256)
    stored_key = hashlib.sha256()
    stored_key.update(client_key.digest())
    signature = hmac.new(msg.encode('utf_8'),
                         msg=stored_key.digest(), digestmod=hashlib.sha256)
    client_key_digest = client_key.digest()
    signature_digest = signature.digest()
    client_proof = bytearray()
    i = 0
    while i < client_key.digest_size:
        client_proof.append(client_key_digest[i] ^ signature_digest[i])
        i = i + 1

    return hexlify(client_proof)


def login(client, server, user, password):
    """ logs in to the router using SCRAM method of authentication """
    setup_session(client, server)
    token = get_server_token(client, server)
    url = "http://%s/api/user/challenge_login" % server
    request = ET.Element('request')
    username = ET.SubElement(request, 'username')
    username.text = user
    clientnonce = generate_nonce()
    firstnonce = ET.SubElement(request, 'firstnonce')
    firstnonce.text = clientnonce
    mode = ET.SubElement(request, 'mode')
    mode.text = '1'
    headers = {'Content-type': 'text/html',
               '__RequestVerificationToken': token[32:]}
    response = client.post(url, data=ET.tostring(
        request, encoding='utf8', method='xml'), headers=headers)
    scram_data = ET.fromstring(response.text)
    servernonce = scram_data.findall('./servernonce')[0].text
    salt = scram_data.findall('./salt')[0].text
    iterations = int(scram_data.findall('./iterations')[0].text)
    verification_token = response.headers['__RequestVerificationToken']
    login_request = ET.Element('request')
    clientproof = ET.SubElement(login_request, 'clientproof')
    clientproof.text = get_client_proof(
        clientnonce, servernonce, password, salt, iterations).decode('UTF-8')
    finalnonce = ET.SubElement(login_request, 'finalnonce')
    finalnonce.text = servernonce
    headers = {'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
               '__RequestVerificationToken': verification_token}

    url = "http://%s/api/user/authentication_login" % server
    result = client.post(url, data=ET.tostring(
        login_request, encoding='utf8', method='xml'), headers=headers)
    verification_token = result.headers['__RequestVerificationTokenone']

    return verification_token


def reboot(client, server, user, password):
    """ reboots the router :) """
    verification_token = login(client, server, user, password)
    url = "http://%s/api/device/control" % server
    headers = {'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
               '__RequestVerificationToken': verification_token}
    client.post(
        url, data='<?xml version:"1.0" encoding="UTF-8"?><request><Control>1</Control></request>', headers=headers)


def main():
    """ main method """
    client = requests.Session()
    reboot(client, ROUTER, USER, PASSWORD)






#****************************************  code that does the ping testing ***************

SITES = ["google.com", "raspberrypi.org" , "no-ip.com", "grc.com", "youtube.com"]

DELAY_BETWEEN_PINGS = 1    # delay in seconds
DELAY_BETWEEN_TESTS = 120  # delay in seconds I would suggest 120-180 seconds or more
DELAY_AFTER_ROUTER_REBOOT = 180  # delay in seconds probably needs to be 180-240 seconds

# issue Linux ping command to determine internet connection status
def ping(site):
  
  cmd = "/bin/ping -c 1 " + site
  try:
    output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
  except subprocess.CalledProcessError:
    
    print (site,"bad") # can be removed
    return 0
  else:
    print (site,"good") # can be removed
    return 1
    
def ping_sites(site_list, wait_time, times):
  successful_pings = 0
  attempted_pings = times * len(site_list)
  for t in range(0, times):
    for s in site_list:
      successful_pings += ping(s)
      sleep(wait_time)
  
  return successful_pings / float(attempted_pings)   # return percentage successful     
  


while True:
  
  success = ping_sites(SITES, DELAY_BETWEEN_PINGS, 2)
  print (success)
  if success <= 0.8:  
    print ("Internet is DOWN")
    
    main()
    
    sleep(DELAY_AFTER_ROUTER_REBOOT)
  else:
    print ("Internet is OK")
    
sleep(DELAY_BETWEEN_TESTS)
now if it works at the command line it might still not work from cron , because cron is a different environment and it may not be able in import your router settings from the config file, in which case it may be simpler to add the settings to the program, and dispense with the config file.

So if it fails to run with some error please post the error back here in its entirety. I would say we have a 50/50 chance of it working first try ;)


Initial testing shows it is working great! wow thanks.

aerosmith9110
Posts: 27
Joined: Fri Aug 16, 2019 10:41 pm

Re: cron/bash job to run when ip s not responding to ping

Sat Aug 24, 2019 1:54 am

I used:

@reboot sleep 120 && python3 /home/pi/filename.py

Cron job seems to be working.. so it is working...

Also how will I know that it is working in the background?
ps -A isn't showing it specifically...

but I am seeing this
1126 ? 00:00:04 python3
1127 ? 00:00:04 python3

User avatar
rpdom
Posts: 25190
Joined: Sun May 06, 2012 5:17 am
Location: Essex, UK

Re: cron/bash job to run when ip s not responding to ping

Sat Aug 24, 2019 5:39 am

That ps -A is only showing the python command, not its command line parameters like the script name. There are various options for ps to show more details. You can even customise the output.

I use ps -ef to show all processes and their arguments, or ps -efl to show even more details.

If you just want to show the python3 processes you could use

Code: Select all

ps -fp $(pidof python3)
Unreadable squiggle

jbudd
Posts: 2115
Joined: Mon Dec 16, 2013 10:23 am

Re: cron/bash job to run when ip s not responding to ping

Sat Aug 24, 2019 8:45 am

A bit of a rant possibly...

IF
Your program is executable (ls -l filename.py shows -rwxr-xr-x, chmod +x filename.py will make it executable)
AND
The first line in the file is
#! /usr/bin/python3
AND
You call it from cron (or otherwise) without "python3"
THEN
You wouldn't have the possibility of the wrong interpreter being used.
AND
ps -A would show /home/pi/filename.py
(Not sure about that one - I always use ps -ef)

Use the features that Linux provides and you save yourself problems down the line.
Over and out

aerosmith9110
Posts: 27
Joined: Fri Aug 16, 2019 10:41 pm

Re: cron/bash job to run when ip s not responding to ping

Sat Aug 24, 2019 9:34 am

jbudd wrote:
Sat Aug 24, 2019 8:45 am
A bit of a rant possibly...

IF
Your program is executable (ls -l filename.py shows -rwxr-xr-x, chmod +x filename.py will make it executable)
AND
The first line in the file is
#! /usr/bin/python3
AND
You call it from cron (or otherwise) without "python3"
THEN
You wouldn't have the possibility of the wrong interpreter being used.
AND
ps -A would show /home/pi/filename.py
(Not sure about that one - I always use ps -ef)

Use the features that Linux provides and you save yourself problems down the line.
With your recommendation I did:


-rw-r--r-- 1 root root 5813 Aug 24 08:07 reboot_router.py

to

pi@raspberrypi:~ $ sudo chmod +x reboot_router.py

-rwxr-xr-x 1 root root 5813 Aug 24 08:07 reboot_router.py

got it to run using:

./reboot_router.py

added this on crontab:

@reboot sleep 120 && ./reboot_router.py

I don't know any better so I am open to suggestions... But I am not sure what I am doing or what is the best practice.
Last edited by aerosmith9110 on Sat Aug 24, 2019 9:51 am, edited 1 time in total.

User avatar
B.Goode
Posts: 18724
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: cron/bash job to run when ip s not responding to ping

Sat Aug 24, 2019 9:49 am

aerosmith9110 wrote:
Sat Aug 24, 2019 9:34 am
jbudd wrote:
Sat Aug 24, 2019 8:45 am
A bit of a rant possibly...

IF
Your program is executable (ls -l filename.py shows -rwxr-xr-x, chmod +x filename.py will make it executable)
AND
The first line in the file is
#! /usr/bin/python3
AND
You call it from cron (or otherwise) without "python3"
THEN
You wouldn't have the possibility of the wrong interpreter being used.
AND
ps -A would show /home/pi/filename.py
(Not sure about that one - I always use ps -ef)

Use the features that Linux provides and you save yourself problems down the line.
With your recommendation I did:


-rw-r--r-- 1 root root 5813 Aug 24 08:07 reboot_router.py

to

pi@raspberrypi:~ $ sudo chmod +x reboot_router.py

-rwxr-xr-x 1 root root 5813 Aug 24 08:07 reboot_router.py
I tried to run it with out the python3 and it gives me:

pi@raspberrypi:~ $ reboot_router.py
bash: reboot_router.py: command not found


I don't know any better so I am open to suggestions... But I am not sure what I am doing or what is the best practice.




Well, @jbudd did say, explicitly:
AND
You call it from cron (or otherwise) without "python3"
But you didn't....


From a shell (command line or 'terminal') prompt, try:

Code: Select all

./reboot_router.py
Beware of the Leopard

aerosmith9110
Posts: 27
Joined: Fri Aug 16, 2019 10:41 pm

Re: cron/bash job to run when ip s not responding to ping

Sat Aug 24, 2019 9:52 am

B.Goode wrote:
Sat Aug 24, 2019 9:49 am
aerosmith9110 wrote:
Sat Aug 24, 2019 9:34 am
jbudd wrote:
Sat Aug 24, 2019 8:45 am
A bit of a rant possibly...

IF
Your program is executable (ls -l filename.py shows -rwxr-xr-x, chmod +x filename.py will make it executable)
AND
The first line in the file is
#! /usr/bin/python3
AND
You call it from cron (or otherwise) without "python3"
THEN
You wouldn't have the possibility of the wrong interpreter being used.
AND
ps -A would show /home/pi/filename.py
(Not sure about that one - I always use ps -ef)

Use the features that Linux provides and you save yourself problems down the line.
With your recommendation I did:


-rw-r--r-- 1 root root 5813 Aug 24 08:07 reboot_router.py

to

pi@raspberrypi:~ $ sudo chmod +x reboot_router.py

-rwxr-xr-x 1 root root 5813 Aug 24 08:07 reboot_router.py
I tried to run it with out the python3 and it gives me:

pi@raspberrypi:~ $ reboot_router.py
bash: reboot_router.py: command not found


I don't know any better so I am open to suggestions... But I am not sure what I am doing or what is the best practice.




Well, @jbudd did say, explicitly:
AND
You call it from cron (or otherwise) without "python3"
But you didn't....


From a shell (command line or 'terminal') prompt, try:

Code: Select all

./reboot_router.py

Thanks,

I was actually trying it when you posted :)

is @reboot sleep 120 && ./reboot_router.py correct?
Last edited by aerosmith9110 on Sat Aug 24, 2019 9:55 am, edited 1 time in total.

jbudd
Posts: 2115
Joined: Mon Dec 16, 2013 10:23 am

Re: cron/bash job to run when ip s not responding to ping

Sat Aug 24, 2019 9:53 am

Type echo $PATH.
It will give you something like this
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/games:/usr/games
If you have a directory /home/pi/bin then $PATH will include that too
/home/pi/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/games:/usr/games

This is the list of directories that the shell will look for an executable command unless you specify where it is /home/pi/command or ./command or ~/command

So: You can create a bin directory mkdir ~/bin and put the file in there.
Or put the file in /usr/local/bin
Or execute it from the command line with ./command.
Or put export PATH=/home/pi:$PATH in /home/pi/.bashrc

$PATH is set when you login.

When you run a command from cron you should use the full pathname eg /home/pi/bin/command because $PATH may contain a different list in cron.
Over and out

pcmanbob
Posts: 13765
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: cron/bash job to run when ip s not responding to ping

Sat Aug 24, 2019 10:03 am

aerosmith9110 wrote:
Sat Aug 24, 2019 1:54 am
I used:

@reboot sleep 120 && python3 /home/pi/filename.py

Cron job seems to be working.. so it is working...

Also how will I know that it is working in the background?
So you could always add some logging code to the script so that each time it runs it logs the time and date and the status of the internet connection, of course this log will fill quickly , depending on how often you are running the ping test.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

aerosmith9110
Posts: 27
Joined: Fri Aug 16, 2019 10:41 pm

Re: cron/bash job to run when ip s not responding to ping

Sat Aug 24, 2019 10:04 am

jbudd wrote:
Sat Aug 24, 2019 9:53 am
Type echo $PATH.
It will give you something like this
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/games:/usr/games
If you have a directory /home/pi/bin then $PATH will include that too
/home/pi/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/games:/usr/games

This is the list of directories that the shell will look for an executable command unless you specify where it is /home/pi/command or ./command or ~/command

So: You can create a bin directory mkdir ~/bin and put the file in there.
Or put the file in /usr/local/bin
Or execute it from the command line with ./command.
Or put export PATH=/home/pi:$PATH in /home/pi/.bashrc

$PATH is set when you login.

When you run a command from cron you should use the full pathname eg /home/pi/bin/command because $PATH may contain a different list in cron.
did this:

pi@raspberrypi:~ $ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/games:/usr/games

this is where my files at

pi@raspberrypi:~ $ pwd
/home/pi

so I assue that this will work on crontab?

@reboot sleep 120 && ./reboot_router.py

aerosmith9110
Posts: 27
Joined: Fri Aug 16, 2019 10:41 pm

Re: cron/bash job to run when ip s not responding to ping

Sat Aug 24, 2019 10:06 am

pcmanbob wrote:
Sat Aug 24, 2019 10:03 am
aerosmith9110 wrote:
Sat Aug 24, 2019 1:54 am
I used:

@reboot sleep 120 && python3 /home/pi/filename.py

Cron job seems to be working.. so it is working...

Also how will I know that it is working in the background?
So you could always add some logging code to the script so that each time it runs it logs the time and date and the status of the internet connection, of course this log will fill quickly , depending on how often you are running the ping test.
Since I made it executable would ps -A show it running?

Return to “Beginners”