【问题标题】:Running full commands through remote ssh [duplicate]通过远程 ssh 运行完整命令 [重复]
【发布时间】:2011-10-26 06:21:15
【问题描述】:

可能重复:
how to use ssh to run shell script on a remote machine?

我正在尝试制作一个在远程服务器的日常 cron 作业上运行的 bash 脚本,以通过 ssh 自动登录到另一个 unix 机器,运行一些命令然后离开。

#!/bin/bash
ssh machinehost.com -l admin -p 2222 "/usr/bin/find /share/Public/backups/set0 -mtime +14 | xargs rm -f;
                               /usr/bin/find /share/Public/backups/set1 -mtime +4 | xargs rm -f;
                               /usr/bin/find /share/Public/backups/set2 -mtime +3 | xargs rm -f;
                               /usr/bin/find /share/Public/backups/set3 -mtime +21 | xargs rm -f;
                               /usr/bin/find /share/Public/backups/set4 -mtime +2 | xargs rm -f;
                               /usr/bin/find /share/Public/backups/set5 -mtime +2 | xargs rm -f;
                               "

我遇到的问题是我需要修改我当前的现有代码,以便在每个命令之前执行一些更复杂的操作,例如

if [ $(ls /share/Public/backups/set1 -1 | wc -l ) -gt 4 ] then run above command
fi

我将如何在远程 ssh 机器上而不是在我的本地 cron 机器上运行此命令?

【问题讨论】:

  • @Wooble 另一个问题是寻求一种在远程计算机上运行 shell 脚本的方法,因为这是解决此海报问题的方法。我认为这个问题已经足够不同了。

标签: bash ssh sh


【解决方案1】:

尝试在本地编写 bash 脚本并调用:

ssh user@example.com 'bash -s' < local_script.sh

(Found in the discussion here)

【讨论】:

    【解决方案2】:

    编写一个脚本,将其复制到远程机器,然后从 ssh 运行该脚本。

    【讨论】:

    • 这是我在服务器上使用的方法。
    【解决方案3】:

    另一种解决方法是使用 python。有一个叫做pexpect的模块可以解决你的问题,甚至更复杂的场景。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-06
      相关资源
      最近更新 更多