点击这里给我发消息 点击这里给我发消息
首页 > 行业资讯 > linux>详细内容

通过expect让ssh自动交互

添加时间:2010-9-4
    相关阅读: 相关内容

使用expect实现ssh自动交互

  下面是使用expect实现的自动远端命令执行的脚本ssh-exec:

  #!/bin/sh

  # \

  exec expect -- "{GetProperty(Content)}" ${1+"$@"}

  # ssh-exec host user password command

  # execute command on remote host

  exp_version -exit 5.0

  set ERR_PERMISSION_DENIED 1

  set ERR_DIR_OR_FILE_NOT_EXIST 2

  set ERR_TIMEOUT 3

  set ERR_CONNECTION_REFUSED 4

  set ERR_INVALID_ARGUMENT 5

  proc auth_trans {password} {

  upvar #0 ERR_PERMISSION_DENIED ERR_PERMISSION_DENIED

  upvar #0 ERR_DIR_OR_FILE_NOT_EXIST ERR_DIR_OR_FILE_NOT_EXIST

  send "$password\r"

  expect {

  #password not correct

  "Permission denied, please try again." {

  exit $ERR_PERMISSION_DENIED

  }

  # ...transmission goes after...

  -re "Is a directory|No such file or directory" {

  exit $ERR_DIR_OR_FILE_NOT_EXIST

  }

  -re "KB/s|MB/s" {

  set timeout -1

  expect eof

  }

  }

  }

  if {$argc!=2} {

  send_user "usage: remote-exec command password\n"

  send_user " command should be quoted.\n"

  send_user " Eg. remote-exec \"ssh ls\\; echo done\" password\n"

  send_user " or: remote-exec \"scp /local-file :/remote-file\" password\n"

  exit $ERR_INVALID_ARGUMENT

  }

  set cmd [lindex $argv 0]

  set password [lindex $argv 1]

  eval spawn $cmd

  #timeout in sec, default 10

  set timeout 30

  expect {

  #first connect, no public key in ~/.ssh/known_hosts

  "Are you sure you want to continue connecting (yes/no)?" {

  send "yes\r"

  expect "password:"

  auth_trans $password

  }

  #already has public key in ~/.ssh/known_hosts

  "password:" {

  auth_trans $password

  }

  #user equivalence already established, no password is necessary

  -re "kB/s|MB/s" {

  set timeout -1

  expect eof

  }

  -re "Is a directory|No such file or directory" {

  expect eof

  exit $ERR_DIR_OR_FILE_NOT_EXIST

  }

  "Connection refused" {

  expect eof

  exit $ERR_CONNECTION_REFUSED

  }

  #connetion error

  timeout {

  exit $ERR_TIMEOUT

  }

  }

本文作者:未知
咨询热线:020-85648757 85648755 85648616 0755-27912581 客服:020-85648756 0755-27912581 业务传真:020-32579052
广州市网景网络科技有限公司 Copyright◎2003-2008 Veelink.com. All Rights Reserved.
广州商务地址:广东省广州市黄埔大道中203号(海景园区)海景花园C栋501室
= 深圳商务地址:深圳市宝源路华丰宝源大厦606
研发中心:广东广州市天河软件园海景园区 粤ICP备05103322号 工商注册