【问题标题】:BASH Script to SSH to another server and run commands as userBASH 脚本通过 SSH 连接到另一台服务器并以用户身份运行命令
【发布时间】:2015-09-06 12:10:26
【问题描述】:

我通过论坛和谷歌阅读了很多,但是我无法找到解决这个特定问题的方法。

基本上,我的脚本在我的本地机器上运行,然后通过 SSH 连接到具有不同用户名的服务器上(它一直工作到这里),并且在那台机器上我需要运行一些命令(它们不运行) .

以下是不起作用的部分代码:

if [[ "${TYPE}" == "cPanel" ]]; then

        #Connect to the server with credentials defined earlier in the script - works properly.
        ssh $USER@$HOST -p $PORT

        #Get the domain by the username - works properly
        user=$(sudo grep ${DOM} /etc/userdomains)

        #Extract only the username from the above string - works properly
        userNew=$(echo ${user} | awk 'END {print $NF}')

        #Log in as the new username - works properly
        sudo su -s /bin/bash ${userNew}

fi

这是一个 cPanel 服务器,我需要作为 cPanel 用户之一登录。

请帮忙。

附:上面的脚本在运行到 cPanel 服务器本身时可以正常运行。仅当在我的本地机器上调用 SSH 脚本时它才起作用。

【问题讨论】:

  • 我不确定这是否是自动回复,但我仍然意识到答案对于我的问题是绝对正确的。问题是,在测试时,我没有提到我需要保持登录到该服务器,由于我没有说明,回复没有回答。我仍然对所有相关人员进行投票并标记了正确答案,因为我是根据我提出的问题给出的答案。

标签: bash ssh cpanel


【解决方案1】:

如果要在远程服务器上运行命令,则需要将它们放在 SSH 命令的末尾。您的脚本目前正在使用 SSH 连接到远程服务器,但随后只为您提供了一个交互式 shell。

你需要这样的东西:

ssh $USER@$HOST -p $PORT <command to execute>

【讨论】:

    【解决方案2】:

    使用here document

    if [[ "${TYPE}" == "cPanel" ]]; then
      ssh $USER@$HOST -p $PORT << \EOF
    
        #Get the domain by the username - works properly
        user=$(sudo grep ${DOM} /etc/userdomains)
    
        #Extract only the username from the above string - works properly
        userNew=$(echo ${user} | awk 'END {print $NF}')
    
        #Log in as the new username - works properly
        sudo su -s /bin/bash ${userNew}
    EOF
    fi
    

    【讨论】:

      猜你喜欢
      • 2016-10-24
      • 1970-01-01
      • 1970-01-01
      • 2014-07-17
      • 2019-01-21
      • 2016-11-09
      • 2011-06-21
      • 1970-01-01
      相关资源
      最近更新 更多