I'm trying to set up a class so that I can ssh into a remote server (I have the IP, username, and password) and then send a command like "echo "test"" and then receive back the output (e.g., "test"). I'm using JSch to do this but I don't understand how to do it.
import com.jcraft.jsch.*;
public class ConnectSSH {
public int execute (String command) {
JSch jsch = new JSch();
String ip = "00.00.00.00;
String user = "root";
String pass = "password";
int port = 22;
try {
Session session = jsch.getSession(user, ip, port);
session.setPassword(pass);
session.connect();
...
I'm not sure what to do, I'm stuck after connecting.
Any advice is greatly appreciated.
解决方案
Try this:
JSch jsch=new JSch();
Session session=jsch.getSession(remoteHostUserName, RemoteHostName, 22);
session.setPassword(remoteHostpassword);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
ChannelExec channel=(ChannelExec) session.openChannel("exec");
BufferedReader in=new BufferedReader(new InputStreamReader(channel.getInputStream()));
channel.setCommand("pwd;");
channel.connect();
String msg=null;
while((msg=in.readLine())!=null){
System.out.println(msg);
}
channel.disconnect();
session.disconnect();