expect code for automatic remote ssh login and erasing a file

[ permalink ] [ download ]
#!/usr/bin/expect -f


if {$argc < 4 || $argc > 5} {
   puts "Usage: sshErase <file> <user> <passwd> <ip> <port(optional)>"
   exit
 }

set file [lindex $argv 0]
set user [lindex $argv 1]
set passwd [lindex $argv 2]
set theip [lindex $argv 3]
set port ""
if {$argc == 5} {
   set port [lindex $argv 4]
} else {
  set port "22"
}
puts "File to erase: $file"
puts "User to erase with: $user"
puts "Passwd of the user: $passwd"
puts "Ip: $theip"
puts "Port: $port"

set timeout 10
spawn ssh "$user@$theip"
expect {
       "assword:*" { 
       		   send "$passwd\r"
		   puts "Password metida..."
		   exp_continue
       }
       -re "$user@*" {
       	           puts "La conexion ha tenido exito"
		   puts "Executing: rm -rf $file \r"
		   send "rm -rf $file\r"
		   set timeout 1 
		   expect {
		   	  "rm:" {
			  	puts "Problems with the deleting"
				puts "Ensure about your privileges"
				close
				exit
			  }
			  timeout {
			  	  puts "File deleted correctly."
				  close
				  exit
		          }
		   }
       } 

       timeout {
       	       puts "ERROR: The ssh has been timed out!!"       
       }

       "connecting (yes/no)?" {
       		   send "yes\r"
		   exp_continue
       }	
       eof {
       	   puts "Error: Final inesperado de la conexion\n"
	    exit
       }
}
hits counter