const { Client } = require( 'ssh2' );
-const fs = require('fs').promises; // Use promises
module.exports = {
createClient:( req, res, next ) => {
res.status( 500 ).json( { error:`SSH connection failed: ${ err.message }` } );
} ).connect( sshConfig );
}, getClients:async ( req, res, next ) => {
- const statusContent = await fs.readFile('/var/log/openvpn/openvpn-status.log', 'utf8');
- const clients = [];
- let inClientList = false;
-
- console.log('status content: ', statusContent);
-
- statusContent.split('\n').forEach(line => {
- console.log('line: ', line);
- if (line.startsWith('Common Name,Real Address,Bytes Received,Bytes Sent,Connected Since')) {
- inClientList = true;
- return;
- }
- if (line.startsWith('ROUTING TABLE') || line === '') {
- inClientList = false;
- return;
- }
- if (inClientList) {
- const [common_name, real_address, bytes_received, bytes_sent, connected_since] = line.split(',');
- console.log('client info: ', common_name, real_address, bytes_received, bytes_sent, connected_since);
- clients.push({
- common_name,
- virtual_address: real_address.split(':')[0],
- bytes_received,
- bytes_sent,
- connected_since,
- });
- }
- });
- /*const conn = new Client();
+ const conn = new Client();
conn.on( 'ready', () => {
const command = `cat /var/log/openvpn/openvpn-status.log`;
conn.exec( command, ( err, stream ) => {
stream.on( 'close', ( code ) => {
conn.end();
if (code === 0) {
- const clients = output.split( '\n' ).filter( line => line.startsWith( 'Common Name,Real Address,Bytes Received,Bytes Sent,Connected Since' ) ).map( line => {
+ console.log( 'output: ', output );
+ const lines = output.split( '\n' );
+ const sIndex = lines.findIndex( line => line.startsWith( 'Common Name,Real Address,Bytes Received,Bytes Sent,Connected Since' ) );
+ const eIndex = lines.findIndex( line => line.startsWith( 'ROUTING TABLE' ) );
+ const clients = lines.slice( sIndex + 1, eIndex ).map( line => {
const parts = line.split( ',' );
+ console.log( 'parts: ', parts );
return { name:parts[1], ip:parts[2], connectedSince:parts[8] };
} );
+ /*const clients = output.split( '\n' ).filter( line => line.startsWith( 'Common Name,Real Address,Bytes Received,Bytes Sent,Connected Since' ) ).map( line => {
+ const parts = line.split( ',' );
+ return { name:parts[1], ip:parts[2], connectedSince:parts[8] };
+ } );*/
res.json( { clients } );
} else {
res.status( 500 ).json( { error:`Command failed: ${ output }` } );
} );
} ).on( 'error', ( err ) => {
res.status( 500 ).json( { error:`SSH connection failed: ${ err.message }` } );
- } ).connect( sshConfig );*/
+ } ).connect( sshConfig );
}
};
\ No newline at end of file