【问题标题】:How to use su command from within ssh command in unix shell script如何在 unix shell 脚本的 ssh 命令中使用 su 命令
【发布时间】:2013-10-07 15:16:50
【问题描述】:

我的要求是登录到远程机器并为此创建一些文件夹我计划将用户名和密码作为用户的输入并尝试制作自动化的 shell 脚本。

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... 

在执行 su dsadmin 之后,它会变成

   bash-3.00$

这里没有密码或任何东西的迹象。

从上面看它不起作用

您能否建议是否可以在自动脚本中使用密码在 ssh 之后制作 su。任何建议将不胜感激。

谢谢!

【问题讨论】:

    标签: bash shell unix ssh su


    【解决方案1】:

    我很久以前就使用过expect命令,即使是从ssh控制台启动的su命令,它也能顺利运行。

    这里有一些可能对你有用的例子。

    首先是 bash 脚本:

    #!/bin/bash
    
    exec 1> stdoutfile
    exec 2> stderrfile
    
    ./yourexpectscript  YOUR_REMOTEIP_HERE userexample passwordexample
    

    其次是expect脚本:

    #!/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 $user@$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"
    

    【讨论】: