utils/sshcmd.sh

#! /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 $?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值