Skip to content
Advertisement

how can i read data from a file in expect script

#! /bin/expect   
set timeout 20 
set user [lindex $argv 0] 
set password [lindex $argv 1] 
set prompt "$ "  ;# -- main activity   
proc dostuff { currenthost} {      
;# do something with currenthost      
send -- "ls -lrtr"   return}   ;# -- start of task

set fd [open ./hostlist r] 
set hosts [read -nonewline $fd] 
close $fd 

foreach host [split $hosts "n" ] {       
spawn /usr/bin/ssh $user@$host       
  while (1) {         
    expect { 
        "no)? " {            
        send -- "yesr"        
    }                  
    "password: " {             
        send -- "$passwordr"        
    }                   
    "$prompt" {            
        dostuff { $host }            
        break        
    }       
     }    
  } 

expect "$prompt"   
send -- "exitr"  
}   
expect eof  

I looked through this code online but will it read data if it is arragnged in 2 columns like.

HOST   TFTP_SERVER_ADDRESS
xx     XXYY
aa     AABB
...    ...
...    ....

and so on

I would like to assign each TFTP_SERVER_ADDRESS to a variable and use it in my script.

furthermore,Is this piece of code secure :

# grab the password
stty -echo
send_user -- "Password for $user@$host: "
expect_user -re "(.*)n"
send_user "n"
stty echo
set pass $expect_out(1,string)

#... later
send -- "$passr"

Advertisement

Answer

Sample Script that reads data from a file and then calls an expect script.

ChangePassword.sh

while read line
do
    pin=`echo $line | awk -F'|' '{print $1}'`
    ipaddress=`echo $line | awk -F'|' '{print $2}'`
    password=`echo $line | awk -F'|' '{print $3}'`
    #echo "$pin -- $password -- $ipaddress"
    echo "./t.expect $ipaddress $pin "$password" "
done<pin_password_8_192series.csv

t.expect

#!/usr/bin/expect -f
set timeout 20
set IPaddress [lindex $argv 0]
set PIN [lindex $argv 1]
set PASSWORD [lindex $argv 2]

spawn telnet $IPaddress 
expect "localhost login:"
send "rootr"
expect "Password:"
send "rootr"
send "cd /mnt/sipr"
send "sed -i  's/Password="$PIN"/Password="$PASSWORD"/g' Config.xmlr"
send "rebootr"
send "exitr"
interact

pin_password_8_192series.csv

341|192.168.6.1|&<M11qqHVkDdBj2
342|192.168.6.3|gyo8rB-9C<Ok.;=
343|192.168.6.6|skFI)4S-O.&-y,i
344|192.168.6.8|+Fqp6z*qEtQN0s?
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement