<?php
/**
* 测试sftp 连接及下载远程文件
*/
$config = [
'host' => '192.168.1.111',
'username'=>'root',
'password'=>'',
'port'=>'22',
];
$localPath = 'D:\\jaja\\php1\\';//本地存储路径
$remotePath = '/data/data/';
$sftp = new Sftp($config);
$re = $sftp->ssh2_dir_exits($remotePath);
if($re) {
$fileArr = $sftp->fileList($remotePath);
if(!$fileArr) {
printLog('远程目录获取文件列表失败 或者 远程目录为空');exit;
}
foreach ($fileArr as $k => $v) {
$downRes = $sftp->downSftp($remotePath . '/' . $v, $localPath . '\\' . $v);
if(!$downRes) {
printLog('下载文件失败---' . $v);
} else {
printLog('下载文件成功---' . $v);
sleep(1);
$delRes = $sftp->deleteSftp($remotePath . '/' . $v);
if(!$delRes) {
printLog('删除文件失败---' . $v);
} else {
printLog('删除文件成功---' . $v);
}
}
}
sleep(1);
$upRes = $sftp->upSftp($localPath . '112233.html', $remotePath . '123.html');
if(!$upRes) {
printLog('上传文件失败---112233.html');
} else {
printLog('上传文件成功---112233.html');
}
} else {
printLog('访问远程目录不存在');exit;
}
class Sftp
{
// 初始配置为NULL
private $config = NULL;
// 连接为NULL
private $conn = NULL;
//sftp resource
private $ressftp = NULL;
// 初始化
public function __construct($config)
{
$this->config = $config;
$this->connect();
}
public function connect()
{
$this->conn = ssh2_connect($this->config['host'], $this->config['port']);
if( ssh2_auth_password($this->conn, $this->config['username'], $this->config['password'])) {
$this->ressftp = ssh2_sftp($this->conn);//启动引力传动系统
}else{
printLog("用户名或密码错误");exit();
}
}
/**
* 判段远程目录是否存在
* @param $dir /远程目录
* @return bool
*/
public function ssh2_dir_exits($dir){
return file_exists("ssh2.sftp://" . intval($this->ressftp) .$dir);
}
/**
* 下载文件
* @param $remote /远程文件地址
* @param $local /下载到本地的地址
* @return bool
*/
public function downSftp($remote, $local)
{
return copy("ssh2.sftp://" . intval($this->ressftp).$remote, $local);
}
/**
* 文件上传
* @param $local /本地文件地址
* @param $remote /上传后的文件地址
* @param int $file_mode
* @return bool
*/
public function upSftp($local,$remote, $file_mode = 0777)
{
return copy($local, "ssh2.sftp://" . intval($this->ressftp) . $remote);
}
/**
* 删除远程目录中文件
* @param $file
* @return bool
*/
public function deleteSftp($file)
{
return ssh2_sftp_unlink($this->ressftp, $file);
}
/**
* 遍历远程目录
* @param $remotePath
* @return array
*/
public function fileList($remotePath)
{
$fileArr = scandir('ssh2.sftp://' . intval($this->ressftp) . $remotePath);
foreach ($fileArr as $k => $v) {
if($v == '.' || $v == '..') {
unset($fileArr[$k]);
}
}
return $fileArr;
}
}
function printLog($log)
{
echo '[' . date('Y-m-d H:i:s', time()) . '] - ' . $log . "<br>";
}
参考:
http://php.net/manual/zh/book.ssh2.php