Edit: I've figured it out by referencing the Exploring Expect book. Please don't hesitate to add to my answer or make other suggestions, though! I will mark this as answered when I am allowed to (2 days from now).
I've looked around and unfortunately I'm not able to find too much on using SSH with expect here on this site. I am relatively new to Expect but I have been teaching myself with the Exploring Expect book.
My question is: How can I use a single spawned SSH process for multiple tcl procedures? My workaround right now is to close the SSH connection at the end of procedure 1 and re-spawn a new SSH connection in procedure 2.
Example: (The example is simplified quite a bit and only includes the necessary components to demonstrate my question... My whole program is over 200 lines as of now)
;# Proc definition for procedure1
proc procedure1 {user host pw} {
spawn /usr/bin/ssh $user@$host
expect "Password:"
send "$pw\r"
expect "#" ;# This is my device's prompt
;# From here it does a bunch of stuff... sends commands to the SSH
;# session, captures output, builds arrays and lists, etc
send "exit" ;# Disconnects the SSH session
return $mylist ;# returns a list of numbers to be used in procedure 2
}
;# Proc definition for procedure2
proc procedure2 {resultofproc1 user host pw} {
spawn /usr/bin/ssh $user@$host
expect "Password:"
send "$pw\r"
expect "#" ;# This is my device's prompt
;# Proc 2 now continues on in the same device using the results (a
;# list) from proc1.
return
}
;# Procedure call for first procedure:
set resultofproc1 "[procedure1 $user $host $pw]"
;# Procedure call for second procedure:
procedure2 $resultofproc1 $user $host $pw
Instead of closing the SSH connection at the end of procedure1 and reopening the SSH connection at the beginning of procedure2, how can I send commands from procedure2 to the SSH connection opened in procedure1? Obviously I would have to remove the sending of exit to keep the connection open. Assuming this is possible... Is this even a good practice or am I better off separating connections between procedures? If so, can you modify my code example to demonstrate how?
From what I have gathered, I think it has to do with the spawn_id variable.. but I can't figure out how to implement that in my code. I am currently reviewing chapter 10 "Handling Multiple Processes" in the Exploring Expect book. I will report back if I can figure it out on my own.
Thanks for your assistance!
I have viewed these answers on stackoverflow:
Tcl Expect Keep SSH Spawn open
Expect Procedure for SSH Login
Using procedure for spawing SSH doesn't work properly with expect