【问题标题】:Bash: how to run a script remotelyBash:如何远程运行脚本
【发布时间】:2014-05-09 23:29:11
【问题描述】:

我有一个脚本(比如run.py),我想将它发送到远程机器(比如10.1.100.100),cd 到该远程机器的一个目录,然后在该目录中执行run.py

如何将上述过程封装在一个 bash 脚本中?我不知道如何让 bash 在另一台机器上远程执行命令。

希望我能在终端中看到run.py 的标准输出。但如果我只能重定向它,那也没关系。

【问题讨论】:

标签: linux bash shell


【解决方案1】:
chmod +x ./run.py
scp -pq  ./run.py 10.1.100.100:'/home/myremotedirectory/run.py'
ssh 10.1.100.100     'cd /somedirectory  &&  /home/myremotedirectory/run.py'

看看有没有帮助

【讨论】:

  • 您也可以将脚本作为标准输入和ssh remote 'cat >tmp; chmod +x tmp; tmp' 发送,但是远程临时文件处理应该比这个粗略的概念证明更复杂一些,它也不包括cd .另请注意,某些网站专门禁止/tmp 中的可执行文件。
【解决方案2】:

如何通过 SSH 运行本地脚本

简介:

通过 SSH 执行脚本而不复制脚本文件。 您需要一个简单的 SSH 连接和一个本地脚本。

代码:

#!/bin/sh
print_usage() {
        echo -e "`basename $0` ssh_connexion local_script"
        echo -e "Remote executes local_script on ssh server"
        echo -e "For convinient use, use ssh public key for remote connexion"
        exit 0
}

[ $# -eq "2" ] && [ $1 != "-h" ] && [ $1 != "--help" ] || print_usage

INTERPRETER=$(head -n 1 $2 | sed -e 's/#!//')

cat $2 | grep -v "#" | ssh -t $1 $INTERPRETER

示例:

 - ssh-remote-exec root@server1 myLocalScript.sh #for Bash
 - ssh-remote-exec root@server1 myLocalScript.py #for Python
 - ssh-remote-exec root@server1 myLocalScript.pl #for Perl
 - ssh-remote-exec root@server1 myLocalScript.rb #for Ruby

分步说明

此脚本执行以下操作: 1° 捕获第一行 #!获取解释器(即:Perl、Python、Ruby、Bash 解释器), 2° 通过 SSH 启动远程解释器, 3° 通过 SSH 发送所有脚本正文。

本地脚本:

本地脚本必须以 #!/path/to/interpreter 开头

- #!/bin/sh for Bash script
 - #!/usr/bin/perl for Perl script
 - #!/usr/bin/python for Python script
 - #!/usr/bin/ruby for Ruby script

此脚本不是基于本地脚本扩展,而是基于 #!信息。

【讨论】:

    【解决方案3】:

    你可以这样做:

    ssh -l yourid 10.1.100.100 << DONE
    cd /your/dir/
    ./run.py
    DONE
    

    上面已经编辑过了,我不记得原来是什么了,如果我想在一个连接中做,我会这样做。

    ssh -l yourid 10.1.100.100 python < <(
    echo "import os"
    echo "os.chdir('/yourdir')"
    echo "print(os.getcwd())"
    cat yourscript.py
    )
    

    【讨论】:

    • 这要求run.py 已经存在于远程计算机上。易于修复,但不是对 OP 问题的完整答案。
    【解决方案4】:

    请记住,这不是一个规则,您必须 cd 到请求的目录。

    一旦您可以访问远程机器,只需键入该文件的相对路径,而不使用 cd:

    /some_folder/./run.py
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-30
      • 1970-01-01
      相关资源
      最近更新 更多