jsch连接linux中文乱码,jsch连接Linux工具类

import com.alibaba.fastjson.JSONObject;

import com.jcraft.jsch.*;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import java.io.*;

/**

* Created by solon on 2017/3/1.

* 远程调用工具

*/

public class SSHBase {

String host;

String user;

Session session;

UserInfo ui;

final Logger logger = LoggerFactory.getLogger(SSHBase.class);

public SSHBase(String host, String user, String passwd) {

this.host = host;

this.user = user;

this.ui = new MyUserInfo(passwd);

}

public void connect() {

try {

JSch jsch = new JSch();

this.session = jsch.getSession(this.user, this.host, 22);

this.session.setUserInfo(this.ui);

this.session.connect();

logger.info("connect to {}@{} success.", this.user, this.host);

} catch (JSchException e) {

logger.error("connect to {} failed.", this.host, e);

}

}

public String runCommand(String cmd) {

Channel channel = null;

StringBuffer cmdOutput = new StringBuffer();

int cmdExitStatus = -1;

boolean isSuccess = false;

JSONObject result = new JSONObject();

result.put("result",isSuccess);

result.put("output",cmdOutput.toString());

result.put("exitStatus",cmdExitStatus);

try {

channel = session.openChannel("exec");

((ChannelExec) channel).setCommand(cmd);

channel.setInputStream(null);

((ChannelExec) channel).setErrStream(System.err);

InputStream in = channel.getInputStream();

channel.connect();

byte[] tmp = new byte[1024];

logger.info("run "{}"", cmd);

while (true) {

while (in.available() > 0) {

int i = in.read(tmp, 0, 1024);

if (i < 0) break;

cmdOutput.append(new String(tmp, 0, i));

}

if (channel.isClosed()) {

if (in.available() > 0) continue;

cmdExitStatus = channel.getExitStatus();

break;

}

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

logger.error("run "{}" thread sleep error", cmd, e);

return result.toString();

}

}

logger.info("{} output is:{}", cmd, cmdOutput);

logger.info("{} ExitStatus is:{}", cmd, cmdExitStatus);

} catch (JSchException e1) {

logger.error("run "{}"", cmd, e1);

return result.toString();

} catch (IOException e1) {

logger.error("run "{}"", cmd, e1);

return result.toString();

} finally

{

if (channel != null) {

channel.disconnect();

}

}

isSuccess = true;

result.put("result",isSuccess);

result.put("output", cmdOutput.toString());

result.put("exitStatus", cmdExitStatus);

return result.toString();

}

public boolean scpToRemote(String srcFile, String dstFile) {

Channel channel = null;

try {

FileInputStream fis = null;

boolean ptimestamp = true;

// exec 'scp -t rfile' remotely

String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + dstFile;

channel = this.session.openChannel("exec");

((ChannelExec) channel).setCommand(command);

// get I/O streams for remote scp

OutputStream out = channel.getOutputStream();

InputStream in = channel.getInputStream();

channel.connect();

if (checkAck(in) != 0) {

logger.error("scp {} check ack failed.", srcFile);

return false;

}

File _lfile = new File(srcFile);

if (ptimestamp) {

command = "T " + (_lfile.lastModified() / 1000) + " 0";

// The access time should be sent here,

// but it is not accessible with JavaAPI ;-<

command += (" " + (_lfile.lastModified() / 1000) + " 0

");

out.write(command.getBytes());

out.flush();

if (checkAck(in) != 0) {

logger.error("scp {} check ack failed.", srcFile);

return false;

}

}

// send "C0644 filesize filename", where filename should not include '/'

long filesize = _lfile.length();

command = "C0644 " + filesize + " ";

if (srcFile.lastIndexOf('/') > 0) {

command += srcFile.substring(srcFile.lastIndexOf('/') + 1);

} else {

command += srcFile;

}

command += "

";

out.write(command.getBytes());

out.flush();

if (checkAck(in) != 0) {

logger.error("scp {} check ack failed.", srcFile);

return false;

}

// send a content of lfile

fis = new FileInputStream(srcFile);

byte[] buf = new byte[1024];

while (true) {

int len = fis.read(buf, 0, buf.length);

if (len <= 0) break;

out.write(buf, 0, len); //out.flush();

}

fis.close();

// send ' '

buf[0] = 0;

out.write(buf, 0, 1);

out.flush();

if (checkAck(in) != 0) {

logger.error("scp {} check ack failed.", srcFile);

return false;

}

out.close();

channel.disconnect();

} catch (JSchException e) {

logger.error("scp {} failed.", srcFile, e);

return false;

} catch (IOException e) {

logger.error("scp {} failed.", srcFile, e);

return false;

} finally {

if (channel != null) {

channel.disconnect();

}

}

return true;

}

public void close() {

if (this.session != null) {

this.session.disconnect();

}

}

public class MyUserInfo implements UserInfo {

String passwd;

public MyUserInfo(String passwd) {

this.passwd = passwd;

}

public String getPassword() {

return passwd;

}

public boolean promptYesNo(String str) {

return true;

}

public String getPassphrase() {

return null;

}

public boolean promptPassphrase(String message) {

return true;

}

public boolean promptPassword(String message) {

return true;

}

public void showMessage(String message) {

logger.info(message);

}

}

int checkAck(InputStream in) throws IOException {

int b = in.read();

// b may be 0 for success,

// 1 for error,

// 2 for fatal error,

// -1

if (b == 0) return b;

if (b == -1) return b;

if (b == 1 || b == 2) {

StringBuffer sb = new StringBuffer();

int c;

do {

c = in.read();

sb.append((char) c);

}

while (c != '

');

if (b == 1) { // error

logger.error(sb.toString());

}

if (b == 2) { // fatal error

logger.error(sb.toString());

}

}

return b;

}

}

要使用JSch连接Linux服务器,您需要遵循以下步骤: 1. 下载JSch库,您可以从以下链接下载JSch库:http://www.jcraft.com/jsch/ 2. 将JSch库添加到您的Java项目中。 3. 使用以下代码连接Linux服务器: ```java import com.jcraft.jsch.*; public class SSHConnection { public static void main(String[] args) { String host = "your_host_name"; String user = "your_user_name"; String password = "your_password"; int port = 22; try { JSch jsch = new JSch(); Session session = jsch.getSession(user, host, port); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); // 连接成功后执行的命令 String command = "ls -l"; Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); // 输出命令执行结果 byte[] tmp = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, 1024); if (i < 0) break; System.out.print(new String(tmp, 0, i)); } if (channel.isClosed()) { if (in.available() > 0) continue; System.out.println("exit-status: " + channel.getExitStatus()); break; } try { Thread.sleep(1000); } catch (Exception ee) { } } channel.disconnect(); session.disconnect(); } catch (JSchException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上述代码中,您需要将host、user和password替换为您的Linux服务器的主机名、用户名和密码。您还可以修改port变量以使用其他端口。在连接成功后,代码将执行ls -l命令,并输出命令的执行结果。 除了使用exec通道执行命令外,您还可以使用sftp通道上传或下载文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值