前言
作为网络运维人员,通常需要管理几百台,甚至是上千台设备,经常需要登录设备做一些命令查询或者配置的操作,往往需要准备设备IP,账号,密码,每次登录工作繁琐,为了实现快速登录设备,所以编写了此shell脚本,通过事先预置设备信息,然后执行脚本,实现一键式登录,方便运维,提高工作效率。
一、实现原理
事先预置设备信息(关键参数:IP,账号,密码),并借助expect自动化交互套件,可以将ssh登录交互过程自动化完成。
二、使用步骤
使用方法:loginDevice.sh、loginDevice.exp、deviceinfo.txt,共3个文件放在同一目录下
注意事项:脚本需要expect环境支持
1.shell脚本
文件名:loginDevice.sh
#!/bin/bash
# -------------------------------------------------------------------------------
# Name:loginDevice.sh
# Author: wenhui.Cheng
# Description: 通过设备IP,或者检索的方法实现自动登录
# Version: v2.0
# Date: 2022-10-10
# -------------------------------------------------------------------------------
# 使用方法:loginDevice.sh、loginDevice.exp、deviceinfo.txt,共3个文件放在同一目录下
# 注意事项:脚本需要expect环境支持
echo "
┌──────────────────────────────────────────────────────────────────────┐
│ ∙ Linux下自动登录网络设备 ∙ │
│ (A tool for automatic device login) │
│ │
│ ∙ Description : 通过设备IP,或者检索的方法实现自动登录 │
│ ∙ Author : wenhui.Cheng │
│ ∙ E-Mail : 756942988@qq.com │
│ ∙ Version : v2.0 │
│ │
└──────────────────────────────────────────────────────────────────────┘
"
curdir=$(cd `dirname $0`; pwd)
cd $curdir
read -p "请输入【设备IP】或者【设备名称】,设备名称支持模糊查询(输入Q退出):" parameter1
if [[ $parameter1 = Q ]] || [[ $parameter1 = q ]]; then
exit 0
else
if ! echo $parameter1 | grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}.[0-9]\{1,3\}\.[0-9]\{1,3\}' ;then # 如果输入的参数不是IP,则
# 根据输入的参数,检索满足条件的数据,显示前8列,左对齐:column -t
grep -e 设备名称 -e $parameter1 deviceinfo.txt |awk '{for(i = 1; i <= 8; i++) printf("%s ", $i); printf("\n")}'| column -t
read -p "请输入设备编号(输入Q退出):" parameter2 # 继续输入参数,锁定唯一设备
if [[ $parameter2 = Q ]] || [[ $parameter2 = q ]]; then
exit 0
else
IP=`grep -E 【$parameter2】 deviceinfo.txt | awk '{print $5}'`
# LoginModel=`grep -E 【$parameter2】 deviceinfo.txt | awk '{print $8}'`
UserName=`grep -E 【$parameter2】 deviceinfo.txt | awk '{print $10}'`
PassWord=`grep -E 【$parameter2】 deviceinfo.txt | awk '{print $11}'`
./loginDevice.exp $IP $UserName $PassWord
fi
else
IP=$parameter1
UserName=`grep -w $parameter1 deviceinfo.txt | awk '{print $10}'` # -w 精确匹配,只显示全字符合的列
PassWord=`grep -w $parameter1 deviceinfo.txt | awk '{print $11}'`
./loginDevice.exp $IP $UserName $PassWord # 如果输入的参数是IP地址,则直接登录
fi
fi
2.exp脚本
文件名:loginDevice.exp
#! /usr/bin/expect
set IpAddress [lindex $argv 0]
set UserName [lindex $argv 1]
set PassWord [lindex $argv 2]
spawn ssh $UserName@$IpAddress
expect {
"*yes/no" { send "yes\r"; exp_continue}
"assword:" { send "$PassWord\r" }
}
interact
该脚本实现设备登录交互过程。
3.设备信息
文件名:deviceinfo.txt
编号 所属网络 区域 设备名称 设备IP 设备类型 设备厂商 设备型号 登录方式 登录账号 登录密码
【1】 城域网 台北 XXXX-MB-CMNET-BRAS02-HD-ME60 192.168.100.100 BRAS 华为 ME60-X16 SSH admin admin123456
【2】 城域网 台北 XXXX-MB-CMNET-BRAS03-MW-ME60 192.168.100.101 BRAS 华为 ME60-X16 SSH admin admin123456
【3】 城域网 台北 XXXX-MB-CMNET-BRAS04-CL-ME60 192.168.100.102 BRAS 华为 ME60-X16 SSH admin admin123456
...
总结
以上就是脚本所有内容,本文借助expect套件,实现快速便捷地登录网络设备,极大提升运维效率。