<?php
// /home/work/scripts/gp-data/conf/system.conf.php
return [
'sftp' => [
'host' => 'data.sftp.daiyuanpei.com',
'port' => '3333',
'user' => 'data-online',
'password' => 'SFTPDAIYUANPEI',
'root' => 'upload/online'
]
];
<?php
// /home/work/scripts/gp-data/lib/sftp.class.php
if (!defined("ROOT")) {
define("ROOT", dirname(dirname(__FILE__)));
}
class sftp {
private $conn;
private $config;
public function connect()
{
$this->config = require(ROOT . "/conf/system.conf.php");
$this->config = $this->config['sftp'];
$this->conn = ssh2_connect($this->config['host'], $this->config['port']);
ssh2_auth_password($this->conn, $this->config['user'], $this->config['password']);
return $this;
}
public function download($remote, $local)
{
$ressftp = ssh2_sftp($this->conn);
return copy("ssh2.sftp://{$ressftp}/$remote", $local);
}
public function upload($local, $remote)
{
$ressftp = ssh2_sftp($this->conn);
return copy($local, "ssh2.sftp://{$ressftp}/$remote");
}
public function getRoot($path)
{
return $this->config['root'] . '/' . $path;
}
}
<?php
// 上传
if (!defined("ROOT")) {
define("ROOT", dirname(dirname(__FILE__)));
}
$current='20210318';
$ftp_dir='data';
require_once(ROOT . "/lib/sftp.class.php");
$ftp = (new sftp())->connect();
$ftpPath = $ftp_dir.'/'. "$current.dat";
$md5FtpPath = $ftp_dir.'/' . "$current.md5";
echo $ftpPath.PHP_EOL;
echo $md5FtpPath.PHP_EOL;
// $md5 = md5_file($ftpPath);
// echo $md5;
// file_put_contents($md5FtpPath, $md5);
// die;
$ftpPath = $ftp->getRoot($ftpPath);
$md5FtpPath = $ftp->getRoot($md5FtpPath);
echo "upload $md5File and $dataFile to sftp.".PHP_EOL;
$dataFile ='/home/work/scripts/gp-data/'.$ftp_dir.'/'.$current.'.dat';
$md5File ='/home/work/scripts/gp-data/'.$ftp_dir.'/'.$current.'.md5';
echo "source_data:".$dataFile.PHP_EOL;
echo "ftp dir".$ftpPath.PHP_EOL;
echo "md5_source_data:".$md5File.PHP_EOL;
echo "md5 ftp dir".$md5FtpPath.PHP_EOL;
//die;
$a = $ftp->upload($dataFile, $ftpPath);
$b = $ftp->upload($md5File, $md5FtpPath);
var_dump($a, $b);
<?php
/* 下载文件
Usage:
sftp.php -P port -p password username@host -s sourceFile -t localFile
example:
/home/work/odp/php/bin/php sftp.php -P **** -p ****** data-online@*.*.*.* -s upload/online/data/20210318.md5 -t ./20210318.md5
*/
set_time_limit(0);
ini_set('memory_limit','2048M');
$port = $argv[2];
$password = $argv[4];
$userHost = $argv[5];
$sourceFile = $argv[7];
$localFile = $argv[9];
if($password === '-') $password = '';
$username = explode('@', $userHost)[0];
$host = explode('@', $userHost)[1];
$conn = ssh2_connect($host, $port);
$result = ssh2_auth_password($conn, $username, $password);
$ressftp = ssh2_sftp($conn);
$content = file_get_contents("ssh2.sftp://{$ressftp}/{$sourceFile}");
file_put_contents($localFile, $content);
|