通过 rc.local 中调用的脚本 ssh 运行 不工作

ssh run by script called in rc.local not working


当我 运行 在 bash 中我自己独立运行时,此代码有效。 ssh 隧道已正确打开。
但是当我在启动时通过 rc.local 调用这个脚本时出现了问题。没有任何反应,但程序告诉我 "Program completed without errors" 这意味着脚本执行了 bash 命令...
这里的主要内容是当用户按下按钮(在 GPIO4 上)时,此代码将执行 bash 命令。 你们能帮我找出我做的错误吗?

#!/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()

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.

这就是问题所在。首先,我通过在 rc.local 中更改执行脚本和写入日志的用户:

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

然后我通过日志发现是环境问题。我刚刚用 os.chdir(path) 更改了脚本开头的当前目录,然后就完成了 ;) !谢谢@furas。