1

I'm looking to create a script in python that initiates an SSH session with a server. I know it has to be a simple process i'm just not sure where to start. My ultimate plan is to automate this script to run on startup. i am not even sure python is the best way to go i just know it comes preloaded on raspbain for the pi.

M4dW0r1d
  • 97
  • 3
  • 12
  • 2
    This would be a one-liner in shellscript. – sobek Nov 10 '16 at 18:07
  • 1
    Possible duplicate of [How to make a ssh connection with python?](http://stackoverflow.com/questions/6188970/how-to-make-a-ssh-connection-with-python) – Sufiyan Ghori Nov 11 '16 at 00:20
  • @SufiyanGhori I disagree, while the subject might suggest it, the OP doesn't specifically ask about python. – sobek Nov 11 '16 at 11:00

1 Answers1

2

A simple bash script would be better suited to the task. It is possible with python, but there's no obvious reason to make it harder than necessary.

From write a shell script to ssh to a remote machine and execute commands:

#!/bin/bash
USERNAME=someUser
HOSTS="host1 host2 host3"
SCRIPT="pwd; ls"
for HOSTNAME in ${HOSTS} ; do
    ssh -l ${USERNAME} ${HOSTNAME} "${SCRIPT}"
done

From how do i run a script at start up (askubuntu):

You will need root privileges for any the following. To get root, open a terminal and run the command

sudo su

and the command prompt will change to '#' indicating that the terminal session has root privileges.

Alternative #1. Add an initscript.

Create a new script in /etc/init.d/myscript.

vi /etc/init.d/myscript

(Obviously it doesn't have to be called "myscript".) In this script, do whatever you want to do. Perhaps just run the script you mentioned.

#!/bin/sh 
/path/to/my/script.sh

Make it executable.

chmod ugo+x /etc/init.d/myscript

Configure the init system to run this script at startup.

update-rc.d myscript defaults

Alternative #2. Add commands to /etc/rc.local

vi /etc/rc.local

with content like the following.

# This script is executed at the end of each multiuser runlevel 
/path/to/my/script.sh || exit 1   # Added by me 
exit 0

Alternative #3. Add an Upstart job.

Create /etc/init/myjob.conf

vi /etc/init/myjob.conf

with content like the following

description     "my job" 
start on startup
task
exec /path/to/my/script.sh

Depending on what you do with the ssh connection, if it needs to stay open over the entire up time of the device, you will need to use some more trickery however (ssh connections are autoclosed after a period of inactivity).

Community
  • 1
  • 1
sobek
  • 1,386
  • 10
  • 28