【问题标题】:How to scp with php using my ec2 key如何使用我的 ec2 密钥与 php 进行 scp
【发布时间】:2017-10-26 00:56:59
【问题描述】:

我在我的 Mac 上使用这样的命令来 scp 到我的远程服务器(在 .sh 文件中 - 它必须自动完成)。

scp -i my_key.pem index.html ubuntu@<ip>:~/public/index.html;

现在我必须在 Windows 机器上做同样的事情,我想我会用 php 编写它而不是使用 bash,这样代码在 Windows 和 Mac 上是相同的(我们的应用程序也运行一个已经使用的本地服务器php 脚本,这很复杂)。我查看了一些示例,但找不到我的确切解决方案。另外,老实说,我对私钥/公钥知之甚少,我想小心。

我有这样的东西。我不知道该怎么办。

$hostname = '21.232.foo.bar'; 
$sourceFile = 'index.html';
$targetFile = '~/public/indexx.html';

// SSH Key File — I'm guessing this should be private, not public
    private $ssh_auth_priv = '~/.ec2/my_key.pem'; 

$connection = ssh2_connect($hostname, 22);

ssh2_scp_send($connection, $sourceFile, $targetFile, 0777);

另外,如果我想做一些愚蠢的事情并且有更简单的方法,请告诉我。感谢您的帮助。

~~ 更新

我的代码现在如下所示,我收到错误警告:ssh2_scp_send():创建远程文件失败:发送文件失败

<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
 <?php 

$hostname = '13.124.foo.bar'; 
$sourceFile = 'foo.txt';
$targetFile = '~/public2/foo.txt';

$connection = ssh2_connect($hostname, 22);

ssh2_auth_pubkey_file(
    $connection,
    'ubuntu',
    '~/.ec2/id_rsa.pub',
    '~/.ec2/bh.pem'
);


ssh2_scp_send($connection, $sourceFile, $targetFile, 0644);



 ?> 
 </body>
</html>

这是托管在我的 localhost:8000 上

【问题讨论】:

    标签: php amazon-ec2


    【解决方案1】:

    一般格式为

    1   <?php
    2   $conn = ssh2_connect('example.com', 22);
    3   ssh2_auth_pubkey_file(
    4       $conn,
    5       'username',
    6       '/home/username/.ssh/id_rsa.pub',
    7       '/home/username/.ssh/id_rsa'
    8   );
    9   ......
    

    使用ssh2_scp_send($conn, '/local/filename', '/remote/filename', 0644);发送文件,其中0644是文件权限。

    如果您想继续使用 ssh2 来处理此类事情,请查看 http://www.patcup.com/php-ssh-authentication-using-a-public-key/,但建议您使用 https://github.com/phpseclib/phpseclib

    【讨论】:

    • 泰。为什么推荐使用phpseclib?您编写的代码似乎更容易,因为我不必安装另一个库。另外,我读到没有人在使用 phpseclib 并且很难安装(在 SO 评论中)。
    • 对于简单的 scp 我不会担心,但如果您希望在某个时候集成其他隐私/加密或构建更密集的安全传输...phpseclib.sourceforge.net/ssh/compare.htmlstackoverflow.com/questions/14304234/… (巨大的一块是交互式控制台......这使得 scp 从远程到远程很容易 pz)
    • 另外,我使用 .pem 文件。我对 RSA 一无所知。
    • pem 只是一种编码,rsa 是一种密码。你的 pem 密钥就像 RSA。
    • 我想我会用你提供的链接得到它。
    猜你喜欢
    • 2020-05-13
    • 2011-04-03
    • 2011-01-03
    • 2014-07-29
    • 2017-10-13
    • 1970-01-01
    • 2021-03-09
    相关资源
    最近更新 更多