如何使用PHP设置交互式SSH会话?

Cam*_*ron 3 php openssh proc-open pty

我正在尝试通过Mac OS X 10.6上的命令行使用PHP建立到远程服务器的交互式SSH连接.我目前正在使用PHP的proc_open函数来执行以下命令:

ssh -t -t -p 22 user@server.com
Run Code Online (Sandbox Code Playgroud)

这几乎可行.该-t -t选项都应该强制伪终端,他们几乎做.我可以输入SSH密码并按Enter键.但是,按下后,终端似乎只是挂起.没有输出,没有任何东西 - 就像SSH会话失败一样.我无法运行命令或任何东西,必须使用Ctrl + C杀死整个事物.我知道登录成功,因为我可以执行命令,ssh -t -t -p 22 user@server.com "ls -la"并获得正确的输出.

我认为这个问题必须与我在proc_open调用中使用标准管道的事实有关,所以我用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;  
    }  
} 
Run Code Online (Sandbox Code Playgroud)

(对不起 - 我不能为我的生活弄清楚SO的格式说明......)

我究竟做错了什么?为什么我不能用pty?这在Mac OS X上是不可能的吗?谢谢你的帮助!

Ale*_*min 5

您应该使用公钥身份验证,而不是尝试以编程方式绕过交互式密码身份验证.

密码提示应该是从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
Run Code Online (Sandbox Code Playgroud)


或者,您可以使用plink(PuTTY for Linux的一部分)而不是OpenSSH,因为它可以在命令行上获取密码plink -pw password example.com.但这样做会带来安全风险,因为ps aux在服务器上运行的任何人都可以在进程列表中看到密码.

还有一个调用的程序sshpass从环境变量或命令参数中获取密码并将其传递给ssh.