Using procedure for spawing SSH doesn't work p

2019-07-27 09:13发布

问题:

I have a expect script which when uses a procedure to spawn SSH and, later using expect doesn't work, when ssh spawn is directly used, the expect thing seems to work fine. Any idea what can be wrong here ??

I am using the same code snippet in the other case and works fine.

proc sshLogin {serverName userName password} {
  global logfd
  set timeout 10
  logMessage "Connecting to  server = $serverName, please wait..."
  log_user 0
  spawn -noecho ssh -X "$userName\@$serverName"
  expect { 
    "password:" {
      send "$password\r"
      expect {
        "]#" {
          log_user 1
          logMessage "Logged in to Server = $serverName"
          return 1
        }
        "Permission denied" {
          log_user 1
          logMessage "Incorrect password!"
        }
      }
    }
    timeout {
      log_user 1
      logMessage "Connection to $serverName timed out"
    }
    eof {
      log_user 1
      logMessage "Connection to $serverName failed!"
    }
  }
  return 0
}

回答1:

You should also declare that spawn_id is a global variable in your procedure, by either adding:

global spawn_id

or by changing global logfd to:

global logfd spawn_id

This is because the current value of the spawn_id variable is used to determine what is being controlled (vital if you want to have expect control two subprocesses). Expect tries to do some “clever” stuff to handle the case where you've put the expect/send calls in a procedure without declaring things, but it's not a very reliable method and it does not work with spawn itself: you have to make it explicit (which is a good idea anyway when working with procedures).



标签: tcl expect