用 slack 和 hubot 搭建运维机器人【ubuntu】

一、安装nodejs包管理工具npmnode

apt-get  install npm     ------ubuntu 中刚安装的npm版本比较低,须要进行升级  
npm -g install npm@3.10.7 //升级到指定版本

npm -g install npm //升级到最新版本
 

二、安装nodejsredis

npm install -g n
n stable  //安装nodejs的最新稳定版本,也能够安装指定版本: n v6.6.0

 

三、安装hubotshell

npm install -g hubot coffee-script yo generator-hubot

四、建立配置hubot目录npm

mkdir /root/hubot
cd /root/hubot
yo hubot
若是使用root用户安装,则须要对如下目录进行受权
chmod g+rwx /root /root/.config /root/.config/configstore
chown -R chown ubuntu /root/.config/configstore
chmod g+rwx /root/hubot chmod -R g+rwx /root/.npm

yo hubot // 若是是root用户安装,这步以前须要调整文件和目录权限.这步安装时若报错,能够尝试屡次安装的操做。

安装hubot,默认会带上heroku和redis,若是用不到能够卸载掉:

npm uninstall hubot-heroku-keepalive --save
在目录下的文件中把有关和的两行删掉就好了,不然总是会报几个警告。
而后,再把删掉,目前咱们暂时还用不到它:hubotexternal-scripts.jsonherokuredishubot-scripts.jsonrm -f hubot-scripts.json

 五、启动hubot服务json

如今能够正式启动hubot了: ./bin/hubot
试着执行几个测试命令:
hmbot> help
usage:
history 
exit, \q - close shell and exit
help, \? - print this usage
clear, \c - clear the terminal screen
hmbot> ping

六、链接hubot和slackubuntu

1、首先须要在slack 上安装好hubot的插件,它会自动生成一个token,把这个token记录下来,输入:
env HUBOT_SLACK_TOKEN=xoxb-你的token ./bin/hubot --adapter slack

注释:这时候就启动起来,等待接收命令了。可是因为缺省加入的是的频道,若是你改掉了频道名字,或者删掉了这个频道的话,你须要从新邀请小机器人进入一个新的频道,不然无法对话。

二、如今能够在slack客户端,经过下面的命令和hubot进行对话:
hubot helphubothubotslack#general

 七、让hubot保持在线bash

可是若是这时候咱们关掉ssh的话,小机器人就掉线了,怎么办呢?能够用nohup的方法让它留在后台,也能够用tmux:
yum install tmux
tmux new -s hubot
在tmux里执行上面的命令,而后按ctrl+b,而后再按d退出。若是再想进去,能够执行:
tmux a
-t hubot

八、让hubot执行shell脚本ssh

     咱们须要小机器人来执行一些shell脚本,因此须要安装:工具

npm install hubot-script-shellcmd
cp -R node_modules/hubot-script-shellcmd/bash ./

修改一下external-scripts.json,添加上如下模块:hubot-script-shellcmd。若是到此为止,你操做的步骤和我基本同样的话,你的external-scripts.json应该长的像这个样子:测试

[
  "hubot-diagnostics",
  "hubot-help",
  "hubot-google-images",
  "hubot-google-translate",
  "hubot-pugme",
  "hubot-maps",
  "hubot-rules",
  "hubot-shipit",
  "hubot-script-shellcmd"
]

测试shell脚本:

配置完毕上面的东东,这里须要重启下hubot服务:
nohup ./bin/hubot --adapter slack & #执行启动脚本时,千万不要进入bin目录,要在bin目录的外面执行启动脚本,不然启动失败。
而后在slack客户端经过以下命令,对hubot说话: @hmbot run ping #//hmbot 为hubot的申请名称,run 能够经过HUBOT_SHELLCMD_KEYWORD配置。

 

 

 附录hubot脚本:

#!/bin/sh

set -e

npm install
export PATH="node_modules/.bin:node_modules/hubot/node_modules/.bin:$PATH"
export HUBOT_SLACK_TOKEN="token"        #slack上面申请的token
export HUBOT_SHELLCMD_KEYWORD="run"     #修改命令虎符

exec node_modules/.bin/hubot --name "hmbot" "$@"
相关文章
相关标签/搜索