【问题标题】:Pass arguments to a bash script stored locally and needs to be executed on a remote machine using Python Paramiko将参数传递给本地存储的 bash 脚本,需要使用 Python Paramiko 在远程机器上执行
【发布时间】:2021-03-03 23:34:21
【问题描述】:

我的本​​地机器上存储了一个 shell 脚本。该脚本需要如下参数:

#!/bin/bash
echo $1
echo $2

我需要在远程机器上运行此脚本(无需在远程机器上复制脚本)。我正在使用 Python 的 Paramiko 模块来运行脚本,并且可以毫无问题地在远程服务器上调用。

问题是我无法将这两个参数传递给远程服务器。这是我的python代码中的sn-p,用于在远程服务器上执行本地脚本:

with open("test.sh", "r") as f:
    mymodule = f.read()
c = paramiko.SSHClient()
k = paramiko.RSAKey.from_private_key(private_key_str)
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())

c.connect( hostname = "hostname", username = "user", pkey = k )
stdin, stdout, stderr = c.exec_command("/bin/bash - <<EOF\n{s}\nEOF".format(s=mymodule))

使用 bash 我可以简单地使用以下命令:

ssh -i key user@IP bash -s < test.sh "$var1" "$var2"

有人可以帮助我如何使用 Python 将这两个参数传递给远程服务器吗?

【问题讨论】:

    标签: python bash ssh parameter-passing paramiko


    【解决方案1】:

    做同样的事情,你在bash做的事情:

    command = "/bin/bash -s {v1} {v2}".format(v1=var1, v2=var2)
    stdin, stdout, stderr = c.exec_command(command)
    stdin.write(mymodule)
    stdin.close()
    

    如果你更喜欢heredoc语法,你需要使用单引号,如果你想扩展参数:

    command = "/bin/bash -s {v1} {v2} <<'EOF'\n{s}\nEOF".format(v1=var1,v2=var1,s=mymodule)
    stdin, stdout, stderr = c.exec_command(command)
    

    与在 bash 中使用引号的方式相同:

    ssh -i key user@IP bash -s "$var1" "$var2" <<'EOF'
    echo $1
    echo $2
    EOF
    

    虽然你的 Python 代码中有一个变量中的脚本,但你为什么不直接修改脚本本身呢?这会更直接,imo。


    强制警告:不要使用AutoAddPolicy - 这样做会失去对MITM attacks 的保护。有关正确的解决方案,请参阅Paramiko "Unknown Server"

    【讨论】:

    • command = "/bin/bash -s {v1} {v2} &lt;&lt;'EOF'\n{s}\nEOF".format(v1=var1,v2=var1,s=mymodule) stdin, stdout, stderr = c.exec_command(command) 工作。谢谢你 :)
    猜你喜欢
    • 1970-01-01
    • 2015-05-13
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多