在执行脚本时向bash传递参数

本文关键字:参数 bash 执行 脚本 | 更新日期: 2023-09-27 18:06:12

我试图在远程Linux机器上从Windows执行bash shell脚本。

我使用c#和SSH。网络图书馆。

脚本存在于windows机器上,不能安装在Linux机器上。我在脚本中读取使用'File.ReadAllText(…)',它在脚本中加载为字符串。使用SSH。然后在Linux上执行这个脚本:

        SshCommand cmd;
        using (var client = new SshClient(ConnectionInfo))
        {
            client.Connect();
            cmd = client.CreateCommand(string.Format("sh -x -s < {0}", script));                 
            cmd.Execute();
            client.Disconnect();
        }
        return cmd.ExitStatus;

当脚本没有任何参数时,此操作有效。但是如果我需要传入一些参数,下面的代码执行脚本,但缺少参数:

     cmd = client.CreateCommand(string.Format("sh -x -s p={0} < {1}", parameterString, script));
示例脚本如下:
#!/bin/bash
# check-user-is-not-root.sh
echo "Currently running $0 script"
echo "This Parameter Count is       [$#]"
echo "All Parameters            [$@]"

输出为:

Currently running bash script
This Parameter Count is     [0]
All Parameters          []

现在我正在使用curl(就像在这里批准的答案:)。

cmd = client.CreateCommand(string.Format("curl http://10.10.11.11/{0} | bash -s {1}", scriptName, args))

但是我仍然认为一定有一种方法可以读取带有参数的bash脚本,并在远程Linux机器上通过ssh运行它。

在执行脚本时向bash传递参数

也许您最好运行ssh user@host 'command; another; more',或者如果您确实必须使用显式的sh,例如ssh user@host "sh -c 'command; another; more'"。这样还可以避免将脚本放在临时文件中。

我做了一些故障排除,完全是在linux操作系统上进行的。我认为我认为你的问题是'p='。

我把你的测试脚本放在/tmp/script中,然后运行如下命令:

$ ssh 192.168.2.3 sh -s foo bar baz < /tmp/script
Currently running sh script
This Parameter Count is       [3]
All Parameters            [foo bar baz]

我也试过

$ ssh 192.168.2.3 sh -s p=foo bar baz < /tmp/script
Currently running sh script
This Parameter Count is       [3]
All Parameters            [p=foo bar baz]

…所以我不完全确定为什么你会看到参数计数为0,你应该至少看到p=作为一个参数。看起来您正在尝试使用'p='来指定参数列表,但这不是必需的。试一试,看看会发生什么。

要清楚,'/tmp/script'存储在我的本地 linux机器上,而不是在远程机器上。发送到ssh命令的标准输入的任何内容都将被发送到远程机器,并作为正在执行的命令的标准输入进行处理,因此我可以同样轻松地使用命令

$ cat /tmp/script | ssh 192.168.2.3 sh -s foo bar baz