[英]How to execute a local Shell Script with SSH commands on server?
I want to run a local shell script that have SSH commands on the server using PHP. 我想使用PHP在服务器上运行包含SSH命令的本地Shell脚本。 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. 在脚本中,我使用ssh
运行ls -lart
类的命令,并将结果保存在服务器中的日志文件中,然后使用scp
将远程文件复制到我的本地主机。 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. 如果我使用终端user@local_host:~$ ./my_local_shell.sh
运行脚本,一切正常。 But if i use shell_exec()
to execute the script using PHP like this: 但是,如果我使用shell_exec()
使用PHP执行脚本,如下所示:
/// 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. 屏幕上未打印任何内容,并且文件内的SSH命令未执行。
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. 我知道我可以使用ssh2_shell()
,但是通过使用它,我必须在PHP内部发送命令,而这不是我想要的。
I already gave the permissions needed to index.php
and my_local_shell.sh
我已经给了index.php
和my_local_shell.sh
所需的权限
Any ideas how I can do this? 有什么想法可以做到吗?
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使用了无法捕获的某种ncurses,因此可以在shell脚本中将-v标志添加到scp命令中
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成功返回0,因此您可以编写
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 至于PHP,请检查您是否具有PHP的开始和结束标记,并更正您的echo语句
echo "<pre>".$output."</pre>";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.