我正在尝试使用JSch从Android使用SSH在Linux服务器上执行命令。

据我所知,我正在连接到服务器,但是当我尝试检索命令的结果时,却什么也没得到。

连接到服务器:

public class SSHCommand {

public static String executeRemoteCommand(

String username,

String password,

String hostname,

int port) throws Exception {

JSch jsch = new JSch();

Session session = jsch.getSession(username, hostname, port);

session.setPassword(password);

// Avoid asking for key confirmation

Properties prop = new Properties();

prop.put("StrictHostKeyChecking", "no");

session.setConfig(prop);

session.connect();

// SSH Channel

ChannelExec channelssh = (ChannelExec)

session.openChannel("exec");

ByteArrayOutputStream baos = new ByteArrayOutputStream();

channelssh.setOutputStream(baos);

// Execute command

channelssh.setCommand("ls");

channelssh.connect();

channelssh.disconnect();

return baos.toString();

}

}

检索数据:

public class MainActivity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

final String TAG = "TESTING";

new AsyncTask(){

@Override

protected Void doInBackground(Integer... params) {

try {

Log.d(TAG, SSHCommand.executeRemoteCommand("username", "password", "192.168.0.1", 22));

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

}.execute(1);

}

}

我在这里想念什么?

Logo

更多推荐