如何在Shell脚本中使用脚本中的密码登录用户账户?

3
我正在编写一个 shell 脚本,使用在脚本中指定的密码登录到任何用户帐户。我的 shell 脚本如下所示:
mypass="helloworld"
echo mypass>su myaccount

执行完这个shell脚本后,我仍然停留在当前用户账户中,而不是进入myaccount用户账户。

简而言之,我想知道如何通过运行一个shell脚本来登录用户账户。


你需要使用expect发送密码。 - Raghuram
如果您使用 ./scrip.sh 执行脚本,则会在新的子 shell 中执行。即使 su 命令起作用,一旦该 shell 完成,您仍将留在原始帐户 shell 中。 - RedX
2个回答

3
通过使用expect脚本,可以发送密码。下面是登录到su账户并执行pwd命令的基本expect脚本示例。
#!/usr/bin/expect

spawn su myaccount          # Spawning the su process
expect "Password:*"         # Wait/expect for the Password string from the spawned process
send "uraccpassword\r"      # send the password to spawned process as an input.
expect "*bash*"
send "pwd\r"
expect "*bash*"

0
如果您想在不提供密码的情况下登录帐户,则需要使用 ssh-keygen 从您的帐户生成 ssh 密钥,并将公钥复制到您要登录的帐户中。此外,我建议始终对生成的密钥设置一个口令,并使用 ssh-agent 进行管理。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接