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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘