Alex Diamond
Alex Diamond

Reputation: 586

Execute and Disown Process Remotely Through a Bash Script?

I have a Python program I execute on my Raspberry Pi but, I execute it through SSH. I want to write a simple Bash script that allows me to double click it and perform the startup which includes: SSHing into the Pi, cd'ing into the directory, executing the python file and sending to background, then using disown -h to be able to let it run without relying on keeping the SSH connection up. I'm using sshpass for simplicity and this is what I have so far but, upon running it, the terminal freezes, the processes run but, I know my program does not start up. What's wrong with what I have tried and how can I achieve my goal?

#!/bin/bash

$(
sshpass -p [MyPass] ssh pi@[MyIP]
"
cd Documents/MyProgram/;
python3 myFile.py &;
disown -h
"
)

Excuse my formatting, it's for clarity.

Upvotes: 1

Views: 1755

Answers (2)

Charles Duffy
Charles Duffy

Reputation: 295618

You can't effectively disown a process if it still has handles on the local TTY. Use redirection to prevent them:

ssh pi@"$myIP" bash -s <<'EOF'
  cd Documents/MyProgram/ || exit
  python3 myFile.py </dev/null >/dev/null 2>&1 &
  disown -h
EOF

Redirecting to file works just as well -- the goal is to override the handles on each of your SSH session's stdin, stdout and stderr; that it's /dev/null is not so important.

Upvotes: 1

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30625

sshpass probably hangs on password validation. The safest approach is to use ssh-copy-id to copy private key to remote host and then use normal ssh command For no password login via ssh:

ssh-keygen
ssh-copy-id user@host

then just use ssh

ssh user@host "nohup python3 myFile.py 2>&1 > /dev/null &;exit;"

you may use nohup

nohup python3 myFile.py 2>&1 > /dev/null &

Upvotes: 1

Related Questions