将参数传递给本地存储的 bash 脚本,需要使用 Python Paramiko 在远程机器上执行 [英] Pass arguments to a bash script stored locally and needs to be executed on a remote machine using Python Paramiko

查看:45
本文介绍了将参数传递给本地存储的 bash 脚本,需要使用 Python Paramiko 在远程机器上执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a shell script stored on my local machine. The script needs arguments as below:

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

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

I need to run this script on a remote machine (without copying the script on the remote machine). I am using Python's Paramiko module to run the script and can invoke on the remote server without any issue.

问题是我无法将这两个参数传递给远程服务器.这是我在远程服务器上执行本地脚本的 python 代码片段:

The problem is I am not able to pass the two arguments to the remote server. Here is the snippet from my python code to execute the local script on the remote server:

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 我可以简单地使用以下命令:

With bash I can simply use the below command:

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

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

Can someone help me with how to pass the two arguments to the remote server using Python?

推荐答案

bash 中做同样的事情:

Do the same, what you are doing in the 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语法,你需要使用单引号,如果你想扩展参数:


If you prefer the heredoc syntax, you need to use the single quotes, if you want the argument to be expanded:

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 中使用引号的方式相同:

The same way as you would have to use the quotes in the bash:

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


尽管您在 Python 代码中的变量中有脚本,为什么不直接修改脚本本身呢?那会更直接,imo.

强制性警告:请勿使用 AutoAddPolicy – 您将失去针对 MITM 攻击 这样做.如需正确的解决方案,请参阅Paramiko未知服务器".

Obligatory warning: Do not use AutoAddPolicy – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".

这篇关于将参数传递给本地存储的 bash 脚本,需要使用 Python Paramiko 在远程机器上执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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