Skip to content

Instantly share code, notes, and snippets.

@ojacques
Created July 22, 2021 11:40
Show Gist options
  • Save ojacques/b996d5450d99682aa0670d9ec9e3ba05 to your computer and use it in GitHub Desktop.
Save ojacques/b996d5450d99682aa0670d9ec9e3ba05 to your computer and use it in GitHub Desktop.
Hubot: Execute ssh command asynchronously and provide nicely formatted output on slack
# Description:
# Execute ssh command asynchronously and provide nicely formatted output on slack
#
# Commands:
# hubot my_ssh_command server - Your ssh command to run on host
#
module.exports = (robot) ->
robot.respond /my_ssh_command (.*)/i, (msg) ->
server = msg.match[1]
msg.send "Running command on #{server}..."
spawn = require('child_process').spawn
# Replace long running test command below!
ssh = spawn "ssh", ["-o", "StrictHostKeyChecking=no", "user@#{server}", "cd ~ && ls -alrt && find / -name default 2>/dev/null"]
ssh.stdout.on "data", (data) ->
respond msg, "#{server}", data.toString()
ssh.stderr.on "data", (data) ->
respond msg, "#{server}", data.toString()
ssh.on "exit", (code) ->
if code is 0
respond msg, "#{server}", ":tada: Command successful!"
respond = (msg, server, str, wrap = '```') ->
len = 3000
_size = Math.ceil(str.length / len)
_ret = new Array(_size)
_offset = undefined
_i = 0
while _i < _size
_offset = _i * len
_ret[_i] = str.substring(_offset, _offset + len)
_i++
msg.send({
attachments: [{
pretext: "`#{server}`",
thumb_url: "https://www.jeedom.com/market/filestore/market/script/images/ssh_command.sh_icon.png",
text: "#{wrap}#{_ret[0]}#{wrap}",
mrkdwn_in: ["text", "pretext"]
}],
username: process.env.HUBOT_SLACK_BOTNAME,
as_user: true,
});
unless _ret.length == 1
x = 1
setInterval (->
msg.send "#{wrap}#{x+1} of #{_ret.length}\n#{_ret[x]}#{wrap}"
if _ret.length == x+1
clearInterval this
else
x++
), 8000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment