문제

I am trying to create a script that will log onto a server, run some commands while providing information back to the user. I can log onto the server fine using the script, my issue is the output I get back. My script is something like this:

#!/bin/bash

/usr/bin/expect << SSHLOGIN

set timeout 600

spawn ssh user@myServer.com
expect {
    "Are you sure you want to continue connecting (yes/no)?" {
        send "yes\n";exp_continue
    }
        Password: {
            send "$2\n"
        }
}
expect {
    "# " {
        send "echo \"Current Directory is:\" \n"
    }
}
expect "# " {
        send "pwd \n"
}
expect {
    "# " {
        send "exit \n"  
    }   
}
wait
SSHLOGIN

& my output is as follows:

spawn ssh user@myServer.com
Password: 
You have new mail.
DISPLAY set to user.myServer:0.0
# echo "Current Directory is:" 
Current Directory is:
# pwd 
/home/user/

The output I am trying to achieve is something like:

spawn ssh user@myServer.com
Password: 
You have new mail.
DISPLAY set to user.myServer:0.0
Current Directory is:
/home/user/

I've tried using log_user 0/1, stty etc.. but I can't seem to get it right with those...

Any help would be appreciated.

도움이 되었습니까?

해결책

The problem is that the std output of the spawned process includes both program output and sent commands, the latter just because of echoing from the remote device.

You could manipulate stdout via the log_user command, turning it off while still expecting & capturing, and printing out the output yourself via the "puts" command. Lastly re-enable, if at all needed. The below works because Expect does not read the echoed command until the expect command.

I can't test now so I'll leave you the regexp to match the pwd output (beware of prompts with current paths), but since the point of your question is not the regexp, I figure the following will do for you:

#!/bin/bash

/usr/bin/expect << SSHLOGIN

set timeout 600

spawn ssh user@myServer.com
expect {
    "Are you sure you want to continue connecting (yes/no)?" {
        send "yes\n";exp_continue
    }
        Password: {
            send "$2\n"
        }
}
expect {
    "# " {
        send "pwd \n"
        log_user 0
        expect -re "(include_here_between_the_parenthesis_a_regexp_that_matches_your_pwd_output)" {
            puts "Current directory is: $expect_out(1,string)"
        }
        log_user 1
}
expect {
    "# " {
        send "exit \n"  
    }   
}
wait
SSHLOGIN

As a last comment... why not change the top line to #!/usr/bin/expect and make this an expect script as opposed to a bash one with a here documnet (or whatever that was called)? It's almost pure expect code after all.

Let me know how that goes, and don't forget upvoting or marking the answer if it indeed helped. :-)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top