我正在学习 Java 和 Jsch,我可以让它运行其他命令,但不能运行 cd。 SSHManager sendCommand 函数返回的错误码不是null,而是一些不可读的字符串,每次都不一样(可能这意味着它是null,不熟悉Java 的内部工作原理)。
知道为什么不吗?类似问题在这里JSch - Why doesn't CD work?但无人回答。
我不会在此处复制并粘贴整个 SSSHManager 类 - 有用的答案以及我正在尝试遵循的完整代码。 Run a command over SSH with JSch
示例代码如下:
import SSH.SSHManager;
public class src
{
int ERROR = 0;
public static void main(String[] args)
{
String username = "debian";
String password = "temppwd";
String ipadd = "192.168.7.2";
SSHManager ssh = new SSHManager(username, password, ipadd, "");
ssh.connect();
String out = "";
//this doesn't work, printing output as bytes to show how weird it is
out = ssh.sendCommand("cd Desktop");
System.out.println(out.getBytes());
//some other test commands
out = ssh.sendCommand("mkdir test");
System.out.println(out);
out = ssh.sendCommand("ls");
System.out.println(out);
ssh.sendCommand("logout");
}
}
Eclipse 控制台的输出(bin 和 Desktop 已经在根目录中):
[B@b065c63
bin
Desktop
test
最佳答案
通过 SSH“执行” channel (SSHManager.sendCommand
后面的内容)执行的每个命令都在其自己的 shell 中执行。所以这些命令相互之间没有影响。
要在同一个 shell 中执行多个命令,只需使用适当的服务器 shell 语法即可。大多数 *nix shell 使用分号或双符号(具有不同的语义)。
在您的情况下,双符号会更合适。
cd Desktop && mkdir test && ls
另见 Multiple commands using JSch .
虽然,如果您想读取命令输出,您将无法区分,一个命令的输出结束和以下命令的输出开始。如果您想检查命令退出代码,更不用说了。
然后最好以不需要上下文的方式在其自己的“exec” channel 中执行每个命令。在您的情况下,这意味着使用完整路径:
mkdir Desktop/test
ls Desktop
另见 How to perform multiple operations with JSch .
此外,由于您打算只使用文件操作,实际上您根本不应该执行 shell 命令。使用标准 SSH API 进行文件操作,即 SFTP。
关于java - 为什么 cd 命令不能使用 Java JSch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14910926/