总结
豆包 AI 助手文章总结

怎么用php实现远程连接

藏色散人
发布: 2021-07-19 09:49:04
原创
3821人浏览过
用php实现远程连接的方法:首先安装SSH2模块;然后通过“ssh2_connect ($host, $port = null, $methods = nullarray , $callbacks = nullarray)”方法连接即可。

怎么用php实现远程连接

本文操作环境:windows7系统、PHP7.1版,DELL G3电脑

怎么用php实现远程连接?

php实现远程操作

使用 php 进行远程操作的时候,需要安装SSH2模块。关于在SSH2模块中用到过的几个函数,做一个简单的记录。

立即学习PHP免费学习笔记(深入)”;

常用方法

1、连接

ssh2_connect ($host, $port = null, $methods = nullarray , $callbacks = nullarray )
登录后复制

连接到一个 SSH 服务器

2、认证

ssh2_auth_password ($session, $username, $password)
登录后复制

在 SSH  上使用普通密码进行认证

或者

ssh2_auth_pubkey_file ($session, $username, $pubkeyfile, $privkeyfile, $passphrase = null)
登录后复制

通过公钥进行认证

3、文件传送

ssh2_scp_send ( resource $session , string $local_file , string $remote_file [, int $create_mode = 0644 ] )
登录后复制

通过 scp 协议发送文件

ssh2_scp_recv ( resource $session , string $remote_file , string $local_file )
登录后复制

通过 scp 协议获得文件

4、执行命令

ssh2_exec ($session, $command, $pty = null, $env = nullarray , $width = null, $height = null, $width_height_type = null)
登录后复制

在远程机器上执行命令

5、其他

ssh2_fetch_stream ($channel, $streamid) {}
登录后复制

获取拓展的数据流。常用的$streamid 定义有:

define ('SSH2_STREAM_STDIO', 0);
define ('SSH2_STREAM_STDERR', 1);
stream_set_blocking ( resource $stream , bool $mode )
登录后复制

设置流为 阻塞/非阻塞 状态。当 $mode 为 true 时为阻塞; $mode 为 false 时,则为非阻塞状态。

简单应用

//建立连接
$connection = ssh2_connect($host, (int)$port);
if (!$connection) {
 
... ...
 
}
 
//进行认证
 
if (!ssh2_auth_password($connection, $user, $password)) {
 
... ...
 
}
 
//发送文件
if (!ssh2_scp_send($connection, $sourceFile, $targetFile, 0644)) {
 
... ...
 
}else{
 
$stream = ssh2_exec($connection, "stat /tmp/targetFile 2>&1");
$errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
 
// Enable blocking for both streams
stream_set_blocking($errorStream, true);
stream_set_blocking($stream, true);
 
echo stream_get_contents($stream);
 
// Close the streams
fclose($errorStream);
fclose($stream);
 
}
登录后复制

推荐学习:《PHP视频教程

以上就是怎么用php实现远程连接的详细内容,更多请关注php中文网其它相关文章!

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
豆包 AI 助手文章总结
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号