简体   繁体   English

使用PHP SSH进入计算机

[英]SSH into a machine using PHP

I'm trying to 我试图

  • SSH into my VM SSH进入我的VM
  • Go to a specific directory 转到特定目录
  • Run a Script 运行脚本

My command 我的命令

ssh user@45.12.129 "cd ~/scripts; pwd; ./startVM.sh"

PHP 的PHP

$cmd = 'ssh user@45.12.129 "cd ~/scripts; pwd; ./startVM.sh";
$data = shell_exec($cmd);

I'm not sure when to input my password. 我不确定何时输入密码。 I hope someone can fill out what I missed. 我希望有人可以填写我错过的内容。

The easiest (though not necessarily most secure) way would be to create an passwordless ssh key and add that to your VM: 最简单(尽管不一定最安全)的方法是创建无密码的ssh密钥并将其添加到您的VM:

  • run ssh-keygen to create a new public/private keypair if you haven't already (or if you want to create a new key just for this purpose) 运行ssh-keygen来创建一个新的公用/专用密钥对(如果您还没有的话)(或者如果您想为此创建一个新的密钥)
  • Put the generated public key in ~/.ssh/authorized_keys for the user in the VM. 将生成的公共密钥放入VM中用户的〜/ .ssh / authorized_keys中。 Make sure this file is only readable and writable by the target user. 确保此文件仅可由目标用户读取和写入。 (It should have mode 0500.) (它应该具有模式0500。)
  • ssh will now work without a password. ssh现在无需密码即可工作。 (In effect, the private key is the password.) (实际上,私钥密码。)
  • If you want to specify a specific key to use, specify with ssh -i path-to-key-file . 如果要指定要使用的特定密钥,请使用ssh -i path-to-key-file

Warning: Keep in mind that allowing remote code execution can be very dangerous, especially when the target is the root account. 警告:请记住,允许远程执行代码是非常危险的,尤其是当目标是root帐户时。 If this were a local VM, you should be relatively safe, but do be cautious when using this technique in general, especially over the internet. 如果这是本地VM,则应该相对安全,但通常在使用此技术时尤其要谨慎,尤其是在Internet上。 You can very easily shoot yourself in the foot like this. 您可以很容易地像这样用脚射击自己。

You probably want to create a non-root user in your VM for this purpose. 为此,您可能要在VM中创建一个非root用户。 If that user requires root privileges to complete its task, then grant access only to the specific functionality it needs with sudo and an appropriate sudoers file entry. 如果该用户需要root特权才能完成其任务,请使用sudo和适当的sudoers文件条目仅授予对其所需的特定功能的访问权限。

Can you try something like this? 你可以尝试这样的事情吗?

        if(!($con = ssh2_connect($ip, $port))){
            echo'cannot connect';
        } else {
            //Auth
            if(!ssh2_auth_password($con, "userssh", "password")) {
                echo'authentication failed';
            } else {
                //Execute command
                if(!($stream = ssh2_exec($con, "cd ~/scripts; pwd; ./startVM.sh" )) ){
                    echo 'failed executing';
                } else {
                     echo 'sucess';

                }
            }
         } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM