python - 如何使用 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
?
解决方案
从 SSH 的角度来看,您所做的不是传递参数,而是执行命令。最后,从客户端的角度来看,实际上将“命令”作为参数注入某些脚本是无关紧要的。
所以使用标准的 Paramiko 代码来执行命令:
Python Paramiko - Run command
(stdin, stdout, stderr) = s.exec_command('parameter')
# ... read/process the command output/results
推荐阅读
- python - 二进制数组值
- spring - 在 Mockito.when 中使用 Map 中的匹配值
- dbt - 根据 dbt 中的唯一键更新目标表上的记录(数据构建工具)
- api - Azure 应用服务 http 标头 url 编码
- wpf - 如果我们使用禁用 contxtmenu
- reactjs - react-hook-form 错误:transformToNestObject 不是函数
- django - 带有 CSRF 令牌的 Chrome 扩展请求
- python - 更改对外部函数的引用
- c++ - 如果我不对 COM 对象使用 Release,是否有任何内存/句柄泄漏
- kotlin - 在 onActivityResult 上启动两个 mediaProjection 服务