1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PHPで鍵認証でsftp通信する

Last updated at Posted at 2023-02-18

はじめに

仕事の関係でsftp通信スクリプトをphpで作ることになったので簡単なサンプルを残す

前提

以下の環境で実施
接続元サーバ:10.0.1.4
接続元ユーザ:azureuser
接続先サーバ:10.0.1.5
接続先ユーザ:azureuser
php version:5.6(両方とも)

手順

鍵ファイルを作成する

下記を参考に、
接続元サーバに「秘密鍵ファイル」
接続先サーバに「公開鍵ファイル」
を配置する

sftpできるようにする準備

接続元サーバ

特になし、鍵ファイルだけ準備しておくように。

接続先サーバ

鍵認証を許可する設定を入れる

vi /etc/ssh/sshd_config

下記のオプションを有効化する

PubkeyAuthentication yes

sshd再起動

systemctl restart sshd

php5.6とssh2をインストール(接続元サーバ

php5.6インストール

yum -y install epel-release
rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-7.rpm
yum -y install php56-php php56-php-cli php56-php-common php56-php-devel php56-php-gd php56-php-mbstring php56-php-mysqlnd php56-php-pdo php56-php-xml
ln -s /opt/remi/php56/root/usr/bin/php /usr/bin/php
php -v

ssh2インストール

yum -y install php-pear
yum -y install php-devel
yum -y install php56-php-ssh2
yum -y install libssh2-devel
pecl install ssh2-0.12

php.ini編集する

sudo vi /etc/php.ini

↓↓末尾にコレ入れる
extension=ssh2.so

(多分やらなくていいけど)apache再起動

systemctl restart httpd

スクリプトを作成する(接続元サーバ

今回は接続元サーバにおいてあるファイルを、接続先サーバにアップロードするphpスクリプトを作成します
これを、/home/azureuser/配下に保管

upload_file.php
<?php
$local_file = '/home/azureuser/hello.txt';
$remote_file = '/home/azureuser/hello.txt';

$connection = ssh2_connect('10.0.1.5', 22);
ssh2_auth_pubkey_file($connection, 'azureuser', '/home/azureuser/.ssh/id_rsa.pub', '/home/azureuser/.ssh/id_rsa');

$sftp = ssh2_sftp($connection);

$local_handle = fopen($local_file, 'r');
$remote_handle = fopen("ssh2.sftp://{$sftp}{$remote_file}", 'w');

$read = 0;
$length = filesize($local_file);

while ($read < $length && ($buffer = fread($local_handle, $length - $read))) {
    $read += strlen($buffer);
    if (fwrite($remote_handle, $buffer) === false) {
        fclose($remote_handle);
        fclose($local_handle);
        die("ファイル書き込み中にエラーが発生しました。");
    }
}

fclose($remote_handle);
fclose($local_handle);

echo "アップロードが完了しました。\n";
?>

hello.txtも/home/azureuser/配下に保管

hello.txt
Hello, world!

php実行

cd /home/azureuser/
php upload_file.php

接続先サーバにファイルがアップロードされている確認する(接続先サーバ

ll /home/azure/hello.txt
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?