ssh登录远程服务器执行命令

ssh登录远程服务器执行命令

前言

本文主要是说明如何通过ssh登录远程服务器,执行相关命令,并获取执行结果,并贴脚本源码。

参数说明

  • serverIp=$1 #远程IP
  • sshUser=$2 #SFTP用户
  • sshPass=$3 #SFTP密码
  • sshCmd=$4 #远程命令

脚本源码

#!/bin/bash
##############################################################
# AUTHOR: 黑半白
# Desc  : ssh登录远程服务器执行命令
##############################################################

#获取脚本名称
shName=`basename $0`

#接收参数
serverIp=$1 #远程IP
sshUser=$2  #SFTP用户
sshPass=$3  #SFTP密码
sshCmd=$4   #远程命令

#当前系统日期-yyyymmdd
sysDate=`date +"%Y%m%d"`
#当前系统时间-hhmmss
sysTime=`date +"%H%M%S"`

#定义日志文件路径和日志文件名
logPath=/app/log/public/sshCmd/${sysDate}
logFile=${logPath}/sshCmd_${sysTime}.log

#定义日志函数
Log()
{
    
    
    createTime=`date  +"%Y-%m-%d %H:%M:%S"`
    echo "[${createTime}] $*" |tee -a ${logFile} 2>/dev/null 
}

#定义检查创建目录函数
CheckDir()
{
    
    
    if [ ! -d $1 ]; then
        mkdir_log=` mkdir -p -m 775 $1 `
        if [ $? -ne 0 ]; then
            echo "[ERROR]: Directory [$1] create fail, please check..."
            exit 1
        fi    
    fi
}

#检查日志目录
CheckDir "${logPath}"

#检查参数个数
if [ $# -ne 4 ]; then
    Log "[Error] 参数输入错误, 请检查!"
    Log "[Error] Eg:"
    Log "[Error] sh ${shName} 远程IP ssh用户 ssh密码 远程命令"
    exit 1
fi

#定义主函数
execute_ssh_cmd()
{
    
    
    local serverIp=$1
    local sshUser=$2
    local sshPass=$3
    local sshCmd=$4

    log_file=${logPath}/execute_ssh_cmd_${sysTime}.log
    #如果密码中包含$符号,需要转义以下
    sshPass=`echo ${
     
     sshPass} | sed 's/\\$/\\\\$/g'`
    
    expect <<EOF > ${log_file}
    #超时时间,因为远程命令执行时间不定,设定不超时(根据实际情况而定)
    set timeout -1
    spawn ssh ${sshUser}@${serverIp} "${sshCmd}"
    expect {
    
    
        "(yes/no)?"
        {
    
    
            send "yes\n"
            expect "*password:" {
    
     send "${sshPass}\n"}
        }
        "*assword:"
        {
    
    
            send "${sshPass}\n"
        }
        #IP地址输入不对或网络不通
        "No route to host"
        {
    
    
            send "IP地址不对或网络不通\n"
        }
    }
    expect {
    
    
        "please try again"
        {
    
    
            #密码输入不正确,因为前面设定无超时时间限制,需要发送键盘命令Ctrl+C,终止当前操作
            send "\03\n"
        }
    }
    #获取远程命令执行结果
    catch wait result
    exit [lindex \$result 3]

EOF
    #获取远程执行命令返回值
    sshRet=$?
    Log "=================远程命令执行日志信息如下================="
    cat ${log_file}|tee -a ${logFile}
    echo ""

    cat ${log_file} | grep -iE "denied|No such file or directory|No route to host" >/dev/null
    
    if [ $? -eq 0 -o $sshRet -ne 0 ];then
        Log "[Error] 脚本执行失败, 请检查!"
        Log "[Error] 日志文件: [${logFile}]"
        exit 1
    fi
    
    Log "远程执行命令返回值为[$sshRet]"
    Log "[Info] 脚本执行成功."
}

Log "[Info] 开始执行脚本:"
Log "[Info] serverIp : ${serverIp}"
Log "[Info] sshUser  : ${sshUser}"
Log "[Info] sshPass  : ${sshPass}"
Log "[Info] cmd      : ${sshCmd}"
echo "请等待远程命令运行完成"

execute_ssh_cmd "$@"

结语

如有需要请拿走,若转载请追加本文链接哦!

能学一点是一点,至少不是0!

Over!

猜你喜欢

转载自blog.csdn.net/weixin_49192027/article/details/112854412