How to scp with php using my ec2 key
I use a command like this on my Mac to scp to my remote server (in a .sh file - this should be done automatically).
scp -i my_key.pem index.html ubuntu@<ip>:~/public/index.html;
Now I have to do the same from Windows machine, and decided I would just write it in php instead of bash so the code is the same for Windows and Mac (our application also starts a local server which already uses php scripts, this is tricky) ... I have looked at several examples but cannot find my exact solution. Also, to be honest, I don't know much about private / public keys and I want to be careful.
I have something like this. I don't know what to do for the key.
$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);
Also, if I'm trying to do something stupid and there is a much easier way, please let me know. Thanks for your help.
~~ UPDATE
Now my code looks like this and I am getting an error. Warning: ssh2_scp_send (): Failed to create remote file: Failed to send file
<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>
This will be hosted on my localhost: 8000
source to share
The general format would be
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 ......
Use ssh2_scp_send($conn, '/local/filename', '/remote/filename', 0644);
to send a file, where 0644 is the file permissions.
Check out http://www.patcup.com/php-ssh-authentication-using-a-public-key/ if you want to continue using ssh2 for this type of thing, but it's recommended to use https://github.com/phpseclib / phpseclib .
source to share