在保持所需输出的同时从终端输出中删除send命令

时间:2014-03-05 15:53:17

标签: bash ssh scripting expect

我正在尝试创建一个脚本,该脚本将登录到服务器,运行一些命令,同时向用户提供信息。 我可以使用脚本登录服务器,我的问题是我得到的输出。我的脚本是这样的:

#!/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

&安培;我的输出如下:

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/

我想要实现的输出类似于:

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

我尝试过使用log_user 0/1,stty等等。但我似乎无法正确使用这些......

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

问题在于,生成进程的std输出包括程序输出发送的命令,后者只是因为来自远程设备的回显。

您可以通过log_user命令操作stdout,将其关闭,同时仍然期待&amp;捕获,并通过“puts”命令自行打印输出。最后重新启用,如果需要的话。以下是有效的,因为Expect在expect命令之前不会读取echoed命令。

我现在无法测试因此我会留下正则表达式以匹配pwd输出(提防当前路径的提示),但由于问题的重点不是正则表达式,我认为以下内容适合您:

#!/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

作为最后的评论...为什么不将顶行更改为#!/ usr / bin / expect并使其成为一个期望脚本,而不是使用此处documnet(或任何被调用的)的bash?毕竟它几乎是纯粹的期望代码。

让我知道这是怎么回事,如果确实有帮助的话,不要忘记支持或标记答案。 : - )