登录服务器并且查看日志
正常执行步骤为(伪代码):
ssh root@xxx.xxx.xxx.xxx
password
cd xxx
nowDate=date "+%Y%m%d" #获取时间
cat ../log/xx_${nowDate}.log | grep '${logId}'
期待实现的是一个脚本,执行./sshLog.sh logId即可查看日志
实现方式
工具安装
如果直接执行,在ssh连接成功后剩余的脚本将不会继续执行,这里借助expect和spawn工具来实现ssh连接后继续执行操作。
工具安装方式参考Expect工具的安装及使用方法
其中最核心的内容如下:
Expect工具是依赖tcl的,所以也需要安装tcl。
首先下载并安装tcl,这里安装8.4.19版本。
# wget https://sourceforge.net/projects/tcl/files/Tcl/8.4.19/tcl8.4.19-src.tar.gz
# tar zxvf tcl8.4.19-src.tar.gz
# cd tcl8.4.19/unix && ./configure
# make
# make install
然后下载expect并安装。
# wget http://sourceforge.net/projects/expect/files/Expect/5.45/expect5.45.tar.gz
# tar zxvf expect5.45.tar.gz
# cd expect5.45
# ./configure --with-tcl=/usr/local/lib --with-tclinclude=../tcl8.4.19/generic
# make
# make install
# ln -s /usr/local/bin/expect /usr/bin/expect
注意这里的configure命令需要使用–with-tclinclude选项传入tcl安装包中的generic文件夹路径。
安装完成之后运行expect命令,查看是否安装成功。
具体实现
expect工具安装完成后实现就很简单了,代码如下:
#!/bin/bash
nowDate=`date '+%Y%m%d'`
logId=${1}
/usr/bin/expect <<EOF
# 连接ssh
spawn ssh -p xxport root@xxx.xxx.xxx.xxx
expect "*password:"
send "xxxxxxxx\n"
# 进入到后端目录
expect "*root*"
send "cd xxPath\n"
# 确认一下路径
send "pwd\n"
# 查看日志
send "cat ../log/xxxx_${nowDate}_json.log | grep '${logId}'\n"
expect eof
EOF
切换分支
切换分支的基本操作为(伪代码):
ssh root@xxx.xxx.xxx.xxx
password
cd xxx
cd ../branch_x
git branch # 查看当前处于哪个分支
git fetch origin git_branch_xxx # fetch分支代码
git checkout git_branch_xxx
exit
具体实现
#!/usr/bin/expect
# 连接ssh
spawn ssh -p xxPort root@xxx.xxx.xxx.xxx
expect "*password:"
send "xxxxxxxxxx\n"
# 进入到后端目录
expect "*root*"
send ".xxPath\n"
# 确认一下路径
send "pwd\n"
set branch [lindex $argv 0]
set gitBranch [lindex $argv 1]
# 切换分支
send "cd ../${branch}\n"
# 查看当前所处分支
send "git branch\n"
# 拉取代码
send "git fetch origin ${gitBranch}\n"
send "git checkout ${gitBranch}\n"
send "exit"
expect eof