无法通过 Python 子进程 SSH [英] Unable to SSH via Python subprocess

查看:32
本文介绍了无法通过 Python 子进程 SSH的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过堡垒 ssh 进入一台机器.因此,该命令相当长:

I need to ssh into a machine via a bastion. Therefore the command is rather very long for this:

ssh -i  <pemfile location> -A -o 'proxycommand ssh -i <pemfile location> ec2-user@<bastion ip address> -W %h:%p' hadoop@<machine ip>

这个命令相当长.所以我尝试编写一个 python 脚本,它以 ip 地址和 pemfile 位置作为输入并执行 ssh.

This command is rather very long. So I tried to write a python script which takes ip addresses and pemfile location as inputs and does ssh.

#!/usr/local/bin/python3
import argparse
import subprocess
import os
import sys
import errno

parser = argparse.ArgumentParser(description="Tool to ssh into EMR via a bastion host")
parser.add_argument('master', type=str, help='IP Address of the EMR master-node')
parser.add_argument('bastion', type=str, help='IP Address of bastion EC2 instance')
parser.add_argument('pemfile', type=str, help='Path to the pemfile')

args = parser.parse_args()

cmd_list = ["ssh", "-i", args.pemfile, "-A", "-o", "'proxycommand ssh -i {} ec2-user@{} -W %h:%p'".format(args.pemfile, args.bastion), "hadoop@{}".format(args.master)]

command = ""

for w in cmd_list:
    command = command + " " + w

print("")
print("Executing command : ", command)
print("")

subprocess.call(cmd_list)

运行此脚本时出现以下错误:

I get the following error when I run this script :

command-line: line 0: Bad configuration option: 'proxycommand

但我能够通过 bash 运行确切的命令.

But I am able to run the exact command via bash.

为什么来自 python 脚本的 ssh 会失败?

Why is the ssh from python script failing then?

推荐答案

您犯了(常见的)错误,将语法引号与字面引号混合使用.在命令行中,shell 在将字符串传递给您正在运行的命令之前删除所有引号;你应该做同样的事情.

You are making the (common) mistake of mixing syntactic quotes with literal quotes. At the command line, the shell removes any quotes before passing the string to the command you are running; you should simply do the same.

cmd_list = ["ssh", "-i", args.pemfile, "-A",
    "-o", "proxycommand ssh -i {} ec2-user@{} -W %h:%p".format(
        args.pemfile, args.bastion), "hadoop@{}".format(args.master)]

另请参阅何时将引号括在 shell 变量周围? 讨论引用如何在 shell 中工作,也许 实际含义子进程中的 'shell=True' 作为 Python 端的起点.

See also When to wrap quotes around a shell variable? for a discussion of how quoting works in the shell, and perhaps Actual meaning of 'shell=True' in subprocess as a starting point for the Python side.

然而,编写交互式 SSH 会话的脚本会很脆弱;对于这类事情,我建议您查看合适的 Python 库,例如 Paramiko.

However, scripting interactive SSH sessions is going to be brittle; I recommend you look into a proper Python library like Paramiko for this sort of thing.

这篇关于无法通过 Python 子进程 SSH的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆