简体   繁体   中英

Connecting in SSH in a Python script

I am connected to a first Raspberry Pi (172.18.xx) in SSH and I would like to launch a script on the first RPI but the script is on another Raspberry Pi (192.168.xx). First, I did the configuration to connect without password to the second RPI from the first one. When I am on the first one, I am launching this command :

ssh pi@192.168.x.x 'sudo python script_RPI2.py'

And this is working correctly, I can check the correct results but I would like to launch this script in another script on the first RPI. So, I put the previous command in the file : script_RPI1.py. Then, I am launching the script : sudo python script_RPI1.py And I got the following error :

 ssh pi@192.168.x.x 
         ^
SyntaxError: invalid syntax

Anyone has an idea concerning my problem ?

How are you launching the script? What appears from the minimal information you gave is that you are trying or to do that command within the Python interactive interpreter or that you want to execute it in the interpreter and you forgot to surround it with quotes(") in order to make it as a string.

Try to explain a bit more please.

You want to run a bash command:

ssh pi@192.168.x.x 'sudo python script_RPI2.py'

you show do it in a .sh file as in the following example:

#!/bin/sh

ssh pi@192.168.x.x 'sudo python script_RPI2.py'

After saving this file just do ./name_of_file.sh, which will simply run your bash file in the terminal, if you want to run a python script that opens a terminal in another process and executes string that are terminal commands you should look at something like this:

from subprocess import call
call(["ls"])

This will execute ls in another terminal process and return the result back to you. Please check what you want to actually do and decide on one of these paths.

Modified the entire answer and actually put some extra time on the code. The full solution for you to integrate will look something like the code below. Note that the code is setup in a way that you can define the host to connect to, along with the command you want to execute in the remote RPi

import subprocess
import sys

remoteHost="pi@192.168.x.x"
command="python /path/to/script.py"

ssh = subprocess.Popen(["ssh", "%s" % remoteHost, command],
                       shell=False,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
    error = ssh.stderr.readlines()
    print >>sys.stderr, "ERROR: %s" % error
else:
    print result

yourVar = result   ### This is where you assign the remote result to a variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM