简体   繁体   English

SSH/期望 “期望”在期望 shell 脚本中如何工作?

[英]SSH/Expect How does "expect" work in expect shell script?

I try to login ssh using expect.我尝试使用期望登录 ssh。 It works, but some outputs are not expected and I do not know why.它有效,但有些输出不是预期的,我不知道为什么。 This is my shell script:这是我的 shell 脚本:

#!/bin/sh
expect -c ' spawn ssh USER@ADDRESS ; 
            expect "?assword:" ; 
            send "MyPassword\r" ;
            expect "?" ;
            send "logout\r" ; 
            interact'

This is the output in my MacOS terminal:这是我的 MacOS 终端中的 output:

ip87-114:Downloads tasiyuchien$ ./test.sh 
spawn ssh USER@ADDRESS
Password:
logout
Last login: Tue Sep 13 18:17:21 2022 from 140.112.87.114
xdn42o221:~ USER$ logout
Connection to 140.112.42.221 closed.
ip87-114:Downloads tasiyuchien$ 

The first question is why there is a "logout" output after "Password:"?第一个问题是为什么“密码:”后面有“注销”output? Isn't the question mark represents any single character?问号不是代表任何单个字符吗? Is there any implicit output or pattern I don't see cause I see nothing after "Password:".是否有任何隐含的 output 或我看不到的模式,因为在“密码:”之后我什么也看不到。 (Also strangely, when I replace "?" as "*", nothing will be output after "Password:". hmm...) The same question can be asked when I login, cause I also see nothing but the "logout" is output. (同样奇怪的是,当我将“?”替换为“*”时,“密码:”之后什么都不会是 output。嗯......)当我登录时可以问同样的问题,因为除了“注销”我什么也看不到是 output。

The second question is why are there two "logout" outputted, I thought the except argument can be reused only if "except continue" is added.第二个问题是为什么有两个“logout”输出,我认为只有添加“except continue”才能重复使用except参数。

Can anyone explain to me what's happening.任何人都可以向我解释发生了什么。 Thanks!谢谢!

As part of the login process, after the Password: prompt is shown, you enter your password and hit Enter, then the login process prints a newline.作为登录过程的一部分,在显示密码:提示后,您输入密码并按 Enter,然后登录过程会打印一个换行符。 This newline is the character matched by "?".此换行符是“?”匹配的字符。

Changing "?"改变“?” to "*" works better: the asterisk is more greedy probably.到“*”效果更好:星号可能更贪婪。 Instead of matching exactly one character, it matches one or more characters, so it will try to collect as many as possible.它不是只匹配一个字符,而是匹配一个或多个字符,因此它会尝试收集尽可能多的字符。

Why two "logout"s appear?为什么会出现两个“注销”? I don't know.我不知道。 Perhaps your shell re-prints user input after displaying your prompt..也许您的 shell 在显示您的提示后重新打印用户输入..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM