我正试图通过macosx10.6上的命令行使用php建立到远程服务器的交互式ssh连接。我目前正在使用php的proc_open函数执行以下命令:
ssh -t -t -p 22 user@server.com
这几乎行得通。
-t -t
选项应该会强制使用一个伪终端,而它们几乎会这样做。我可以输入ssh密码并按enter。但是,按enter键后,终端似乎只是挂起。没有输出,什么都没有-就好像ssh会话失败了。我不能运行命令或任何东西,必须使用CTRL+C杀死整个东西。我知道登录是成功的,因为我可以执行一个命令,如ssh -t -t -p 22 user@server.com "ls -la"
并获得正确的输出。我认为这个问题必须与我在我的PopyOutlook调用中使用标准管道的事实有关,所以我用PtY替换它们。我得到以下错误:“pTY伪终端不支持这个系统……”
Mac OS X不支持PTY或伪终端吗?(我对使用所有这些shell术语都很陌生)。
以下是php代码:
$descriptorspec = array(0 => array("pty"), 1 => array("pty"), 2 => array("pty"));
$cwd = getcwd();
$process = proc_open('ssh -t -t -p 22 user@server.com', $descriptorspec, $pipes, $cwd);
if (is_resource($process))
{
while (true)
{
echo(stream_get_contents($pipes[1]));
$status = proc_get_status($process);
if (! $status["running"])
break;
}
}
(抱歉-我一辈子都搞不懂SO的格式说明…)
我做错什么了?为什么我不能使用PTY?这在MacOSX上是不可能的吗?谢谢你的帮助!
最佳答案
您应该使用公钥身份验证,而不是试图以编程方式绕过交互式密码身份验证。
密码提示应该是从TTY使用的,我相信它是故意使用其他方式难以使用。而且-t -t
参数仅在连接到远程主机后才生效。我不相信PHP函数proc_open()
可以在虚拟终端中运行一个命令。
要设置公钥身份验证,请执行以下操作:
# Generate keypair
ssh-keygen -t rsa
# Copy public key to server
scp ~/.ssh/id_rsa.pub example.com:.ssh/authorized_keys
# Now you shouldn't be prompted for a password when connecting to example.com
# from this host and user account.
ssh example.com
# Since the web server (and thus PHP) probably has its own user account...
# Copy the ~/.ssh/id_rsa file somewhere else
cp ~/.ssh/id_rsa /some_path/id_rsa
# Change ownership of the file to the web server account
chown www-data:www-data /some_path/id_rsa
# Fix the file permissions (ssh ignore the keyfile if it is world readable)
chown 600 /some_path/id_rsa
# Try connecting to the server through the web server account
su -c "ssh -i /some_path/id_rsa -o UserKnownHostsFile=/some_path/known_hosts example.com" www-data
# Add the host to the known hosts file when prompted
另外,您可以使用
plink
(部分用于Linux的P腻y)而不是OpenSSH,因为它可以在命令行上输入密码plink -pw password example.com
。但是这样做会带来安全风险,因为在服务器上运行ps aux
的任何人都可以在进程列表中看到密码。还有一个名为
sshpass
的程序从环境变量或命令参数获取密码并将其传递给ssh
。