File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ const { Client } = require ( "ssh2" ) ;
2+
3+ export const executeSSHCommand = async (
4+ command : string ,
5+ host : string ,
6+ port : number ,
7+ username : string ,
8+ password : string
9+ ) : Promise < string > => {
10+ return new Promise ( ( resolve , reject ) => {
11+ const conn = new Client ( ) ;
12+ conn
13+ . on ( "ready" , ( ) => {
14+ conn . exec ( command , ( err : any , stream : any ) => {
15+ if ( err ) {
16+ conn . end ( ) ;
17+ return reject ( err ) ;
18+ }
19+
20+ let stdout = "" ;
21+ let stderr = "" ;
22+
23+ stream
24+ . on ( "close" , ( code : number ) => {
25+ conn . end ( ) ;
26+ if ( code === 0 ) {
27+ resolve ( stdout ) ; // Return the command output
28+ } else {
29+ reject ( new Error ( stderr ) ) ;
30+ }
31+ } )
32+ . on ( "data" , ( data : { toString : ( ) => string } ) => {
33+ stdout += data . toString ( ) ;
34+ } )
35+ . stderr . on ( "data" , ( data : { toString : ( ) => string } ) => {
36+ stderr += data . toString ( ) ;
37+ } ) ;
38+ } ) ;
39+ } )
40+ . on ( "error" , ( err : any ) => {
41+ console . error ( "SSH Error:" , err ) ;
42+ reject ( err ) ;
43+ } )
44+ . connect ( {
45+ host,
46+ port,
47+ username,
48+ password,
49+ } ) ;
50+ } ) ;
51+ } ;
You can’t perform that action at this time.
0 commit comments