如何通过 Java 在 SSH 中运行多个命令?
如何使用 Java 运行时在 SSH 中运行多个命令?
命令: ssh [电子邮件受保护] '导出MYVAR=这个/目录/是/酷; /运行/我的/脚本 /myscript; echo $MYVAR'
@Test
public void testSSHcmd() throws Exception
{
StringBuilder cmd = new StringBuilder();
cmd.append("ssh ");
cmd.append("[email protected] ");
cmd.append("'export ");
cmd.append("MYVAR=this/dir/is/cool; ");
cmd.append("/run/my/script/myScript; ");
cmd.append("echo $MYVAR'");
Process p = Runtime.getRuntime().exec(cmd.toString());
}
该命令本身可以工作,但是当尝试从 java 运行时执行时却不能。有什么建议或建议吗?
How do I run multiple commands in SSH using Java runtime?
the command: ssh [email protected] 'export MYVAR=this/dir/is/cool; /run/my/script
/myscript; echo $MYVAR'
@Test
public void testSSHcmd() throws Exception
{
StringBuilder cmd = new StringBuilder();
cmd.append("ssh ");
cmd.append("[email protected] ");
cmd.append("'export ");
cmd.append("MYVAR=this/dir/is/cool; ");
cmd.append("/run/my/script/myScript; ");
cmd.append("echo $MYVAR'");
Process p = Runtime.getRuntime().exec(cmd.toString());
}
The command by its self will work but when trying to execute from java run-time it does not. Any suggestions or advice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用较新的 ProcessBuilder 类而不是
运行时.exec
。您可以通过指定程序及其参数列表来构造一个程序,如下面我的代码所示。您不需要在命令周围使用单引号。您还应该阅读 stdout 和 stderr 流以及 waitFor 以使该过程完成。Use the newer ProcessBuilder class instead of
Runtime.exec
. You can construct one by specifying the program and its list of arguments as shown in my code below. You don't need to use single-quotes around the command. You should also read the stdout and stderr streams andwaitFor
for the process to finish.如果
Process
只是挂起,我怀疑/run/my/script/myScript
向stderr
输出了一些内容。您需要处理该输出以及 stdout:If the
Process
just hangs I suspect that/run/my/script/myScript
outputs something tostderr
. You need to handle that output aswell asstdout
:您调用的 Runtime.exec 的版本将命令字符串拆分为多个令牌,然后将其传递给 ssh。您需要的是可以提供字符串数组的变体之一。将完整的远程部分放入一个参数中,同时去掉外部引号。示例
就是这样。
The veriant of
Runtime.exec
you are calling splits the command string into several tokens which are then passed to ssh. What you need is one of the variants where you can provide a string array. Put the complete remote part into one argument while stripping the outer quotes. ExampleThat's it.
您可能想查看 JSch 库。它允许您通过远程主机执行各种 SSH 操作,包括执行命令和脚本。
他们在这里列出了示例:http://www.jcraft.com/jsch/examples/
You might want to take a look at the JSch library. It allows you to do all sorts of SSH things with remote hosts including executing commands and scripts.
They have examples listed here: http://www.jcraft.com/jsch/examples/
这是正确的方法:
例如:
Here is the right way to do it:
For example:
如果您使用 https://github.com/shikhar/sshj/ 中的 SSHJ
If you are using SSHJ from https://github.com/shikhar/sshj/