2013-10-07 112 views
0

我的要求是登录到远程计算机并为此创建一些文件夹我计划将用户名和密码输入为用户的输入并尝试使自动化shell脚本。如何在UNIX shell脚本的ssh命令中使用su命令

1.)我用下面的代码ssh进入机器,并给出预期的密码登录到这台机器。

DSADMINPWD=dsadminpwd 
PWD=pwd 
/usr/bin/expect<<EOD 
spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no <username>@<remotemachineurl> 
expect "password" 
send "$PWD\n" 
EOD 

上述工作正常。但是,在此之后做su dsadmin。我无法从之前取得的密码进入 用户。

2.)我必须从本机内改变用户像su dsadmin。还有一个dsadmin的密码。但它不能正常工作。

DSADMINPWD=dsadminpwd 
    PWD=pwd 
    /usr/bin/expect<<EOD 
    spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no <username>@<remotemachineurl> 
    expect "password" 
    send "$PWD\n" 
    EOD 

    su dsadmin 
    <like to make some folders in dsadmin directory> 
    exit... 

做苏后dsadmin它会来到这里,为

bash-3.00$ 

无密码或任何的迹象。

从上面它不工作

能否请你建议,如果任何事情都是可能的,在自动化脚本SSH密码后,使苏。任何建议将不胜感激。

谢谢!

回答

0

很久以前,我使用expect命令,即使它是从ssh控制台启动的,它也可以顺利地使用su命令。

这里有些例子可能会让你觉得有用。

首先在bash脚本的:

#!/bin/bash 

exec 1> stdoutfile 
exec 2> stderrfile 

./yourexpectscript YOUR_REMOTEIP_HERE userexample passwordexample 

其次,预计脚本:

#!/usr/bin/expect -- 

send_user "connecting to remote server\n" 

set server [lindex $argv 0] 
set user [lindex $argv 1] 
set pass [lindex $argv 2] 
set dsadminpass "dsadminpwd" 

spawn ssh [email protected]$server 
expect "password: " 
send "$pass\n" 

expect { 
    "> " { } 
    "$ " { } 
    "# " { } 
} 

#example command in ssh shell 
send "ls -lah\n" 

expect { 
    "> " { } 
    "$ " { } 
    "# " { } 
    default { } 
} 

#su command 
send "su - dsadmin\n" 

expect { 
    "Password: " { } 
} 

send "$dsadminpass\n" 

expect { 
    "> " { } 
    "$ " { } 
    "# " { } 
    default { } 
} 

#example command in dsadmin shell 
send "ls -lah\n" 

#login out dsdamin shell 
send "exit\n" 

expect { 
    "> " { } 
    "$ " { } 
    "# " { } 
    default { } 
} 

#login out ssh connection 
send "exit\n" 

send_user "connection to remote server finished\n"