Java 使用 shell 脚本在远程机器上执行多个命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3950168/
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-08-14 07:28:08  来源:igfitidea点击:

Multiple commands on remote machine using shell script

javashellssh

提问by Lalith

I have a Java program Desktop/testfolder/xyz.jaron a remote machine. It has a configuration file on the same folder. When I SSH into the machine, I do:

Desktop/testfolder/xyz.jar在远程机器上有一个 Java 程序。它在同一文件夹中有一个配置文件。当我通过 SSH 连接到机器时,我会这样做:

"ssh user@remote java -cp Desktop/testfolder/xyz.jar Main"

The problem here is the configuration file is not in the path, as we are in the home folder so my program cannot read the configuration.

这里的问题是配置文件不在路径中,因为我们在主文件夹中,所以我的程序无法读取配置。

I want to first go into that folder and then run the program from that folder. In a shell script if I did this

我想先进入该文件夹,然后从该文件夹运行程序。如果我这样做,在 shell 脚本中

"ssh user@remote cd Desktop/testfolder"
"java -cp xyz.jar Main"

it executes the first statement and when the second statement is run it runs on my current machine not the remote machine.

它执行第一条语句,当第二条语句运行时,它运行在我当前的机器上而不是远程机器上。

Can we do only one command or there are any other solutions for this?

我们可以只执行一个命令还是有其他解决方案?

采纳答案by Robin

Try something like this:

尝试这样的事情:

ssh [email protected] "cd /home && ls -l"

回答by Trey Hunner

You could try separating the commands by a semicolon:

您可以尝试用分号分隔命令:

ssh user@remote "cd Desktop/testfolder ; java -cp xyz.jar Main"

回答by Dirk

If you want to split your commands over multiple lines for the sake of readability, you could also pass the list of commands to the bashcommand as follows:

如果您想将命令拆分为多行以提高可读性,您还可以将命令列表传递给bash命令,如下所示:

ssh [email protected] bash -c "'
  cd Desktop/testfolder
  java -cp xyz.jar Main
'"