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

菲利普·科尔默

我正在尝试从使用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

马丁·普里克里(Martin Prikryl)

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

因此,请使用标准的Paramiko代码执行命令:
Python Paramiko-运行命令

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章