bash 通过远程 ssh 运行完整命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7048170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:52:56  来源:igfitidea点击:

Running full commands through remote ssh

bashsshsh

提问by Nicarlo

Possible Duplicate:
how to use ssh to run shell script on a remote machine?

可能的重复:
如何使用 ssh 在远程机器上运行 shell 脚本?

I am trying to make a bash script that runs on my remote server's daily cron jobs to automatically login through ssh to another unix box, run a few commands and then leave.

我正在尝试制作一个在远程服务器的日常 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;
                               "

The problem I am having is I need to modify my current existing code to do something a little more complicated before each command like

我遇到的问题是我需要修改我当前现有的代码,在每个命令之前做一些更复杂的事情,比如

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

How would I go about running this command on the remote ssh machine and not on my local cron one?

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

回答by mopsled

Try writing your bash script locally and calling:

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

ssh [email protected] 'bash -s' < local_script.sh

(Found in the discussion here)

在此处的讨论中找到

回答by TMS

Write a script, copy it to the remote machine and from ssh run just that script.

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

回答by Kit Ho

Another workaround is to use python. There is a module called pexpectthat can solve your problem, and even more complicated scenario.

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