在Linux服务器下利用scp实现以下文件传输功能。
从服务器下载文件到本地
scp username@servername:/path/filename /path/filename
上传本地文件到服务器
scp /path/filename username@servername:/path/filename
从服务器下载整个目录
scp -r username@servername:remote_dir/ /path/
上传目录到服务器
scp -r /dir username@servername:remote_dir
以上操作在执行时都会提示你输入密码,输入密码后就会成功执行。
但是这些只适合在操作Linux服务器时使用,如何在程序中执行呢?
在PHP就用到了php_scp_send
和php_scp_revc
函数
php_scp_send
是向另一个服务器传输文件,php_scp_revc
则是下载文件。
这两个函数要结合php_ssh2
组件使用。
以下例子为使用账号密码进行传输
class ssh2scp {
private host = 'host'; //服务器ip
privateuser = 'user'; //服务器账号
private port = '22'; //服务器端口
privatepassword = 'password'; //服务器密码
private con = null; //连接状态
privatelog = ''; //记录工作状态
function __construct(host = '',port = '') {
if(host != '')this->host = host;
if(port != '') this->port =port;
this->con = ssh2_connect(this->host, this->port);
if(!this->con) {
this->log .= "Connection failed !";
}
}
function authPassword(user = '', password = '') {
if(user != '') this->user =user;
if(password != '')this->password = password;
if(!ssh2_auth_password(this->con, this->user,this->password)) {
this->log .= "Authorization failed !";
}
}
function send(local_file, remote_file,prv) {
return ssh2_scp_send(this->con,local_file, remote_file,prv);
}
function revc(local_file,remote_file, prv) {
return ssh2_scp_revc(this->con, remote_file,local_file);
}
function getlog() {
return $this->log;
}
}