const node_ssh = require("node-ssh"); const config = require("./config"); const path = require("path"); const fs = require("fs"); console.log(process.argv.join(" ")); let host = process.argv[2]; let index = process.argv[3]; console.log(index + "号机 " + host); let jump_server = new node_ssh(); jump_server .connect({ host: "173.242.117.220", username: "root", password: "6EdUaZZCs63l", port: 26160 }) .then(client => { client.connection.forwardOut( "127.0.0.1", 12345 + index, "47.244.39.44", 22, function(err, stream) { if (err) { console.log("跳板机连接失败" + err); return jump_server.end(); } console.log("跳板机连接成功"); start(stream); } ); }); function start(stream) { ssh = new node_ssh(); let conf = { host: host, username: "root", port: 22, password: config.password }; if (stream) { conf = { sock: stream, username: "root", password: config.password }; } ssh.connect(conf) .then(async function() { let option = { cwd: "/root", onStdout(chunk) { console.log(chunk.toString("utf8")); }, onStderr(chunk) { console.log(chunk.toString("utf8")); } }; const failed = []; const successful = []; let status = await ssh.putDirectory(__dirname, "/root/autoTrade", { recursive: true, concurrency: 30, validate: function(itemPath) { const baseName = path.basename(itemPath); return ( baseName.substr(0, 1) !== "." && baseName !== "node_modules" // do not allow dot files ); // do not allow node_modules }, tick: function(localPath, remotePath, error) { if (error) { failed.push(localPath); } else { successful.push(localPath); } } }); console.log( "the directory transfer was", status ? "successful" : "unsuccessful" ); console.log("failed transfers", failed.join("\n")); console.log("successful transfers", successful.join("\n")); let nodeInstalled = false; try { await ssh .exec("node", ["-v"], { cwd: "/root", onStdout(chunk) { console.log(chunk.toString("utf8")); }, onStderr(chunk) { console.log(chunk.toString("utf8")); } }) .catch(e => { console.log(e); }); } catch (e) { console.log("安装node"); await ssh.execCommand( "curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -", option ); await ssh.execCommand("sudo apt-get install -y nodejs", option); console.log("node安装完成"); } await ssh .execCommand("npm install", { ...option, cwd: "/root/autoTrade" }) .catch(e => { console.log("npm install failed"); }); await ssh .execCommand("ls -la", { ...option, cwd: "/root/autoTrade" }) .catch(e => { console.log("ls -la failed"); }); await ssh .execCommand("killall node", { ...option, cwd: "/root/autoTrade" }) .catch(e => { console.log("killall node failed"); }); await ssh .execCommand(`node index.js ${index}`, { ...option, cwd: "/root/autoTrade" }) .catch(e => { console.log("node index.js failed"); }); }) .catch(e => { console.log(e); }); }