creeperxts.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /* eslint-disable strict */
  2. const _ = require('lodash');
  3. // const fs = require('fs');
  4. const Client = require('ssh2').Client;
  5. const fs = require('fs');
  6. const moment = require('moment');
  7. const { CrudService } = require('naf-framework-mongoose/lib/service');
  8. class CreeperxtsService extends CrudService {
  9. async creeper() {
  10. // 链接linux服务器
  11. console.log('进入连接linux服务器');
  12. // await this.sshcon();
  13. await this.sshcon();
  14. }
  15. async sshcon() {
  16. const nowdate = moment().locale('zh-cn').format('YYYY-MM-DD');
  17. const conn = new Client();
  18. const pathDir = this.app.config.dataDir;
  19. if (!fs.existsSync(pathDir)) {
  20. fs.mkdirSync(pathDir);
  21. }
  22. conn.on('ready', function() {
  23. conn.exec('top -bcn 1', function(err, stream) {
  24. if (err) throw err;
  25. stream.on('close', function(code, signal) {
  26. conn.end();
  27. }).on('data', function(data) {
  28. const path_ = `${pathDir}/top${nowdate}.txt`;
  29. fs.access(path_, err => {
  30. if (err) {
  31. fs.writeFile(path_, data.toString(), function(err) {
  32. if (err) throw err;
  33. });
  34. } else {
  35. fs.appendFile(path_, data.toString(), function(err) {
  36. if (err) throw err;
  37. });
  38. }
  39. });
  40. }).stderr.on('data', function(data) {
  41. console.log('STDERR: ' + data);
  42. });
  43. });
  44. }).connect({
  45. host: '192.168.10.102',
  46. port: 42973,
  47. username: 'free_ly',
  48. password: '1qaz2wsx',
  49. // privateKey: require('fs').readFileSync('/home/admin/.ssh/id_dsa')
  50. });
  51. }
  52. }
  53. module.exports = CreeperxtsService;