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.
-
2This would be a one-liner in shellscript.sobek– sobek2016-11-10 18:07:16 +00:00Commented Nov 10, 2016 at 18:07
-
1Possible duplicate of How to make a ssh connection with python?Sufiyan Ghori– Sufiyan Ghori2016-11-11 00:20:06 +00:00Commented Nov 11, 2016 at 0:20
-
@SufiyanGhori I disagree, while the subject might suggest it, the OP doesn't specifically ask about python.sobek– sobek2016-11-11 11:00:05 +00:00Commented Nov 11, 2016 at 11:00
1 Answer
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 suand 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.shMake it executable.
chmod ugo+x /etc/init.d/myscriptConfigure the init system to run this script at startup.
update-rc.d myscript defaultsAlternative #2. Add commands to /etc/rc.local
vi /etc/rc.localwith 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 0Alternative #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).