#! /bin/bash
#定义参数,后面parse调用这个脚本时添加的参数会用到.
execcmd=
machineip=
loginuser=
loginpassword=
sshcmd_comm()
{
#获取位置参数,这里应该不用加双引号
cmd="$1"
testip="$2"
password="${3}"
user="${4}"
timeout=180
#判断$1 是否为null
if [ "$1x" = "x" ]; then
echo "ssh_password cmd targetip [password] [user]"
return 1
fi
#判断testip 是否为null
if [ "x${testip}" = "x" ]; then
testip=$testmachine
fi
#cmd=${cmd//\"/\\\"}
#cmd=${cmd//\$/\\\$}
#testip 或者cmd 为null的话,则退出脚本
if [ "x$testip" = "x" -o "x${cmd}" = "x" ]; then
#
echo "isup time testmachine [password] [user]"
exit 1
fi
expect <<-END1
set timeout -1
#通过ssh在远程机器上执行命令。例如在107 上执行ssh 命令
#tiantao@EstBuildSvr1:~/kernel/kernel/arch/arm64$ ssh tiantao@192.168.1.107 ls
#tiantao@192.168.1.107's password:
#a.py
#beta 4 installer failed.docx
#bmc.sh
#执行这个远程命令
spawn ssh -o "ConnectTimeout ${timeout}" ${user}@${testip} "${cmd}"
expect {
"Are you sure you want to continue connecting (yes/no)?" {
send "yes\r"
expect -re "\[P|p]assword:"
send "${password}\r"
}
-re "\[P|p]assword:" {
send "${password}\r"
}
timeout {
#send_user 用于输出log 类似于echo
send_user "connection to $targetip timed out: \$expect_out(buffer)\n"
exit 13
}
eof {
#获得ssh 命令执行的结果
catch wait result
exit [lindex \$result 3]
}
}
expect {
eof {
catch wait result
exit [lindex \$result 3]
}
-re "\[P|p]assword:" {
send_user "invalid password or account. \$expect_out(buffer)\n"
exit 13
}
timeout {
send_user "connection to $targetip time out: \$expect_out(buffer)\n"
exit 13
}
}
END1
return $?
}
#定义一个函数
usage()
{
echo "Usage: sshcmd.sh -c "command" -m "machineip" [-u login_user] [-p login_password]"
}
#parse 调用这个脚本时候的可选参数
while getopts "c:m:p:u:h" OPTIONS
do
case $OPTIONS in
c) execcmd="$OPTARG";;
m) machineip="$OPTARG";;
u) loginuser="$OPTARG";;
p) loginpassword="$OPTARG";;
\?) echo "ERROR - Invalid Parameter"; echo "ERROR - Invalid parameter" >&2; usage; exit 1;;
*) echo "ERROR - Invalid Parameter"; echo "ERROR - Invalid parameter" >&2; usage; exit 1;;
esac
done
#判断execcmd或者machineip 是否为null
if [ "x$execcmd" = "x" -o "x$machineip" = "x" ]; then
usage
exit
fi
#调用前面定义的函数,执行ssh命令
sshcmd_comm "$execcmd" "$machineip" "$loginpassword" "$loginuser"
#返回执行的结果
exit $?
utils/sshcmd.sh
最新推荐文章于 2024-05-16 19:44:15 发布