gpt4 book ai didi

command - 使用j2ssh执行多个命令

转载 作者:行者123 更新时间:2023-12-02 20:31:52 24 4
gpt4 key购买 nike

我想知道如何使用j2ssh执行多个命令。我从网上得到的代码如下:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import com.sshtools.j2ssh.io.IOStreamConnector;
import com.sshtools.j2ssh.io.IOStreamConnectorState;
import com.sshtools.j2ssh.connection.*;

import com.sshtools.j2ssh.SshClient;

import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.session.SessionChannelClient;

import com.sshtools.j2ssh.configuration.SshConnectionProperties;

import com.sshtools.j2ssh.transport.ConsoleHostKeyVerification;

public class MySSHClient {

SshClient ssh = null;
SshConnectionProperties properties = null;
SessionChannelClient session = null;

public MySSHClient(String hostName, String userName, String passwd )
{

try
{
// Make a client connection
ssh = new SshClient();
properties = new SshConnectionProperties();
properties.setHost(hostName);

// Connect to the host
ssh.connect(properties, new ConsoleHostKeyVerification());

// Create a password authentication instance
PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();

pwd.setUsername(userName);
pwd.setPassword(passwd);

// Try the authentication
int result = ssh.authenticate(pwd);

// Evaluate the result
if (result==AuthenticationProtocolState.COMPLETE) {

System.out.println("Connection Authenticated");
}
}
catch(Exception e)
{
System.out.println("Exception : " + e.getMessage());
}

}//end of method.


public String execCmd(String cmd)
{
String theOutput = "";
try
{
// The connection is authenticated we can now do some real work!
session = ssh.openSessionChannel();

if ( session.executeCommand(cmd) )
{
IOStreamConnector output = new IOStreamConnector();
java.io.ByteArrayOutputStream bos = new
java.io.ByteArrayOutputStream();
output.connect(session.getInputStream(), bos );
session.getState().waitForState(ChannelState.CHANNEL_CLOSED);
theOutput = bos.toString();
}
//else
//throw Exception("Failed to execute command : " + cmd);
//System.out.println("Failed to execute command : " + cmd);
}
catch(Exception e)
{
System.out.println("Exception : " + e.getMessage());
}

return theOutput;
}


}

我尝试进入一个目录,然后使用 ls 命令列出文件,但没有成功

MySSHClient sshc = new MySSHClient(<hostName>, <userName>, <passwd>);
System.out.println( sshc.execCmd("cd test") );
System.out.println( sshc.execCmd("ls") );

请问有什么帮助吗?

最佳答案

尝试用分号分隔命令。例如:System.out.println( sshc.execCmd("cd test; ls") );

关于command - 使用j2ssh执行多个命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13742427/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com