Java用ssh连接远程服务器

1, 建立一个maven工程,引入JSch

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>omg</groupId>
<artifactId>omg</artifactId>
<version>0.0.1-SNAPSHOT</version>

<dependencies>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.50</version>
</dependency>
</dependencies>
</project>


2. code


package omg;


import com.jcraft.jsch.*;
import javax.swing.*;
import java.io.*;

public class Shell {
private static InputStream in = null;

public static void main(String[] arg) {

try {
JSch jsch = new JSch();

Session session = jsch.getSession("xxx", "150.236.223.66", 22);

String passwd = "xxxx###";
session.setPassword(passwd);

UserInfo ui = new MyUserInfo() {
public void showMessage(String message) {
JOptionPane.showMessageDialog(null, message);
}

public boolean promptYesNo(String message) {
return true;
}
};

session.setUserInfo(ui);
session.connect(30000);

Channel channel = session.openChannel("shell");
((ChannelShell) channel).setPty(false);

in = channel.getInputStream();
OutputStream out = channel.getOutputStream();

String command = "ls \n";

channel.connect(3 * 1000);

out.write(command.getBytes());
out.flush();

ReadThread readThread = new ReadThread();
readThread.start();

} catch (Exception e) {
System.out.println(e);
}
}

public static abstract class MyUserInfo implements UserInfo,
UIKeyboardInteractive {
public String getPassword() {
return null;
}

public boolean promptYesNo(String str) {
return false;
}

public String getPassphrase() {
return null;
}

public boolean promptPassphrase(String message) {
return false;
}

public boolean promptPassword(String message) {
return false;
}

public void showMessage(String message) {
}

public String[] promptKeyboardInteractive(String destination,
String name, String instruction, String[] prompt, boolean[] echo) {
return null;
}
}

private static class ReadThread extends Thread {

@Override
public void run() {
while (true) {
try {
int i = 0;
while ((i = in.read()) != -1) {
char c = (char) i;

System.out.print(c);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值