2014-02-14 22 views
2

我正在编写一个shell脚本,使用shell脚本本身中提到的密码登录到任何用户帐户。我的shell脚本如下:如何在脚本中使用密码从shell脚本登录到用户帐户?

mypass="helloworld" 
echo mypass>su myaccount 

执行这个shell脚本,我仍然在我的当前用户帐户,而不是myaccount

TL之后,DR我想知道如何通过登录到用户帐户一个通过运行它的shell脚本。

+0

您需要使用expect来发送密码 – Raghuram

+0

或者您需要'ssh' – BMW

+0

如果您使用'./ scrip.sh'执行脚本,那么它将在新的子shell中执行。即使是这个'su',一旦这个shell完成了,你就会被留在原来的账户shell中。 – RedX

回答

3

使用expect脚本可以通过脚本发送密码,下面是登录到su帐户和执行pwd命令的非常基本的期望脚本。

#!/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进行管理。

相关问题