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

本文遵循BY-SA版权协议,转载请附上原文出处链接。


本文作者: 黑伴白

本文链接: http://heibanbai.com.cn/posts/a9f7c484/

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
##############################################################
# 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 "$@"

蚂蚁再小也是肉🥩!


ssh登录远程服务器执行命令
http://heibanbai.com.cn/posts/a9f7c484/
作者
黑伴白
发布于
2021年1月19日
许可协议

“您的支持,我的动力!觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭”

微信二维码

微信支付

支付宝二维码

支付宝支付