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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题