gpt4 book ai didi

node.js - 如何在nodejs中使用openvpn?

转载 作者:搜寻专家 更新时间:2023-10-31 23:20:28 24 4
gpt4 key购买 nike

我有 NodeJS 应用程序,想开始在其中使用 OpenVPN 连接。为此,我在 npm 上找到了 2 个模块(openvpn-client 和 openvpn-bin)——但它们中的任何一个都没有好的文档和示例,但我尽可能地尝试使用它们,但没有成功。

我有 Ipvanish 帐户(登录名/密码)和 540 个 .opvn 文件,我可以使用。我试试这个:

var openvpnmanager = require('node-openvpn');
var openvpnBin = require('openvpn-bin');
var path = require('path');

var filePath = path.normalize('../geo/ipvanish/ipvanish-AU-Sydney-syd-a16.ovpn');

var opts = {
host: 'syd-a16.ipvanish.com', // normally '127.0.0.1', will default to if undefined
port: 443, //port openvpn management console
timeout: 60000, //timeout for connection - optional, will default to 1500ms if undefined
config: filePath
};
var auth = {
user: 'email@gmail.com',
pass: 'password'
};

var openvpn = openvpnmanager.connect(opts)

openvpn.on('connected', function() {
// will be emited on successful interfacing with openvpn instance
console.log('connected')
openvpnmanager.authorize(auth).then(function(res){

});
});

最佳答案

我使用这种更有效的方式(通过它我可以将 OpenVPN 连接作为子进程处理,即时关闭并重新连接)。

var exec = require('child_process').exec;
var psTree = require('ps-tree');

var kill = function (pid, signal, callback) {
signal = signal || 'SIGKILL';
callback = callback || function () {};
var killTree = true;
if(killTree) {
psTree(pid, function (err, children) {
[pid].concat(
children.map(function (p) {
return p.PID;
})
).forEach(function (tpid) {
try { process.kill(tpid, signal) }
catch (ex) { }
});
callback();
});
} else {
try { process.kill(pid, signal) }
catch (ex) { }
callback();
}
};

var ovpnProcess = null;

if(ovpnProcess != null){
console.log('close connection');
var isWin = /^win/.test(ovpnProcess.platform);
if(!isWin) {
kill(ovpnProcess.pid);
} else {
var cp = require('child_process');
cp.exec('taskkill /PID ' + ovpnProcess.pid + ' /T /F', function (error, stdout, stderr) {
// more debug if you need
// console.log('stdout: ' + stdout);
// console.log('stderr: ' + stderr);
// if(error !== null) {
// console.log('exec error: ' + error);
// }
});
}
}

//打开连接我使用这个代码:

ovpnProcess = exec('openvpn ipvanish/'+account.ip+'.ovpn');
ovpnProcess.stdout.on('data', function(data) {
console.log('stdout: ' + data);
});
ovpnProcess.stderr.on('data', function(data) {
console.log('stdout: ' + data);
});
ovpnProcess.on('close', function(code) {
console.log('closing code: ' + code);
});

关于node.js - 如何在nodejs中使用openvpn?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38881067/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com