Reputation: 113
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?
Upvotes: 0
Views: 2267
Reputation: 168636
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'
Upvotes: 1