Reputation: 1664
I'm trying to migrate from using Popen
to directly run a ssh
command to using Paramiko instead, because my code is moving to an environment where the ssh
command won't be available.
The current invocation of the command is passed a parameter that is then used by the remote server. In other words:
process = subprocess.Popen(['ssh', '-T', '-i<path to PEM file>', 'user@host', 'parameter'])
and authorised_keys
on the remote server has:
command="/home/user/run_this_script.sh $SSH_ORIGINAL_COMMAND", ssh-rsa AAAA...
So I've written the following code to try and emulate that behaviour:
def ssh(host, user, key, timeout):
""" Connect to the defined SSH host. """
# Start by converting the (private) key into a RSAKey object. Use
# StringIO to fake a file ...
keyfile = io.StringIO(key)
ssh_key = paramiko.RSAKey.from_private_key(keyfile)
host_key = paramiko.RSAKey(data=base64.b64decode(HOST_KEYS[host]))
client = paramiko.SSHClient()
client.get_host_keys().add(host, "ssh-rsa", host_key)
print("Connecting to %s" % host)
client.connect(host, username=user, pkey=ssh_key, allow_agent=False, look_for_keys=False)
channel = client.invoke_shell()
... code here to receive the data back from the remote host. Removed for relevancy.
client.close()
What do I need to change in order to pass a parameter to the remote host so that it uses it as $SSH_ORIGINAL_COMMAND
?
Upvotes: 2
Views: 1758
Reputation: 202272
From an SSH perspective, what you are doing is not passing a parameter, but simply executing a command. That in the end the "command" is actually injected as a parameter to some script is irrelevant from the client's perspective.
So use a standard Paramiko code for executing commands:
Python Paramiko - Run command
(stdin, stdout, stderr) = s.exec_command('parameter')
# ... read/process the command output/results
Upvotes: 2