来自php的ssh连接

时间:2012-09-20 05:47:40

标签: php putty

我需要使用用户在我的网络表单上输入的用户名ssh到服务器。

如何做到这一点?

5 个答案:

答案 0 :(得分:5)

如果您的意思是“如何通过SSH从我的网站连接到另一台服务器”,那么您可以使用PECL ssh2库执行此操作。

请参阅: http://pecl.php.net/package/ssh2

演练(未经测试):http://kevin.vanzonneveld.net/techblog/article/make_ssh_connections_with_php/

答案 1 :(得分:3)

首先,没有PuTTy命令。这些是shell命令。

要在shell中运行PHP脚本,您需要使用php-cli:

答案 2 :(得分:0)

也许你可以在PHP中使用命令行脚本,这取决于你想要什么。 http://php.net/manual/en/features.commandline.php

答案 3 :(得分:0)

我不确定,但我认为(如果我错了,请纠正我)你要点击网页链接上的某个位置并打开putty(在用户的计算机上)连接到服务器。

您可以将Putty配置为处理 ssh:// 链接。怎么做你可以找到here

配置完成后,您只需要有一个类似于此的链接:

<a href="ssh://user@remoteServer">Click here to connect</a>

请记住,这仅适用于配置为处理ssh://链接类型的系统

我希望这能回答你的问题。

答案 4 :(得分:0)

这是你通过PHP使用putty的方式(不依赖于cli)。请注意,密码不受保护,并且交互式ssh会话将更加复杂。但是,HTTPS和mcrypt(如果需要存储密码和/或bash脚本)可以使这成为一个安全的解决方案。

<?php
// EDIT: added escapeshellcmd() to following vars
$user = escapeshellcmd($_POST['user']);  // username
$host = escapeshellcmd($_POST['host']);  // domain
$pass = escapeshellcmd($_POST['pass']);  // password

// create a string that will be loaded into a bash file for putty
// String can easily be made dynamically.
$bash_sh = <<<EOF                   #START OF BASH
\#!/bin/bash    
echo "BASH ON SSHD SIDE"
for (( i=1; i<=5; i++ ))            # BASH FOR LOOP
do
   echo "echo \$i times in bash"    #\$i is BASH not PHP, so have to escape
done
EOF;                                #END OF BASH

// creates a temp file called 'bash.sh' using the bash script above
file_put_contents("bash.sh", $bash_sh);

// executes putty using the args -ssh, -pw, -t, -m
// -ssh tells putty to use ssh protocol
// -pw tells putty to enter the password automaticaly
// -t tells putty to use a psudo terminal.
// -m tells putty read and execute bash.sh once logged in
exec("putty.exe -ssh ".$user."@".$host." -pw ".$pass." -t -m bash.sh");

// delete bash file since it has been sent
unlink('bash.sh');

?>