0

I'm trying to create a script that uses SSH in Python to log in to a remote machine. My script is then supposed to call a certain rest API from that machine, and then returns the response to the original client.

I can't use subprocesses so that's sadly out of the question. I tried using Paramiko and Fabric but ended up having hugely complicated code segments with a lot of mandatory fields. I have setup my public key in all the steps between me and the machine and can easily go through all the intermediate machines by just typing.

"SSH xxx" - in the terminal

So what I'm looking for is something that allows me to do this simple request without me having to re-specify everything that's already setup. Has anyone done anything similar?

1
  • Why can't you use subprocess? Also you can use ssh as a tunnel, maybe that is enough. Commented Jul 5, 2016 at 15:16

1 Answer 1

1

Yes, I have done something similar.

Here is a working sample program that uses SSH in Python to log in to a remote machine, then calls a certain rest API from that machine, then returns the response to the original client.

import paramiko
from xml.etree import ElementTree as ET
import sys

my_server = sys.argv[1]

client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect(my_server)
stdin, stdout, stderr = client.exec_command(
    'curl http://www.thomas-bayer.com/sqlrest/CUSTOMER/3/')
xml = stdout.read()
xml = ET.fromstring(xml)
assert xml.find('.//FIRSTNAME').text == 'Michael'

If you could use subprocess, here is another such program:

import subprocess
import sys
from xml.etree import ElementTree as ET

my_server = sys.argv[1]

xml = subprocess.check_output([
    'ssh',
    my_server,
    'curl -s http://www.thomas-bayer.com/sqlrest/CUSTOMER/3/'])

xml = ET.fromstring(xml)
assert xml.find('FIRSTNAME').text == 'Michael'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.