Search code examples
pythonsshstartup

ssh run by script called in rc.local not working



This code working when I run it on standalone by myself in bash. The ssh tunnel is open correctly.
But a problem occured when I call this script by rc.local at startup. Nothing happens but the program tell me "Program completed without errors" which means that the script executed the bash command...
The main thing here is when a user will push a button (on GPIO4) this code will execute a bash command. Can you guys please help me to find the mistake I did ?

#!/usr/bin/env python3
import sys,os,time
import RPi.GPIO as GPIO
import subprocess

flag_callback=True

def Callback(channel,port_nb,dist_user,dist_ip):
        global flag_callback
        flag_callback=False
        print('Button Pushed. SSH Tunnel will be open on remote port: \"{}\" until reboot.'.format(port_nb))
        bashCommand = "ssh -fN -R  {}:localhost:22 {}@{}".format(port_nb,dist_user,dist_ip)
        subprocess.Popen(bashCommand.split(),
                stdout=open('/dev/null', 'w'),
                stderr=open('logfile.log', 'a'),
                preexec_fn=os.setpgrp
                )
        print('SSH tunnel opened')

def main():
        if len(sys.argv) > 1:
                port_nb=sys.argv[1]
        else:
                port_nb='2222'

        if len(sys.argv) > 2:
                dist_user=sys.argv[2]
        else:
                dist_user='martin'

        if len(sys.argv) > 3:
                dist_ip = sys.argv[3]
        else:
                dist_ip='192.168.11.111'
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.add_event_detect(4, GPIO.FALLING, lambda channel,tmp_port=port_nb,tmp_user=dist_user,tmp_ip=dist_ip:Callback(channel,tmp_port,tmp_user,tmp_ip), bouncetime = 1000)
        try:
                while(flag_callback):
                        time.sleep(1)
                print("Program completed without errors")
        except:
                print("an error occured")

if __name__== "__main__":
  main()

Solution

  • programs in rc.local may run as different user, with different privilage, and with different environment. First think which you should do is to use logging system which will save in file info what program is doing, what values yu have in variables, etc. When you will have log then you can see if it worked correctly.

    That was the problem. First of all I changed the user which execute the script and write logs by doing this in rc.local :

    su pi -c '/home/pi/Public/OnPushButton_PULLUP.py >> /home/pi/Public/OnPushButton_PULLUP.log 2>&1 &'
    

    Then i realised thanks to the log that there was a problem about the environment. I just changed the current directory at the beginning of my script with os.chdir(path) and it's done ;) ! Thx to you @furas.