如何使用 Paramiko 传递命令行 ssh 参数?

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

我正在尝试从使用 Popen 直接迁移到 运行 ssh 命令,改为使用 Paramiko,因为我的代码正在移动到 ssh 命令将不可用。

命令的当前调用传递了一个参数,然后由远程服务器使用。换句话说:

process = subprocess.Popen(['ssh', '-T', '-i<path to PEM file>', 'user@host', 'parameter'])
远程服务器上的

authorised_keys 有:

command="/home/user/run_this_script.sh $SSH_ORIGINAL_COMMAND", ssh-rsa AAAA...

所以我编写了以下代码来尝试模拟该行为:

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()

我需要更改什么才能将参数传递给远程主机,以便将其用作 $SSH_ORIGINAL_COMMAND

从 SSH 的角度来看,您所做的不是传递参数,而是简单地执行命令。从客户端的角度来看,“命令”最终实际上作为参数注入到某些脚本中是无关紧要的。

因此使用标准的 Paramiko 代码执行命令:
Python Paramiko - Run command

(stdin, stdout, stderr) = s.exec_command('parameter')
# ... read/process the command output/results