基本上,我需要进行某种聊天。我已经建立了JSch库,并使用它们的示例,我能够成功打开客户端(Win10-local)和服务器(Rpi-remote)之间的SSH(-R)隧道。我可以向rpi中的shell发送命令,传递文件,创建新文件,对其进行写入等。但是我需要能够“捕获”并直接从套接字读取服务器端的数据,比如说发送了一些字符串从客户端。然后,我必须在服务器端更改此字符串,然后将其重新发送回客户端,然后在客户端将其打印出来。
我试图创建一个套接字(服务器)并绑定到SSH通信所通过的端口,但是我收到一个错误,因为该端口已被使用,所以无法将其绑定到该端口。如果我先绑定套接字,那么SSH隧道将无法通过。
我还在jsch示例中尝试了守护程序示例: http://www.jcraft.com/jsch/examples/Daemon.java.html 但没有成功。
现在我正在尝试在服务器端使用以下代码:
public class ServerSide {
private final static Random random = new Random();
private final static String[] ADVICE_LIST = {
"Take smaller bites",
"Go for the tight jeans. No they do NOT make you look fat.",
"One word: inappropriate",
};
private void go() throws IOException {
ServerSocket serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress("localhost",12005));
while(!serverSocket.isClosed()) {
Socket socket = serverSocket.accept();
PrintWriter writer = new PrintWriter(socket.getOutputStream());
System.out.println(socket.getOutputStream());
String advice = getAdvice();
System.out.println("Sending advice: " + advice);
writer.write(advice);
writer.close();
System.out.println("Advice sent!");
socket.close();
}
}
private static String getAdvice() {
return ADVICE_LIST[random.nextInt() % ADVICE_LIST.length];
}
public static void main(String[] args) throws IOException {
ServerSide server = new ServerSide();
server.go();
}
}
}
服务器在端口12005上侦听,并且如果检测到任何客户端,则仅向其发送随机消息。昨天当我尝试使用服务器侦听时,无法建立隧道,但是当我尝试使用隧道时,则建立了隧道,但是服务器根本检测不到任何东西。客户端上的代码是:
public class PortForwardingR{
public static void main(String[] arg){
int rport;
String lhost;
int lport;
try{
JSch jsch=new JSch();
String host=null;
if(arg.length>0){
host=arg[0];
}
else{
host=JOptionPane.showInputDialog("Enter username@hostname",
System.getProperty("user.name")+
"@localhost");
}
String user=host.substring(0, host.indexOf('@'));
host=host.substring(host.indexOf('@')+1);
Session session=jsch.getSession(user, host, 22);
String foo=JOptionPane.showInputDialog("Enter -R port:host:hostport",
"port:host:hostport");
rport=Integer.parseInt(foo.substring(0, foo.indexOf(':')));
foo=foo.substring(foo.indexOf(':')+1);
lhost=foo.substring(0, foo.indexOf(':'));
lport=Integer.parseInt(foo.substring(foo.indexOf(':')+1));
// username and password will be given via UserInfo interface.
UserInfo ui=new MyUserInfo();
session.setUserInfo(ui);
session.connect();
// Channel channel=session.openChannel("shell");
// channel.connect();
session.setPortForwardingR(rport, lhost, lport);
System.out.println(host+":"+rport+" -> "+lhost+":"+lport);
}
catch(Exception e){
System.out.println(e);
}
}
public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return passwd; }
public boolean promptYesNo(String str){
Object[] options={ "yes", "no" };
int foo=JOptionPane.showOptionDialog(null,
str,
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
return foo==0;
}
String passwd;
JTextField passwordField=(JTextField)new JPasswordField(20);
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return true; }
public boolean promptPassword(String message){
Object[] ob={passwordField};
int result=
JOptionPane.showConfirmDialog(null, ob, message,
JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION){
passwd=passwordField.getText();
return true;
}
else{ return false; }
}
public void showMessage(String message){
JOptionPane.showMessageDialog(null, message);
}
final GridBagConstraints gbc =
new GridBagConstraints(0,0,1,1,1,1,
GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE,
new Insets(0,0,0,0),0,0);
private Container panel;
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
panel = new JPanel();
panel.setLayout(new GridBagLayout());
gbc.weightx = 1.0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridx = 0;
panel.add(new JLabel(instruction), gbc);
gbc.gridy++;
gbc.gridwidth = GridBagConstraints.RELATIVE;
JTextField[] texts=new JTextField[prompt.length];
for(int i=0; i<prompt.length; i++){
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.weightx = 1;
panel.add(new JLabel(prompt[i]),gbc);
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 1;
if(echo[i]){
texts[i]=new JTextField(20);
}
else{
texts[i]=new JPasswordField(20);
}
panel.add(texts[i], gbc);
gbc.gridy++;
}
if(JOptionPane.showConfirmDialog(null, panel,
destination+": "+name,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE)
==JOptionPane.OK_OPTION){
String[] response=new String[prompt.length];
for(int i=0; i<prompt.length; i++){
response[i]=texts[i].getText();
}
return response;
}
else{
return null; // cancel
}
}
}
}
当提示我输入“ username @ hostname”时,我输入RPI's_username @ Its_publicIP,然后在“ Enter -R port:host:hostport”中输入:12005:localhost:12005。我做对了吗?连接成功建立,因此我认为可以。
此外,我发现了这段代码here(尝试并成功了),它非常接近我想要的代码,但是它与shell兼容,我想直接与服务器端的代码进行通信。
public class TestShell {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
String host = null;
final Session session = jsch.getSession("user", "remotecomputer", 22);
session.setPassword("fluffybunnyslippers");
session.setConfig("StrictHostKeyChecking", "no");
session.connect(30000); // making a connection with timeout.
final Channel channel = session.openChannel("shell");
PipedInputStream pis = new PipedInputStream();
final PipedOutputStream pos = new PipedOutputStream(pis);
channel.setInputStream(pis);
channel.setOutputStream(new OutputStream() {
private int cmdIndx = 0;
private String[] cmds = {
"ls\n",
"cd ..\n",
"ls\n",
"exit\n"
};
private String line = "";
@Override
public void write(int b) throws IOException {
char c = (char) b;
if (c == '\n') {
logout(line);
System.out.print(line);
line = "";
} else {
line += c;
logout(line);
if (line.endsWith("$ ")) {
String cmd = cmds[cmdIndx];
cmdIndx++;
pos.write(cmd.getBytes());
}
}
}
public void logout(String line) {
if (line.startsWith("logout")) {
System.out.println("...logout...");
channel.disconnect();
session.disconnect();
System.exit(0);
}
}
});
channel.connect(3 * 1000);
} catch (Exception e) {
System.out.println(e);
}
}
}
Rpi(服务器)位于具有公共IP的路由器上。路由器在端口12005上设置了端口转发,该端口将数据发送到我的RPI所在的本地IP(以及端口12005)。路由器还将端口12005公开为公共端口,可能没有必要,如果实现了我要尝试的端口,我将关闭它。 客户端只是通过移动热点在wifi上。
有人可以给我一些关于如何使用现有的,有效的SSH隧道直接从套接字读取/写入通信的建议吗?我是通过互联网交流的初学者。