Home >Backend Development >PHP Tutorial >PHP connects to the server for server command operations
Install PHP SSH2 extension
Ubuntu installation of php link server requires php extension:sudo apt-get install libssh2-1 php-ssh2Install in Windows environment
Downloadphp extension ssh2
Download address http://windows.php.net/downloads/pecl/releases/ssh2/ 0.12/
Download according to your PHP version. I use WAMPSERVER2.5 (64bit), and the PHP version is 5.5.12, which is thread-safe.
#5. Restart apache, and you can use php to perform ssh connection operations.
6. Check phpinfo() to see if the php_ssh2 extension is loaded successfully.
Installation in Linux environment
Dependent libraries required for PHP SSH2 extension
openssl: Encryption algorithm collection, C language implementation
libssh2: ssh2 protocol library library, C language implementation
PECL/ssh2: PHP extension of libssh2, allowing PHP programs to call functions in libssh2
Dependencies: PECL/ssh2 – > libssh2 –> openssl
Install the required extension packages
Install libssh2
wget http://www.libssh2.org/download/libssh2-1.4.2.tar.gz tar zxf libssh2-1.4.2.tar.gz cd libssh2-1.4.2 ./configure && make && make install
Install PECL/ssh2
wget http://pecl.php.net/get/ssh2-0.11.3.tgz cd ssh2-0.11.3 phpize (如果报错命令没有找到,apt-get install php5-dev) ./configure —with-ssh2 && make && make install
Modify php configuration information
cd /etc/php5/cgi vim php.ini
Add item: extension=/usr/lib/php5/20090626/ssh2.so
ssh2.so is the module obtained when compiling ssh2. The above is the location of the module .
cd /etc/php5/cli vim php.ini
Added item: extension=/usr/lib/php5/20090626/ssh2.so
ssh2.so is the module obtained when compiling ssh2. The above is the location of the module.
Restart the web server
/etc/init.d/lighttpd restart
Check whether ssh2 is loaded
[root@localhost ~]php -m | grep s
php code usage
public function actionTestServer() { //登陆linux的ssh2用户名 $ssh_user='root'; //登陆linux的密码 $ssh_pwd=''; //默认端口号22 $ssh_port='22'; //服务器IP地址 $ssh_host='120.77.62.13'; //先测试拓展是否安装并开启 if(!function_exists("ssh2_connect")){ exit('SSH扩展没有安装或者没有安装成功'); } //建立ssh2连接 $ssh2 = ssh2_connect($ssh_host, $ssh_port); if(!$ssh2){ exit('连接服务器失败'); }else{ echo '成功连接上了服务器'; } //连接成功后进行密码验证,没验证无法进行其他操作。 if(!ssh2_auth_password( $ssh2, $ssh_user, $ssh_pwd )){ return false; } //shell脚本语句 $e="/etc/init.d/nginx restart >> /tmp/nginx_restart_".date('Ymd').".log"; //通过ssh2_exec执行语句 ssh2_exec($ssh2, $e); }
More PHP related knowledge, Please visit PHP Chinese website!
The above is the detailed content of PHP connects to the server for server command operations. For more information, please follow other related articles on the PHP Chinese website!