shell expect SSH用法一例

本文重点解决两个问题:

  1. 获取SSH远程执行命令的返回状态
  2. expect执行SSH时进程中不显示密码明文

先上Shell 代码:

export IP CMD SSH_PWD
expect << 'END'
# 关闭输出
log_user 0
set timeout 30
# 从系统变量获取数据
set ip "$env(IP)"
set cmd "$env(CMD)"
set pwd "$env(SSH_PWD)"
spawn ssh root@$ip "$cmd"
expect {
    "(yes/no)?"                           {send "yes\r";exp_continue}
    # 忽略大小写
    -nocase "password:"                   {send "$pwd\r";exp_continue}
    # 登录成功,打开输出
    -nocase "authentication successful"   {log_user 1;exp_continue}
    # 登录失败
    -nocase "authentication fail"         {exit 222}
    -nocase "permission denied"           {exit 222}
    eof
}
puts $expect_out(buffer)
lassign [wait] pid spawnid os_error_flag value
# 系统错误
if {$os_error_flag == -1} {
    puts "os errno: $value"
} else {
    # 返回 CMD 执行结果
    exit $value
}
END
exitCode=$?
if [ $exitCode -eq 222 ]; then
    echo 'log error'
elif [ $exitCode -ne 0 ]; then
    echo 'cmd error'
fi

获取执行结果的关键在于【wait】方法的使用:

wait [args]

delays until a spawned process (or the current process if none is named) terminates.

wait normally returns a list of four integers. The first integer is the pid of the process that was waited upon. The second integer is the corresponding spawn id. The third integer is -1 if an operating system error occurred, or 0 otherwise. If the third integer was 0, the fourth integer is the status returned by the spawned process. If the third integer was -1, the fourth integer is the value of errno set by the operating system. The global variable errorCode is also set.

【wait】:延迟直到一个spawn进程结束。返回4个数值:

  1. expect 进程 pid
  2. spawn 线程 id
  3. OS状态值(-1:系统错误,0:正常)
  4. spawn命令返回值(OS值为 -1时返回OS错误代码,为 0时返回CMD退出值)

参考:expect manHow to get the exit code of spawned process in expect shell script?

开头的两个问题都得到了解决:

  • 使用 wait 获取SSH 远程执行命令的返回状态,登录失败也可以通过指定状态码(222)标识;
  • 使用 env 读取外部变量到expect 变量中,从而 PS 不会显示 密码明文。

转载于:https://my.oschina.net/cwalet/blog/779930

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值