Being involved in web development process one has often got to realize actions/commands for which he has not been granted enough rights or the user whose server has launched and executed Drupal, is lacking access to some directories. Libssh2 library seems to render the way out of this situation as it helps provide access to the resources (shell) of the remote server using an encrypted connection.
Shell is a command interpreter in the operating system.
In order to use shell commands in PHP, it's necessary to know the port, host, username and password details. For server connection set up the ssh2_connect function is being used and for user authorization the ssh2_auth_password is.
$port = 2002; $server = 'example.com'; $login = '[email protected]'; $pass = '12345'; if (!function_exists("ssh2_connect")) { exit("ssh2_connect disable"); } if(!($con = ssh2_connect($server, $port))){ //переменный $con в случае успешного соединения //присваивается ссылка идентификатора SSH з’соединения, //необходимое позже для вызова функции ssh2_auth_password, //при неудачном соединении присваеваится значение FALSE. exit("could not connect to {$server} with port {$port}"); } if(!ssh2_auth_password($con, $login, $pass)) { exit("login/password is incorrect"); }
There also exist the following ways of authorization:
- ssh2_auth_hostbased_file - authorization using public HOSTKEY;
- ssh2_auth_none - authorization using "none" method, which is usually not available;
- ssh2_auth_pubkey_file - authorization using public key.
Here are examples of SFTP functions that get accessible after connection has been set up:
- ssh2_sftp_mkdir - creating directories;
- ssh2_sftp_rename - renaming remote files;
- ssh2_sftp_rmdir - deleting directories;
- ssh2_sftp_unlink - deleting files;
- ssh2_sftp - initialization of subsystem SFTP with already connected server SSH2;
- ssh2_sftp_realpath - transforms file name into real effective path at remote file system.
And the list is far from being complete.
$sftp = ssh2_sftp($con); ssh2_sftp_mkdir($sftp, '/new_directory'); ssh2_sftp_rmdir($sftp, '/old_directory')
ssh2_exec function seems to be a most functional as it facilitates executing server shell commands that are available for the above user.
if (!(ssh2_exec($con, "rm {$file}" ))) { exit("remove file failed"); } if (!(ssh2_exec($con, "cp {$path_from} {$path_to}" ))) { exit("file copy failed"); }
In other words, the mentioned library allows for shell commands to be used in PHP code and that affords advanced opportunities for Drupal development.