ssh登录远程服务器执行命令
@[toc]
前言
本文主要是说明如何通过ssh登录远程服务器,执行相关命令,并获取执行结果,并贴脚本源码。
参数说明
- serverIp=$1 #远程IP
- sshUser=$2 #SFTP用户
- sshPass=$3 #SFTP密码
- sshCmd=$4 #远程命令
脚本源码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| #!/bin/bash
shName=`basename $0`
serverIp=$1 sshUser=$2 sshPass=$3 sshCmd=$4
sysDate=`date +"%Y%m%d"`
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 "$@"
|
蚂蚁🐜再小也是肉🥩!