shell实现ssh登录服务器并查看日志,切换分支

登录服务器并且查看日志

正常执行步骤为(伪代码):

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值