Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

python - How to pass a command-line ssh parameter with Paramiko?

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?

question from:https://stackoverflow.com/questions/65904648/how-to-pass-a-command-line-ssh-parameter-with-paramiko

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...