首页> 实战笔录 >PHP开发笔记 >ThinkPHP ThinkPHP
TP5利用scp实现从a服务器转移文件到b服务器
作者:小萝卜 2021-05-21 【 TP5 】 浏览 1407
简介TP5利用scp实现从a服务器转移文件到b服务器
TP5利用scp实现从a服务器转移文件到b服务器
注意:需要php安装ssl2扩展,windows下安装ssl2扩展请参照。
下面是实现该功能的代码:
<?php
/**
* FileCron.php
* 文件描述
* Created on 2021/4/17 0017 10:13
* User: zt
*/
namespace app\crminterface\controller;
//文件远程复制类
use think\Db;
error_reporting(E_ERROR | E_PARSE);
class FileCron
{
protected $files = [],$maxFileNum = 6;//一次读取n个文件
protected $targetServer = [//目标服务器配置
'服务器ip',22,'root','服务器密码'//小程序服务器用于测试
];
protected $path = '/www/wwwroot/crm/public/ceshi';//源文件夹
//protected $path = 'D:\Website\crm\public\ceshi';//源文件夹
protected $targetPath = '/www/backup/ceshi/';//目标文件夹
/**
* 执行远程复制文件
*/
public function file_scp()
{
set_time_limit(0);//不限时间
//要复制的源文件夹
$path = $this->path;
//目标服务器文件夹
$targetPath = $this->targetPath;
$files = $this->dir_list($path);
$model = Db::name('file_scp');
$ssh2 = ssh2_connect($this->targetServer[0],$this->targetServer[1]);
ssh2_auth_password($ssh2,$this->targetServer[2],$this->targetServer[3]);
foreach ($files as $file){
//连接目标服务器
$res = $model->where('hash','=',$file['hash'])->find();
//目标服务器存在该文件 进行移动操作
if(empty($res)){
$new_path = $targetPath . $file['ctime'] . '/';
@ssh2_sftp_mkdir(@ssh2_sftp($ssh2),$new_path,0777,true);
$stream=ssh2_scp_send($ssh2, $file['full'], $new_path.$file['name'], 0755);
if ($stream){//复制成功
//插入数据库
$model->strict(false)->insert([
'name' => $file['name'],
//'old_path' => str_replace($path,'',$file['full']),
'old_path' => $file['full'],
'new_path' => '/' . $file['ctime'] . '/' . $file['name'],
'hash' => $file['hash'],
'dates' => date('Y-m-d H:i:s')
]);
@unlink($file['full']);
}
}else{
//目标服务器存在该文件 不执行移动操作 但是数据库插入数据
//插入数据库
$model->strict(false)->insert([
'name' => $file['name'],
'old_path' => $file['full'],
'new_path' => '/' . $file['ctime'] . '/' . $file['name'],
'hash' => $file['hash'],
'dates' => date('Y-m-d H:i:s')
]);
@unlink($file['full']);
}
unset($stream);
}
ssh2_exec($ssh2, 'exit');
echo '成功';die();
}
/**
* @param $dir
* @return array
* 遍历文件夹下面的所有文件
*/
protected function dir_list($dir) {
if(is_dir($dir)){
if($handle=opendir($dir)){
while(($file=readdir($handle))!==false){
if($file!='.' && $file!=".."){
if(is_dir($dir.DS.$file)){
$this->dir_list($dir.DS.$file);
}else{
if (count($this->files) >= $this->maxFileNum){
break;
}else{
$this->files[]=['full' => $dir.DS.$file,
'name' => $file,
'ctime' => date('Y-m-d',filemtime($dir.DS.$file)),
'hash' => md5_file($dir.DS.$file)
];
}
}
}
}
}
}
closedir($handle);
return $this->files;
}
}
亲测有效,欢迎留言。
很赞哦! (0)