使用 Expect 的 SU 和运行命令

Sar*_*ain 6 linux su bash expect

我想 su 到另一个用户,使用 expect,然后以该用户身份运行图形程序。我正在使用 kcalc 进行测试:

#!/usr/bin/expect
set timeout 20
spawn su dummy
expect "Password:"
send "PASS\r";
send "kcalc\r"
Run Code Online (Sandbox Code Playgroud)

我还尝试删除最后一行并将 su 更改为“su dummy -c kcalc”,但这也不起作用。我很感激任何帮助。

小智 2

我今天刚刚使用 Spawn SSH 会话执行此操作,这里是我编写的一些代码,不确定它是否有帮助:

echo "Type the account you wish to use to issue the command, followed by [ENTER]: "
read account
read -s -p "Password: " password
echo "Type the command you wish to execute, followed by [ENTER]: "
read command
echo "Type the hostname you want to connect to, followed by [ENTER]: "
read hostname
switchToSudo="sudo su"
shortenedHost=`echo $hostname|cut -d. -f 1`
accountSwitched="root@$shortenedHost:/home/$account#"


 VAR=$(expect -c "
        expect \"*~$\"
        send \"$switchToSudo\r\"
        expect \"*?assword*\"
        send \"$password\r\"
        spawn ssh $account@$hostname
        expect "*?assword:*"
        send \"$password\r\"
        expect \"*~$\"
        send \"$switchToSudo\r\"
        expect ""
        send \"$command\r\n\"
        send "logoff"
        ")
echo "=============="
echo "$VAR"
exit
Run Code Online (Sandbox Code Playgroud)