在远程服务器上运行shell脚本并将命令行参数传递给它

时间:2014-07-08 12:30:25

标签: shell ssh

我想通过远程服务器上的脚本运行top命令。 我还想添加一个过滤器,它只允许整数作为命令行参数传递给将在远程服务器上运行的脚本

这是我使用的命令: -

ssh -oConnectTimeout=5 -oBatchMode=yes -l group servername 'bash -s' < /some/path/top_command.sh

现在,当我没有向脚本传递任何参数时,它工作正常并显示top命令的前20行。

它也过滤掉任何字符(非整数)

之类的垃圾值

但问题在于负整数

ssh -oConnectTimeout=5 -oBatchMode=yes -l group servername 'bash -s' < /some/path/top_command.sh -7

现在我收到错误: -

Usage:  bash [GNU long option] [option] ...
    bash [GNU long option] [option] script-file ...
GNU long options:
    --debug
    --debugger
    --dump-po-strings
    --dump-strings
    --help
    --init-file
    --login
    --noediting
    --noprofile
    --norc
    --posix
    --protected
    --rcfile
    --restricted
    --verbose
    --version
    --wordexp
Shell options:
    -irsD or -c command or -O shopt_option          (invocation only)
    -abefhkmnptuvxBCHP or -o option

但是当我尝试不使用top_command.sh脚本运行命令时: -

ssh -oConnectTimeout=5 -oBatchMode=yes -l group servername 'top -b -n 1 | head -n -2'

我获得了top命令输出的负head

现在我很困惑,我做错了什么?

btw top_command.sh的内容

  1 #!/bin/bash
  2 if [[ $1 == "" ]]; then
  3         echo -e "No Argument passed:- Showing default top 20 lines\n"
  4         command=$(top -b -n 1 | head -n 20 2>&1)
  5         echo "$command"
  6 else
  7         re='^[-0-9]+$'
  8         if [[ $1 =~ $re ]]; then
  9                 command=$(top -b -n 1 | head -n $1 2>&1)
 10                 echo "$command"
 11         else
 12                 echo "Argument passed is not an integer"
 13         fi
 14 fi

1 个答案:

答案 0 :(得分:1)

你可以这样做

ssh -oConnectTimeout=5 -oBatchMode=yes -l group servername bash -s -- -7 < /some/path/top_command.sh

--是一个常见的选项 - 参数分隔符,在将以-开头的参数传递给命令时很有用。 mvrm等命令也会识别它。 --之后的所有内容都不再作为选项进行测试,并且已被视为正常参数。如果文件以rm开头,则mv-会很有用。

相关问题