期待,Bash和kpcli

时间:2015-12-02 15:35:31

标签: bash shell expect

我编写了一个脚本,使用kpcli和expect连接到本地keepass数据库,从数据库中获取凭据,然后通过ssh连接。该脚本有效但在通过SSH成功​​登录到远程主机后,会话在大约5秒后死亡。

 #!/bin/bash

 firewall="$1"
 keepass_password="******"
 keepass_db="/media/sf_VM_shared/kdb.kdb"
 keepass_fw_dir="General/Network/Firewalls/SSH"
 firewall_user="admin"


echo -e "\n"
echo "Connecting to keepass Database..."

function get_creds {
  expect <<- DONE
     set timeout 10
     spawn kpcli
     match_max 100000000
     expect  "kpcli:/>"
     send    "open $keepass_db\n"
     expect  "password:"
     send    "$keepass_password\n"
     expect  ">"
     send    "cd $keepass_fw_dir\n"
     expect  "SSH>"
     send    "show -f $firewall\n"
     expect  ">"
DONE

}

credentials=$(get_creds)
ssh_info=$(echo "$credentials" | grep 'Title:\|Pass:\|Notes:' | sed -e 's/^.*:       //')
ip_address=$(echo "$ssh_info" | awk 'NR==3')
firewall_name=$(echo "$ssh_info" | awk 'NR==1')
firewall_pass=$(echo "$ssh_info" | awk 'NR==2')
echo -e "\n"
echo "------Firewall Information-------"
echo -e Firewall IP:'\t \t'         "$ip_address"
echo -e Firewall Name:'\t \t'           "$firewall_name"
echo -e Firewall Password:'\t'          "$firewall_pass"
echo "----------------------------------"
echo -e "\n"
echo "Connecting to firewall module with user "admin"..."

function ssh_connect {
expect <<- DONE
spawn ssh -v -oStrictHostKeyChecking=no -oCheckHostIP=no admin@$ip_address
expect  "password"
      sleep 5
      send  "$firewall_pass\n"
      expect continue
      expect eof

DONE
}

ssh_connect

2 个答案:

答案 0 :(得分:2)

我认为你指的是你的ssh_connect函数,我进一步假设你希望ssh会话在你自己验证后是交互式的。您需要expect interact命令才能将控制权传递给用户。

function ssh_connect {
    expect <<- DONE
        spawn ssh -v -oStrictHostKeyChecking=no -oCheckHostIP=no admin@$ip_address
        expect  "password"
        send -- "$firewall_pass\r"
        interact
DONE
}
  • 期望为“击中回车”发送回车\r,这是惯用的。
  • 使用send -- "$variable"中的双连字符来防止变量的第一个字符为连字符时的情况。

答案 1 :(得分:0)

我设法使用以下内容:

expect -c '
spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no admin@'$ip_address'
expect "(password)"
send '$firewall_pass'
expect "(*)"
interact'