PHP - ssh2_exec and stream_select( ) error - php

When I try to use ssh2_exec to run a python script on a remote server, and try to make it running under un-blocking model. An error shows up:
stream_select(): cannot represent a stream of type SSH2 Channel as a
select()able descriptor
My code:
$ssh_connection = ssh2_connect('server ip address',22);
ssh2_auth_password($ssh_connection, 'root', 'password');
$stream = ssh2_exec($ssh_connection, 'cd /opt/; python db.py');
stream_set_blocking($stream, false);
$read = array($stream);
$write = array();
$except = array();
$return_string = stream_get_contents($stream);
//echo $return_string;
stream_select($read, $write, $except, 300);
Does anybody know why it shows me that error?

Looks like you are you dont have acces or banned on remote server. Try to run from another IP.

Related

How to delete a remote file using ssh?

I am working on a project where we are using 2 VM's one is used as local and can be accessible and from this local VM, we need to access the remote VM. While working on this I am struck on a problem.There is a file in the remote in a directory.Every time a script gets executed the file gets loaded with new data and but I don't need that.I want the file to be deleted everytime before my script executed.
I have given the code below.
if($ssh = ssh2_connect('192.168.150.85', 22)) {
if(ssh2_auth_password($ssh, 'someUserName', 'somePassword')) {
$stream = ssh2_exec($ssh, "python file_scanner.py /home/nsadmin/$file_name");
$stream = ssh2_exec($ssh, 'rm /home/nsadmin/file_scanned');
stream_set_blocking($stream, true);
$data = '';
while($buffer = fread($stream, 4096)) {
$data .= $buffer;
}
fclose($stream);
echo $data; // user
}
}
Here we can see that after ssh connection,Iam ecxecuting some script and the result of this file gets appended in the file file_scanned.But when ever I execute the ssh connection I previous results are also coming.So I did $stream = ssh2_exec($ssh, 'rm /home/nsadmin/file_scanned'); . But it is not working.
Any suggestions on how to change or modify my script so I can remove the file after execution of previous command.
There may be issue with permission I can say,
But this is solution you can give a try.
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);
$stream = ssh2_sftp_unlink($sftp, '/home/nsadmin/file_scanned');
This is frequent thing, which we used for removing remote files.

ssh2_scp_send() and ssh2_scp_recv() functions are not working in php. Why?

ssh2_scp_send() function is hanging in php. Here's the code:
$debug_line_feed = "\n";
$conn = ssh2_connect($sftp_server, 22);
$return = ssh2_auth_password($conn, $sftp_user_name, $sftp_user_pass);
if ($return===true) echo "successfull connection".$debug_line_feed;
echo "uploading file".$debug_line_feed;
$local_filename = $product_feed_file_with_path;
$remote_filename = 'product_feed.txt';
ssh2_scp_send($conn, $local_filename, $remote_filename);
echo "successful".$debug_line_feed;
When i run it, it outputs "successful connection", "uploading file" then hangs. Any idea how to fix this?
I have tried a download as well with ssh2_scp_recv, and it hangs as well, with the local file being created as a 0 byte file.
My guess is that the server has a jail shell installed. At that point SCP wouldn't work but SFTP would.
recently,i use sftp to send file,linux to windows,ssh2_scp_send not work,i solve the problems use
$sftp = ssh2_sftp($conn);
$contents = file_get_contents($localPath);
$result = file_put_contents("ssh2.sftp://{$sftp}/{$remotePath}", $contents);
then works

PHP - WiFi Network Id and passphrase to hexadecimal key

To configure manually a WiFi network, I need the hexadecimal key.
In Ubuntu, I can obtain it with this comand:
wpa_passphrase network passphrase
And the result is:
network={
ssid="network"
#psk="passphrase"
psk=72feda58f99812cd6a4a075047270e361e3ae18f8cb191eb8d55ac07f928a466
}
Then.. How can I obtain the psk with PHP?
EDIT: I do this:
<?php
$fp = fopen("data.txt", "w+");
if(!$fp) die ("Errore nell'apertura del file");
exec("wpa_passphrase network passphrase",$output);
$conf = "";
for($i=0;$i<5;$i++)
$conf .= $output[$i]."";
fwrite($fp,$conf);
fclose($fp);
exec("sudo cp data.txt /etc/wpa_supplicant.conf"); //this doesn't work!
echo "ok<br>".$conf
?>
I've solved, this is the code:
<?php
$fp = fopen("data.txt", "w+");
if(!$fp) die ("Errore nell'apertura del file");
exec("wpa_passphrase network passphrase",$output);
$conf = "";
for($i=0;$i<5;$i++)
$conf .= $output[$i]."\n";
fwrite($fp,$conf);
fclose($fp);
exec("sudo cp data.txt /etc/wpa_supplicant.conf");
echo "1";
?>
But, to execute sudo command, I must add "www-data" user into sudoers file. I did this following this reply
In case anyone is still interested in this: I solved this using plain PHP by reading through the source of wpa_passphrase and comparing the result to the Wireshark PSK tool.
function wpa_passphrase($ssid, $passphrase) {
$bin = hash_pbkdf2('sha1', $passphrase, $ssid, 4096, 32, true);
return bin2hex($bin);
}
$psk = wpa_passphrase('network', 'passphrase');
Requires PHP >= 5.5

PHP: Read from socket or STDIN

I am learning socket programming in PHP and so I am trying a simple echo-chat server.
I wrote a server and it works. I can connect two netcats to it and when I write in the one netcat, I recive it at the other. Now, I want to implement what NC does in PHP
I want to use stream_select to see if I have data on STDIN or on the socket to either send the message from STDIN to the server or reading the incoming message from the server.
Unfortunately the example at the php manual doesn't give me any clue how to do that.
I tried to simply $line = fgets(STDIN) and socket_write($socket, $line) but it doesnt work. So I started to go down and just want stream_select to act up when the user typed the message.
$read = array(STDIN);
$write = NULL;
$exept = NULL;
while(1){
if(stream_select($read, $write, $exept, 0) > 0)
echo 'read';
}
Gives
PHP Warning: stream_select(): No stream arrays were passed in
/home/user/client.php on line 18
But when I var_dump($read) it tells me, that it is an array with a stream.
array(1) {
[0]=>
resource(1) of type (stream)
}
How do I get stream_select to work?
PS: In Python I can do something like
r,w,e = select.select([sys.stdin, sock.fd], [],[])
for input in r:
if input == sys.stdin:
#having input on stdin, we can read it now
if input == sock.fd
#there is input on socket, lets read it
I need the same in PHP
I found a solution. It seems to work, when I use:
$stdin = fopen('php://stdin', 'r');
$read = array($sock, $stdin);
$write = NULL;
$exept = NULL;
Instead of just STDIN. Despite php.net says, STDIN is already open and saves using
$stdin = fopen('php://stdin', 'r');
It seems not, if you want to pass it into stream_select.
Also, the socket to the server should be created with $sock = fsockopen($host); instead of using socket_create on the client side... gotta love this language and it's reasonability and clear manual...
Here a working example of a client that connects to an echo server using select.
<?php
$ip = '127.0.0.1';
$port = 1234;
$sock = fsockopen($ip, $port, $errno) or die(
"(EE) Couldn't connect to $ip:$port ".socket_strerror($errno)."\n");
if($sock)
$connected = TRUE;
$stdin = fopen('php://stdin', 'r'); //open STDIN for reading
while($connected){ //continuous loop monitoring the input streams
$read = array($sock, $stdin);
$write = NULL;
$exept = NULL;
if (stream_select($read, $write, $exept, 0) > 0){
//something happened on our monitors. let's see what it is
foreach ($read as $input => $fd){
if ($fd == $stdin){ //was it on STDIN?
$line = fgets($stdin); //then read the line and send it to socket
fwrite($sock, $line);
} else { //else was the socket itself, we got something from server
$line = fgets($sock); //lets read it
echo $line;
}
}
}
}

Empty PHP SSH2 stream contents, even with stream_set_blocking?

I am working on a tool that reads an iptables configuration from a remote host over SSH2 using the PECL SSH2 extension. I am able to successfully make the connection to the host, authenticate, and execute commands. The trouble I am having is sometimes the stream doesn't contain any data.
/**
* Load the current firewall configuration
* #return bool
*/
public function loadRules() {
$stream = ssh2_exec($this->connection,"~/iptsave;");
stream_set_blocking($stream,true);
$iptablesSave = stream_get_contents($stream);
if(empty($iptablesSave)) {
return false;
}
parent::restore($iptablesSave);
return true;
}
About 25% of the time, loadRules() returns false, even when connecting to locahost instead of the remote system. I was able to work around the problem by changing the ssh2_exec call to
$stream = ssh2_exec($this->connection,"~/iptsave; sleep .5");
but I am concerned that something is wrong.
phpSecLib may be able to help:
According to this post, it always returns the output, unlike ssh2.so.
I've got the same issue here. Somehow you need to set a delay for getting the result of the stream.
The way you've done it is possible, but you could also set a sleep(1) after the stream_set_block($stream, true) function.
You could try the usleep() function. Haven't tried it yet
May be this will solve the issue:
$stream = ssh2_exec($this->connection,"~/iptsave;");
stream_set_blocking($stream,true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
$iptablesSave = stream_get_contents($stream);
With some severs you have to use 'interactive shell'. And sometimes you have to set the delay / sleep manually. A working example:
$connection = ssh2_connect($IP, 22);
$auth = ssh2_auth_password($connection, $User, $Pass);
$cmd = "help" . PHP_EOL;
if (!$auth) {
echo "Login Failed;
exit(1);
}
$shell = ssh2_shell($connection);
stream_set_blocking($shell, false); // we will use manual sleep
sleep(1); // This sleep to make sure that you get the prompt back
fwrite ($shell, $cmd . ";" . PHP_EOL);
sleep(1); // This to make sure that the command executes and we get the prompt back again!
while($output = fgets($shell)){
echo $output;
}
fwrite ($shell, "exit;" . PHP_EOL); // If needed
sleep(1);
ssh2_disconnect($connection);
unset($shell);
unset($connection);

Categories