我有一个 ubuntu vps,其中包含以下详细信息: 用户名:root 主机:abc.domain.xyz 端口:2222 密码授权
我需要我自己的 ssh 上的 vpn 客户端应用程序(如 napsternetV 或 Netmod)——只需 SSH 连接
我找到了 JSch 库,但我无法将此库连接到 Android VpnService 并通过 ssh 发送所有流量
经过多次尝试,我找到了这段代码:
public class MyVpnService extends VpnService {
private Thread mThread;
private boolean mIsRunning;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("soheil", "onStartCommand");
// Start a new thread that establishes the SSH connection and routes traffic through it
mThread = new Thread(new Runnable() {
@Override
public void run() {
try {
// Create an SSH connection
JSch jsch = new JSch();
Session session = jsch.getSession("root", "abc.domain.xyz", 2222);
session.setPassword("12345");
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
// Forward all traffic through the SSH connection
session.setPortForwardingR(2222, "localhost", 5678);
// Get the local and remote ports
int localPort = session.getAssignedLocalPort();
int remotePort = Integer.parseInt(session.getPortForwardingL()[0]);
// Configure the VPN interface
Builder builder = new Builder();
builder.addAddress("10.0.0.2", 24);
builder.addRoute("0.0.0.0", 0);
builder.setSession(String.valueOf(session));
ParcelFileDescriptor vpnInterface = builder.establish();
// Route all traffic through the VPN interface
runVpn(vpnInterface, localPort, remotePort);
} catch (Exception e) {
e.printStackTrace();
}
}
});
mThread.start();
mIsRunning = true;
return START_STICKY;
}
private void runVpn(ParcelFileDescriptor vpnInterface, int localPort, int remotePort) {
try {
byte[] packet = new byte[4096];
DatagramChannel tunnel = DatagramChannel.open();
tunnel.connect(new InetSocketAddress("127.0.0.1", localPort));
while (mIsRunning) {
vpnInterface.read(packet);
ByteBuffer buffer = ByteBuffer.wrap(packet);
tunnel.write(buffer);
buffer.clear();
tunnel.read(buffer);
vpnInterface.write(packet);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (vpnInterface != null) {
vpnInterface.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
但我得到了错误:
vpnInterface.read()
和vpnInterface.write()
和session.getAssignedLocalPort()