0

Need assistance while i want to ping server if got reply then proceed with script and if no reply go again to previous step where we fetch IP from hosts.txt

#Setting up Variables
set timeout 5                                                                                                                                
set fid [open ./hosts.txt r]
set contents [read -nonewline $fid]
close $fid

#Grabbing Password to be used in script further
stty -echo
send_user -- "Enter the Password: "
expect_user -re "(.*)\n"
send_user "\n"
stty echo
set pass $expect_out(1,string)
foreach host [split $contents "\n"] {

    set timeout 5
    spawn ping $host
    expect  {
    "Reply" {puts "$host Is Up"}
    "Request" {puts "$host Is Down"}
        }
GauravG
  • 19
  • 7

1 Answers1

0

Match the "%packet loss" in the summary of ping, like in the script below. As a side note, you mentioned that if the host is not reachable, control should be given back to the foreach loop, which would read the next host, but in your script, you actually try to do something upon failure, so I included a failure option as well.

# Procedure to be called for each
# reachable host
proc handleHost {host} {
    do things...
    expect eof
}

# To be called for unreachable hosts
proc hostFailed {host} {
    puts "$host is not reachable."
}

#Setting up Variables
set timeout 5
set fid [open ./hosts.txt r]
set contents [read -nonewline $fid]
close $fid

#Grabbing Password to be used in script further
stty -echo
send_user -- "Enter the Password: "
expect_user -re "(.*)\n"
send_user "\n"
stty echo
set pass $expect_out(1,string)
foreach host [split $contents "\n"] {

    set timeout 5
    spawn -noecho ping -q -w 1 -c1 $host
    expect {
        " 0% packet loss" { handleHost $host }
        eof               { hostFailed $host }
    }
}
Lacek
  • 7,233
  • 24
  • 28
  • Yes if the host is not reachable i want the script to go and fetch the next IP from hosts file.Sometimes,we have interment connection so in you case if we get 50% reply.so wether script will consider it as failed? – GauravG Aug 12 '20 at 14:55
  • edit 2 : i will run these scripts on cgywin @Lacek – GauravG Aug 13 '20 at 04:53
  • In my example, `ping` sends only one probe (`-c1`), so it is either 100% success or 100% failure. If you want to have more options, you can include any number of patterns in the `expect` block. If a pattern matches, others will be ignored, so you should put the most exact rules first. On cygwin, the `ping` output is different if you use the `ping` program included in windows. In this case, you should match the `Received = 0` pattern to check for a failure, but if you install the `inetutils` package in cygwin, then the output will match the Linux version. – Lacek Aug 13 '20 at 08:12