【问题标题】:Expect Script - enter password then run bash script期望脚本 - 输入密码然后运行 ​​bash 脚本
【发布时间】:2018-07-05 03:30:43
【问题描述】:

我有一个 bash 脚本,它使用启动 ssh 进程的密码调用期望脚本:

#!/usr/bin/bash
/usr/bin/expect $PWD/sshScript.exp $SSHPASSWORD

expect 脚本调用 ssh 命令,等待提示输入密码并发送密码。

#!/usr/bin/expect
set password [lindex $argv 0];
spawn ssh -o "StrictHostKeyChecking no" username@host
expect "Enter your AD Password:" {
    send "$password\r"
}

我可以让远程服务器正确地 ssh 并显示[user@host ~]$,但我想在期望脚本中添加一种自动运行 bash 脚本的方法,该脚本存储在与其他两个脚本相同的位置。

我试过了

a) 将文件 scp 到远程并在服务器中调用它,但我似乎无法期望发送任何文本传递密码

b) 执行spawn ssh -o "StrictHostKeyChecking no" username@host < secondscript.sh发送脚本以运行,但在尝试运行脚本之前不会等待输入密码。

【问题讨论】:

标签: bash shell ssh tcl expect


【解决方案1】:

您可以将 bash 和 expect 脚本组合在一起,并使用它将第 3 个 bash 脚本复制到远程服务器,执行它并返回输出。 这是一个简单的未测试示例:

#!/bin/bash

[... other bash code here ...]

SCRIPT='/path/to/script/to/run/remotely.sh'
LOGIN='test'
IP='your ip or hostname'
LOCATION='/destination/path/to/script/to/run/remotely.sh'

### start expect part here, you may add '-d' after 'expect' for debug

/usr/bin/expect << EOD
### set a 3 minute timeout
set timeout 180
### copy the script you wish to run on the remote machine
spawn scp -o StrictHostKeyChecking=no -p $SCRIPT $LOGIN@$IP:$LOCATION
expect {
  timeout            { send_user "\n# TIMED OUT. HOST NOT REACHABLE #\n"; exit 3 }
  "*assword: "
}
send "your_password\r"
expect {
  "*assword: " { send_user "\n# Incorrect Password. Login Failed. #\n"; exit 4 }
  "100%" { send_user "\nFile copied\n" }
}

### ssh to remote server to run script
spawn ssh $LOGIN@$IP
expect {
  timeout        { send_user "\n# TIMED OUT. SSH DAEMON or PORT 22 CLOSED #\n"; exit 6 }
  "*assword: "
}
send "your_password\r"
expect {
  timeout        { send_user "\n# TIMED OUT. PROMPT NOT RECOGNISED! #\n"; exit 7 }
### expect the prompt symbol
  -re {[#>$] }
## execute your script on the remote machine
send "$LOCATION\r"
expect {
  "enter what you expect here" { send_user "\nRESULT: Message based on what you set the expect to read $IP\n" }
  -re {[#>$] }
}

[... other expect code here ... ]

### exit remote ssh session
send "exit\r"
### end of expect part of script 
EOD
### continue bash script here

[... other bash code here ...]

【讨论】:

  • 将expect 脚本作为here-document 放入bash 脚本会导致除了最简单的脚本之外的所有脚本都造成太多混乱。所以不要那样做。像 OP 那样使用单独的脚本文件(或在期望脚本中执行所有操作)是正确的方法。
  • 我不敢苟同,我相信拥有 1 个脚本来服务 1 个任务是有组织的方式来完成它。此外,在您的脚本中添加 cmets 以便读者能够理解正在执行的操作可以消除任何混淆。再说一次,我相信这是一个偏好问题,并且与该线程的重点无关。
猜你喜欢
  • 2019-09-04
  • 1970-01-01
  • 2014-09-20
  • 2012-05-23
  • 2015-11-28
  • 2018-07-07
  • 2012-05-17
  • 2016-02-28
  • 1970-01-01
相关资源
最近更新 更多