用 slack 和 hubot 搭建運維機器人【ubuntu】


1、安裝nodejs包管理工具npm

apt-get  install npm     ------ubuntu 中剛安裝的npm版本比較低,需要進行升級  
npm -g install npm@3.10.7 //升級到指定版本

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

2、安裝nodejs

npm install -g n
n stable  //安裝nodejs的最新穩定版本,也可以安裝指定版本: n v6.6.0

 

3、安裝hubot

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

4、創建配置hubot目錄

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
hubot目錄下的external-scripts.json文件中把有關herokuredis的兩行刪掉就行了,否則老是會報幾個警告。
然后,再把hubot-scripts.json刪掉,目前我們暫時還用不到它:rm -f hubot-scripts.json

 5、啟動hubot服務

現在可以正式啟動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

6、連接hubot和slack

1、首先需要在slack 上安裝好hubot的插件,它會自動生成一個token,把這個token記錄下來,輸入:
env HUBOT_SLACK_TOKEN=xoxb-你的token ./bin/hubot --adapter slack

注釋:這時候hubot就啟動起來,等待接收命令了。但是由於hubot缺省加入的是slack#general頻道,如果你改掉了頻道名字,或者刪掉了這個頻道的話,你需要重新邀請小機器人進入一個新的頻道,否則沒法對話。

2、現在可以在slack客戶端,通過下面的命令和hubot進行對話:
hubot help

 7、讓hubot保持在線

但是如果這時候我們關掉ssh的話,小機器人就掉線了,怎么辦呢?可以用nohup的方法讓它留在后台,也可以用tmux:
yum install tmux
tmux new -s hubot
在tmux里執行上面的命令,然后按ctrl+b,然后再按d退出。如果再想進去,可以執行:
tmux a
-t hubot

8、讓hubot執行shell腳本

     我們需要小機器人來執行一些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" "$@"

 

 

 

 

 

 

 

 

 

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM