简体   繁体   中英

Running Python code over an existing SSH tunnel

I have a Python module (PyBind11 C++ Lib) that resides on an ECU. To use this library I need a SSH connection to the ECU to start a Python instance via the terminal.

~$ ssh root@IP
~$ python3

python 3.8.2 (default, Feb 25 2020, 10:39:28) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> import myModule

>>> myModule.do_something()
...

This works perfectly in the manual application

Now if I want to run the whole thing completely via Python on the host: (Pseudo Code)

>>> from myLibs import ssh_session

>>> with ssh_session(IP, user, pw) as clt:
       clt.exec_command("python3")
       clt.exec_command("import myModule")
       clt.exec_command("myModule.do_something()")
       ...

Here the commands should be Python commands instead of simple terminal commands.

Anyone have any ideas on how to implement this?

Thanks and greetings

What I have understood from you question is you want to run a python script on the host:

import myModule

myModule.do_something()

Probably scp the script and then running the script might suffice:

from myLibs import ssh_session

with ssh_session(IP, user, pw) as clt:
    clt.exec_command("scp <source_user>@<source_host>:<source_file_path> <destination_user>@<destination_host>:<destination_file_path>")
    clt.exec_command("python3 your_copied_script.py")

1.) HOST (LINUX):

  • Connect ECU via ssh tunnel

2.) TARGET (ECU):

  • Run python interpreter
  • Import myModule
  • Set mySample
  • Send mySample to host

3.) HOST (LINUX)

  • Compare mySample data with expected data (origin)
  • Exit ssh session

Try creating a python file that contains what you want to run on the target and then call the python interpreter:

clt.exec_command("touch myscript.py")
clt.exec_command("echo \"import MyModule\" >> myscript.py")
clt.exec_command("echo \"MyModule.dostuff()\" >> myscript.py")
clt.exec_command("python3 myscript.py")

I also suggest making a function .exec_all(*args) to run multiple commands in a single function call, therefore making the whole thing above a little simpler:

clt.exec_all("touch myscript.py",
             "echo \"import MyModule\" >> myscript.py",
             "echo \"MyModule.dostuff()\" >> myscript.py",
             "python3 myscript.py")

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