donte1234567 2018-11-18 21:29
浏览 336

如何在服务器上使用SSH命令执行本地Shell脚本?

I want to run a local shell script that have SSH commands on the server using PHP. And inside the script i am using ssh to run a command like ls -lart and save the result on a log file in the server, and then using scp to copy the remote file to my local host. Something like this:

/// my_local_shell.sh

#!/bin/bash
host=$1
user=$2
port=$3
ssh -p $port $user@$host 'ls -lart >> /home/remote/file.log'
scp -P $port $user@$host:/home/remote/file.log /home/local/file.log

If i run the script using the terminal user@local_host:~$ ./my_local_shell.sh everything works just fine. But if i use shell_exec() to execute the script using PHP like this:

/// index.php

$output = shell_exec("my_local_shell.sh 192.168.1.1 root 2222");
echo <pre>$output</pre>;

Nothing is printed on screen and the SSH commands inside the file are not executed.

I know I can use ssh2_shell(), but by using it I would have to send the commands inside the PHP, and it's not what i want.
I already gave the permissions needed to index.php and my_local_shell.sh

Any ideas how I can do this?

  • 写回答

1条回答

  • donglian3055 2018-11-19 00:02
    关注

    Apparently scp uses some sort of ncurses that you can't capture, so you could add the -v flag to your scp command in the shell script

    scp -v -P $port $user@$host:/home/remote/file.log /home/local/file.log
    

    or alternatively, since scp returns 0 on success you could write

    scp -P $port $user@$host:/home/remote/file.log /home/local/file.log && echo Success
    

    As for the PHP please check you have PHP opening and closing tags and correct your echo statement

    echo "<pre>".$output."</pre>";
    
    评论

报告相同问题?

悬赏问题

  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案