Page 1 of 1

[CONTRIB] ssh perl script - automate batch commands *UPDATED

Posted: Fri Jan 28, 2005 9:23 am
by iredden
I hacked away at this based on someone elses code. I found this script on the Internet with no credit to it! Thanks to whoever wrote the original script.

EDIT: http://www.dysan.net/Perl/lg.php -- Original script.

You put a file named monitor.passwd in your etc directory....
/etc/monitor.passwd:
admin||blah01
then create a file called txtfile.txt and put in it stuff .....
/somewhere/txtfile.txt:
/ip dhcp-server lease print
then run the script below like
ssh-cmd 127.0.0.1 txtfile.txt
and it should send all the commands in txtfile.txt to the router! I am successfully using this script to take all the static ip address entries in my mysql db (30-40 er so) and pull them into the mikrotik's dhcp server. It works great!

#!/usr/bin/perl
# by Ian Redden (c) 2005
# Purpose: to get info off of a router for looking glass.
#
#-varibles
  use Expect;
  $ssh = "/usr/bin/ssh";
  $router = "$ARGV[0]";
  $txtfile = "$ARGV[1]";

#-get username/password
  open(PS,"/usr/local/mikrotik/monitor.passwd");
   while (<PS>) {
     chomp;
     ($usernm,$pass) = split(/\|\|/, $_);
   }
  close(PS);
  $command = "$ssh -l $usernm $router";

#-connect to router.
  $ssh = Expect->spawn("$command");
  $ssh->log_stdout(1);

#-check to see if dsa authenticity question appears
   if ($ssh->expect(2, "yes/no")) {
     print $ssh "yes\r";
   }

#-send password.
   if ($ssh->expect(undef, "password:")) {
     print $ssh "$pass\r";
   }

#-send command.
   open( FILE, "< $txtfile" ) or die;
   if ($ssh->expect(undef, ">")) {
           while ($cmd = <FILE>) {
              print $ssh "$cmd\r";
              $ssh->expect(undef, ">");
           }
  }
  close FILE;
  print $ssh "/quit\r";

Posted: Fri Jan 28, 2005 10:30 am
by YazzY
Great work!
This makes it possible to do anything on the board form a web based application.
Remember the script requires pearl module called Expect and to initially log in with ssh to the router for key exchange.

Thanks a lot iredden

Posted: Mon Jan 31, 2005 4:00 am
by iredden
I did an update on the ssh-cmd. I noticed a bug when I was coding my dhcp push and bandwidth shaper push from my mysql database. My scripts would write all the correct commands to the text file, but the ssh-cmd would only half the time send half the cmds then quit mysteriously. Its fixed now and works 100% of the time. :)

perl -MCPAN -e shell
install Expect
install IO:Tty
install IO:Stty
quit

Posted: Fri Feb 11, 2005 12:17 am
by iredden
Another update.

Posted: Fri Feb 11, 2005 12:21 am
by changeip
So why can't you just use ssh and a command to execute ? Is there no shell thats spawned or something? Seems like a hack to me. After using a command line like:

ssh -l admin -p pass router.domain.tld "export"

it should just pipe the response out, but it doesn't. Just curious if this is something that would be fixed in 2.9 or there is no way around it.

Sam

Posted: Sun Feb 13, 2005 8:30 pm
by fusion
And still doesn´t working via CRON...

Posted: Wed Feb 16, 2005 12:44 am
by YazzY
I dislike using perl when not necessary so I wrote the same thing in sh.
It works with both ssh and telnet.
It's bit more fancy since I also included dialog menus (I had some spare time).
The whole thing can be easly changed to make it more suitable for running within a cronjob.
Just read the connect_ssh and connect_telnet functions.

The script is avaliable at:
http://yazzy.yazzy.org/coding/shell/rou ... uteros.txt

I tested it with sh on FreeBSD and Gentoo Linux (where /bin/sh -> bash).

Enjoy.

SSH to routeros using plink.exe

Posted: Sun Feb 20, 2005 3:17 pm
by agregorian
Hi YazzY, I'm trying to send commands via plink.exe in ssh but i'm getting back error "Server sent command exit status 127". The connection is working, but when i send any type of command it returns that line. I suspect its the syntax but cant work out.

If anyone can help would appricaite very much.

Posted: Mon Feb 21, 2005 6:06 pm
by isptlan
any version for win based systems ? :) (with/without SSH)

Posted: Tue Feb 22, 2005 11:19 am
by denialsander
any version for win based systems ? :) (with/without SSH)
Use PERL for windows. I'm about to test it in a week or so - so I cannot guarantee you success. ;)

Posted: Tue Feb 22, 2005 6:54 pm
by cmit
Ok, given the amount of questions here - is there any interest in a Windows based "MikroTik automation" tool? I.e. one that could read commands from a file, execute them, output the results to screen or save them to disk, ... The whole thing perhaps with some kind of scheduler or something. Other suggestions?!

What would interested guys be willing to pay for it? I have some proof of concept almost finished, but this would need some more serious work and fine-tuning.

Everybody interested should write to info@cmit.de - I don't want to abuse this forum for those discussions ;)

Posted: Wed Feb 23, 2005 1:09 am
by agregorian
Hi Cmit, i'm interested in a ssh or equivilant tool that i can incorporate in a .bat or .exe file to package commands to send to Mikrotik. The commands will be comming from my billing program, and would include adding/deleteing hotspot users, queues and any other relevant function.

I have Plink.exe command line tool but i cant seem to get Mikrotik to accept commnads, returns "...a ststus 127." as i have said above it may be the syntax.

Have you used plink.exe?

Posted: Wed Feb 23, 2005 7:45 am
by cmit
I myself and several others tried plink.exe to no avail. I suppose it has to do with the way RouterOS is spawing a shell (not not), that you can't execute RouterOS commands from there. I don't think that plink.exe can't be made to work...

My tool would be made exactly for such purposes. I will have the ability to work via command-line only, and perhaps feature an integrated scheduler for repetitive tasks etc. Any suggestions from your side for required features?

Could you send me an e-mail to the address noted above?

Posted: Sun Jul 03, 2005 6:34 am
by surfnet
Was a windows tool ever created?

Posted: Mon Jul 04, 2005 10:35 am
by cmit
Not yet - interest was, well, low...

Posted: Wed Jul 20, 2005 6:27 pm
by iredden
bump, for all the people emailing me asking for this.

Posted: Thu Jul 21, 2005 11:59 am
by lastguru
Let me give you a one-liner, just in case somebody cares about it:

expect -c "spawn ssh user@1.1.1.1 \"/ip route print\"; expect \"password: \"; send \"userpass\r\"; interact"

Note that the host you are connecting to should be previously added to SSH known hosts. Also note that it is for 2.9 only

Posted: Fri Oct 28, 2005 12:25 am
by variable
is telnet/ssh the only way to do this?

i currently have a php script that telnets in and it takes 60 seconds to issue a command.

the other thing is how do you get data back out from mikrotik, the first couple line are easy, but what about when you need to press the down key?

is perl going to be alot faster than the php telnet i use now?

thanks

Posted: Fri Oct 28, 2005 10:12 am
by cmit
Regarding the "down key": There's a parameter "without-paging" for all print commands in MikroTik. Then everything will be output without waiting for a key after every screen of data.
For example: "/interface wireless registration-table print without-paging"

Posted: Thu Mar 30, 2006 4:19 am
by Zaphod
I wrote a bit of php code that can log in and run a command then output the data. This code does require libssh2 (http://sourceforge.net/projects/libssh2/) and the ssh2 module for php5 (http://pecl.php.net/package/ssh2).

To enter a command you have to use a \r instead of \n.
<?php

$server = "x.x.x.x";
$username = "user";
$password = "pass";

$methods = array(
  'kex' => 'diffie-hellman-group1-sha1'
);

$connection = ssh2_connect($server, 22, $methods);
ssh2_auth_password($connection, $username, $password);
$shell = ssh2_shell($connection)){

$cmd = "/system";

$output = user_exec($shell,$cmd);
$output = user_exec($shell,$cmd);

print_r($output);

function user_exec($shell,$cmd) {
    fwrite($shell, $cmd ."\r");
    sleep(1);
    $output = "";
      while($line = fgets($shell)) {
               flush();
               $output[] = $line;
    }
    return $output;
    fclose($shell);
}

?>

Enjoy

Posted: Mon Apr 03, 2006 5:58 am
by hecklertm
cmit:

plink.exe seems to work fine for me to execute commands on a the router. What problem are you running into? I have a cf webserver app running plink in a cfexecute command allowing it to send comands and receive response via plink. No problems.

PLINK via CFEXECUTE?! You 'da MAN!!

Posted: Sat Nov 04, 2006 2:29 pm
by webdaddy
cmit:

plink.exe seems to work fine for me to execute commands on a the router. What problem are you running into? I have a cf webserver app running plink in a cfexecute command allowing it to send comands and receive response via plink. No problems.
I am in dire need of your big magic and have NO more to pull out! What am I doing wrong in the following code? Any "hidden" permissions issues I need to be aware of?

<cftry>
<cfexecute name="D:\wireless\tests\plink.exe"
arguments="system schedule import e-backup-run.rsc"
timeout="30"
variable="myVar"></cfexecute>
Script executed successfully! Eight hours of delicious sleep for YOU!
<cfcatch type="Any">
Script failed miserably. No sleep for YOU, slacker!
</cfcatch>
</cftry>

Any assistance would be MOST appreciated!

Steve Edwards
Dad O'Twins

Posted: Sat Nov 04, 2006 9:11 pm
by hecklertm
Out of town until next week. When I get back, I will post the script here so that you can see what we are doing. It should be fairly simple since it only took about 20 minutes to throw it together initially. That is why I cannot remember the specifics of how we did it.

Posted: Sat Nov 04, 2006 9:21 pm
by hecklertm
dup.

Looking forward to your plink/CF solution!

Posted: Sun Nov 12, 2006 5:44 pm
by webdaddy
Out of town until next week. When I get back, I will post the script here so that you can see what we are doing. It should be fairly simple since it only took about 20 minutes to throw it together initially. That is why I cannot remember the specifics of how we did it.
Thanks in advance for your contribution! I'm certain I'm not the only CF developer interested in seeing how you did it.

Webdaddy

Posted: Mon Nov 13, 2006 9:50 pm
by hecklertm
Ok. Here you go. This is the abridged version after cmit comments...

This should show all you really need to know.
There are a few variables populated by a database in the beginning.
The CFExecute also has the output redirected to a file so you can see the results of the command for "testing purposes". If you need to keep this result beyond the millisecond you executed the command, it should not be saved in a flat file that is overwritten each time.

Oh, and it is not required to use the -P switch to set the port if you are using the standard port 22.

Enjoy.
<CFSET filestring = "D:\#get_command.command_filename#"> 
    
   <CFSET Router_Address = "#get_site_info.Wifi_Site_IP#"> 
   <CFSET Router_Username = "#get_site_info.Repeater_Username#"> 
   <CFSET Router_Password = "#get_site_info.Repeater_Password#"> 
   <CFSET Router_Port = "#get_site_info.Router_Port#"> 
    
   <CFSET connect_string = "-P #get_site_info.Router_Port# #Router_Username#@#Router_Address# -pw #Router_Password# -T -m #filestring#"> 
    
   <cfoutput>#connect_string#</cfoutput> 
   <BR><BR> 
    
<cfexecute name = "d:\downloads\plink"
	   arguments = " -P #Router_Port# #Router_Username#@#Router_Address# -pw #Router_Password# -T -m #filestring#" 
	   timeout = "100" outputfile="D:\virtualwww\Sites\hypewifi\www\admin\no_app\data_dumps\router_output.txt">
	</cfexecute>
	
	<cffile action="READ" file="D:\virtualwww\Sites\hypewifi\www\admin\no_app\data_dumps\router_output.txt" variable="fileoutput">
	
	<pre>
	<cfoutput>#fileoutput#</cfoutput>
	</pre>

Posted: Tue Nov 14, 2006 10:39 am
by cmit
With this ColdFusion snippet you have to take care not to have simultaneous requests to this file, as it's using a fixed file name for saving and then displaying the commands output.
If you have overlapping requests, this could give interesting results ;-)

And you don't actually use the Router_Port variable in your plink execution (which is fine, as long as you don't want to configure the SSH port over your database).

Best regards,
Christian Meis

Posted: Tue Nov 14, 2006 5:30 pm
by hecklertm
Whatever... These things are true. Irrelevant to showing someone how a script could be formatted for the use of plink, but true. As I said in an earlier post, this script was built in about 10 minutes (therefore the hard coded 2222 was not removed from testing) and the script does not get used regularly. If it were in an environment that multiple requests were being submitted at once, it would be writing the output to a database record, not a flat file.
[/code]

Posted: Tue Nov 14, 2006 6:03 pm
by cmit
Hey - no offence intended! :-)

I just wanted to annotate that in case a ColdFusion newbie would use that script as posted - I have seen this way too often, and just wanted to make this clear...

Best regards,
Christian Meis

Posted: Tue Nov 14, 2006 7:27 pm
by hecklertm
You are correct. I should not have posted code that was not cleaned up.
No offense taken. Thanks for noticing the confusing statements. The post has been updated to reflect your comments.

Posted: Fri Dec 29, 2006 9:15 pm
by dot-bot
I myself and several others tried plink.exe to no avail. I suppose it has to do with the way RouterOS is spawing a shell (not not), that you can't execute RouterOS commands from there. I don't think that plink.exe can't be made to work...

My tool would be made exactly for such purposes. I will have the ability to work via command-line only, and perhaps feature an integrated scheduler for repetitive tasks etc. Any suggestions from your side for required features?

Could you send me an e-mail to the address noted above?
Any development on this issue? How can I shutdown the router through remotely and in an automated process under Win32?

using these:
plink -t -ssh 192.168.1.1 -l <username> -pw <password>
plink -t -pw <password> PuTTYSavedSession
I'm able to connect to the router and the MikroTik command prompt appears but ...

Reading the plink manual led me to trying it like this:
plink -t -pw <password> PuTTYSavedSession "/system/shutdown"
plink -t -pw <password> PuTTYSavedSession echo /system/shutdown
plink -t -pw <password> PuTTYSavedSession /system/shutdown

And it's not working, nothing gets passed through.

:? Help is appreciated :)

P.S. I see now an example for the ssh command in *nix systems posted here:
wiki.mikrotik.com/wiki/Use_SSH_to_execute_commands...
Maybe there's an alternative to plink that I could use... like the Win32SSH: ssh-1.2.14-win32bin.zip;setupssh381-20040709.zip

Re:

Posted: Sat Oct 06, 2007 9:21 am
by eugenevdm
'kex' => 'diffie-hellman-group1-sha1'
THANK YOU!

Re: [CONTRIB] ssh perl script - automate batch commands *UPDATED

Posted: Sun Jun 21, 2009 1:22 am
by Andrej90
Hi everyone!!I'm not sure that this is the right place to put this question :) And the question is:
Is there any way to get connected on mikrotik router trought ssh2 or ssh using php script??I was looking on php.net site and saw that the php is only suporting ssh2.I know that the mikrotik have ssh access, but I'm not sure that it'll go with ssh2.
I'm trying to make a web aplication, that could manage mikrotik without using winbox or similar programs....

Re: [CONTRIB] ssh perl script - automate batch commands *UPDATED

Posted: Sun Jun 21, 2009 1:46 am
by ayufan
yes, you can:
$conn = ssh2_connect("192.168.0.1", 22, array('kex' => 'diffie-hellman-group1-sha1')) or die("couldn't connect");
ssh2_auth_password($conn, "admin", "password") or die("coudln't auth");
$shell = ssh2_shell($conn, FALSE);
stream_set_blocking($shell, TRUE);

function conn_exec($cmd) {
	global $shell;
	echo "<<< $cmd\n";
	fwrite($shell, $cmd . "\r");
	sleep(1);
	fgets($shell);
	return trim(fgets($shell));
}

print_r(explode(';', conn_exec(":put [ip firewall filter print as-value]")));

fclose($shell);

Re: [CONTRIB] ssh perl script - automate batch commands *UPDATED

Posted: Sun Jun 21, 2009 1:55 am
by Andrej90
Thanks a lot :) Know I have a few new ideas :)

Re: [CONTRIB] ssh perl script - automate batch commands *UPDATED

Posted: Sun Jun 21, 2009 1:57 am
by Andrej90
sry about the english.It's bad :) *now

Re: [CONTRIB] ssh perl script - automate batch commands *UPDATED

Posted: Sun Jun 21, 2009 2:45 pm
by Chupaka
also you may try to use RouterOS API - it's easier than parse SSH output =)

Re: [CONTRIB] ssh perl script - automate batch commands *UPDATED

Posted: Sun Jun 21, 2009 2:46 pm
by Andrej90
I'll have it on mind

Re: [CONTRIB] ssh perl script - automate batch commands *UPDATED

Posted: Sun Jun 21, 2009 3:41 pm
by ayufan
also you may try to use RouterOS API - it's easier than parse SSH output =)
not when you use:
:put [/ interface print as-value]
;)

Re: [CONTRIB] ssh perl script - automate batch commands *UPDATED

Posted: Sun Jun 21, 2009 5:13 pm
by Chupaka
haha, almost API :D

Re: [CONTRIB] ssh perl script - automate batch commands *UPD

Posted: Wed Sep 15, 2010 5:23 pm
by Ripper
What about ROS5 it wont connect as ROS 3.3

$methods = array ( 'kex' => 'diffie-hellman-group1-sha1' );
$shell = ssh2_connect($host, 22, $methods);
any advices ?

Re: [CONTRIB] ssh perl script - automate batch commands *UPD

Posted: Wed Sep 15, 2010 9:06 pm
by Chupaka
any errors? =)