Bash

使用期望自動化 vncserver 無法按預期工作

  • March 22, 2021

我想在我第一次執行 vncserver 時自動執行該部分,因為它要求輸入密碼(雖然我知道有一個標誌可以傳遞 passwd 文件,但我更喜歡每次需要/想要生成一個新的):

#!/bin/bash

read -s PWD

/usr/bin/expect -d <<EOF
spawn /usr/bin/vncserver -geometry 1366x768 :1
expect "Password:"
send "$PWD\r"
expect "Verify:"
send "$PWD\r"
expect "Would you like to enter a view-only password"
send "n\r"
expect eof
EOF

這裡我使用-d標誌來查看調試輸出,似乎 glob 確實與期望部分匹配,至少第二次(失敗一次,然後在第二次嘗試後匹配)。

它也可以發送密碼(這裡我使用了範例密碼“isthisevenworking”),這似乎有效。

vncserver 在工作時也會顯示通常的輸出,但是,當查看正在執行的程序時,vncserver 沒有執行……(雖然passwd文件.vnc夾中有一個文件)

但是,如果我在腳本結束後手動執行它,或者如果我在腳本末尾添加相同的命令,vnc 確實可以使用範例密碼,如下所示:

#!/bin/bash

read -s PWD

/usr/bin/expect -d <<EOF
spawn /usr/bin/vncserver -geometry 1366x768 :1
expect "Password:"
send "$PWD\r"
expect "Verify:"
send "$PWD\r"
expect "Would you like to enter a view-only password"
send "n\r"
expect eof
EOF
/usr/bin/vncserver -geometry 1366x768 :1

我想知道的是:為什麼 vncserver 命令在期望部分結束後不執行,即使它在期望腳本之外執行也是如此?

我不介意在腳本末尾添加它,因為它可以工作,但感覺有點不必要,因為在設置密碼超出預期後它無論如何都會執行……

編輯:我想我知道為什麼這不能按“預期”工作。似乎腳本過早停止並在 vncserver 啟動之前停止它。可以通過執行以下操作手動模擬相同的內容:

/usr/bin/vncserver -geometry 1366x768 :1

輸入兩次密碼,然後輸入n然後執行Ctrl+ D

所以我想添加無限超時:

#!/bin/bash

read -s PWD

/usr/bin/expect -d <<EOF
set timeout -1
spawn /usr/bin/vncserver -geometry 1366x768 :1
expect "Password:"
send "$PWD\r"
expect "Verify:"
send "$PWD\r"
expect "Would you like to enter a view-only password"
send "n\r"
expect eof
EOF

但這仍然行不通。最後嘗試sleep

#!/bin/bash

read -s PWD

/usr/bin/expect -d <<EOF
spawn /usr/bin/vncserver -geometry 1366x768 :1
expect "Password:"
send "$PWD\r"
expect "Verify:"
send "$PWD\r"
expect "Would you like to enter a view-only password"
send "n\r"
sleep 10
expect eof
sleep 10
EOF

那也沒用……

似乎這篇文章與我的問題有關。所以我去那裡嘗試了兩個答案/方法:

#!/bin/bash

read -s PWD

/usr/bin/expect -d <<EOF
set timeout -1
spawn -ignore HUP /usr/bin/vncserver -geometry 1366x768 :1
expect "Password:"
send "$PWD\r"
expect "Verify:"
send "$PWD\r"
expect "Would you like to enter a view-only password"
send "n\r"
expect_background
expect eof
EOF

沒用,但是:

#!/bin/bash

read -s PWD

/usr/bin/expect -d <<EOF
set timeout -1
spawn screen bash
send "/usr/bin/vncserver -geometry 1366x768 :1\r"
expect "Password:"
send "$PWD\r"
expect "Verify:"
send "$PWD\r"
expect "Would you like to enter a view-only password"
send "n\r"
expect eof
EOF

工作。

引用自:https://unix.stackexchange.com/questions/640396