1

I want to block some web sites through the bash script. I have a list for website names list.txt. router is mikrotik. I need help for Syntax. I cant send command after ssh connection

file = "list.txt"

lines = cat $ file

sshpass -p 'blabla' ssh y@x.x.x.x

for line in $ lines; do

"/ ip proxy acces add dst-host =" $ line "action = deny comment =" list "

done

g3stapoo
  • 23
  • 1
  • 6

3 Answers3

1

It's very old question, but I put my answer if someone reach here with same issue ;)

#!/bin/bash

where="<path to your mikrotik config.txt>";
len=`cat $where | wc -l`;
config=`for (( c=1; c<=$len; c++ )) do line=\`sed -n "$c""p" $where\`; echo  $line; done`;

sshpass -p "blabla" ssh -t -oStrictHostKeyChecking=no y@x.x.x.x $config

Mikrotik also support ssh-key ! is much more safe to use key instead sshpass.

DamianK
  • 387
  • 2
  • 6
0

You are declaring $file and $lines in your local machine, the router you connect to has cannot loop over this value.

Try something like this:

while read l;do
sshpass -p 'blabla' ssh y@x.x.x.x ip proxy access add dst-host ="$l" action = deny comment ='list'
done < list.txt
  • thank your answer you are very kind but I need better solution for ssh connection session count. ssh must be open before loop and then commands send in loop – g3stapoo Sep 25 '17 at 12:48
0

Instead of using sshpass, you can also add your public key:

 ssh 192.168.88.1 "/file print file=key; file set key contents=\"`cat ~/.ssh/id_rsa.pub`\";/user ssh-keys import public-key-file=key.txt;/ip ssh set always-allow-password-login=yes"

Then you can just ssh without having to use sshpass. If you're using ssh mostly, then you can disable colorisation by changing your username to username+ct in your /etc/ssh/ssh_config for your mikrotik hosts, or just ssh username+ct@router.

@DamianK's answer becomes:

where="<path to your mikrotik config.txt>";
len=`cat $where | wc -l`;
config=`for (( c=1; c<=$len; c++ )) do line=\`sed -n "$c""p" $where\`; echo  $line; done`;

ssh x.x.x.x $config

Another nifty thing you can do is to tell ssh to keep the connections open for, say, 600 seconds - then you don't get the login delay of running ssh multiple times, so you can use @esstorm's answer. Just put this in your /etc/ssh/ssh_config:

 ControlMaster auto
 ControlPath ~/.ssh/socket-%r@%h-%p
 ControlPersist 600

The only snag is that if the connection times out, connecting will hang if you reconnect within that timeout. You can of course manually delete the socket, which you can find with find .ssh/sock*

@esstorm's answer becomes:

while read l;do
ssh y@x.x.x.x ip proxy access add dst-host ="$l" action = deny comment ='list'
done < list.txt
dagelf
  • 1,468
  • 1
  • 14
  • 25