我是通过Python文件为mikrotik配置编程脚本。我可以通过SSH,Telnet和mac-telnet连接到mikrotik,但是我无法向mikrotik发送命令,输出进程被中断。你可以用mac-telnet推送python脚本中的命令来帮助我吗?我正在测试主要的mactelnet功能。
我也包括脚本。
非常感谢。
import sys, posix, time, md5, binascii, socket, select
import pexpect
import os
class LoginManager:
""" Class representing Microtic """
def __init__(self,hostIP,login,password):
self.host = hostIP
self.username = login
self.pwd = password
#telnet na mikrotik
def loginTelnet(self,login,password):
"""
Function to login to mikrotik via telnet
:param login:
:param password:
:return:
"""
import telnetlib
try:
host = '172.16.49.2'
port = 23
telnetcon = telnetlib.Telnet(host,port)
telnetcon = telnetlib.Telnet(host)
#user input
telnetcon.read_until(b"Login: ")
telnetcon.write(login.encode()+"\n")
#user password
telnetcon.read_until(b"Password: ")
telnetcon.write(password.encode()+b"\n")
time.sleep(10)
telnetcon.close()
'''
telnetcon.read_until()
telnetcon.read_all('Please press "Enter" to continue!'+"\n")
telnetcon.write('\013')
telnetcon.read_all('/ip address print')
'''
except:
print "Cannot connect to router via telnet"
#metoda na prihlasenie pomocou SSH
def loginSSH(self,login,password):
from pexpect import pxssh,spawn,expect
import getpass
try:
#self.login = login
#self.password = password
connect = pxssh.pxssh()
server = '172.16.49.2'
login = 'admin'
password = 'admin'
port = 22
connect.login(server,login,password)
commands = pxssh.spawn()
time.sleep(10)
connect.logout()
'''
commands.expect('Please press "Enter" to continue!')
commands.sendline('\013')
connect.sendline('/ip address print')
connect.prompt()
print connect.before
'''
except pxssh.ExceptionPxssh,e:
print "Error"
print str(e)
#router = RouterOS('172.16.49.2', 'admin', 'admin')
#router.loginTelnet('admin','admin')
#os.system("mactelnet -l -t 50 > mt.output 2>&1")
#zoznam devicov
deviceList = []
loadMacAddress = False
with open("mt.output", "r") as file:
for line in file:
if loadMacAddress:
macAddress = line.split()[1]
deviceList.append(macAddress)
else:
header = line.split()
if len(header)>1:
if "IP" in header[0] and "MAC-Address" in header[1]:
loadMacAddress = True
print deviceList
username = 'admin'
password = '""'
os.system('mactelnet {} -u {} -p {}'.format(deviceList[0], username, password))
os.system("interface print")
#print udajue[0][0]
阿德里安
答案 0 :(得分:1)
尝试使用此mikrotik python api模块:https://github.com/rtician/routeros。以下示例取自repo中的README.md:
$ pip install routeros
我已经使用Python 3.6.4对此进行了测试,但它确实有用。请注意,您的api访问必须在您的RouterOS上的IP->服务中启用。
from routeros import login
routeros = login('user', 'password', '10.1.0.1')
sample = routeros.query('/ip/pool/print').equal(name='dhcp')
routeros.close()
print(sample)
输出示例:
({'.id': '*1', 'name': 'dhcp', 'ranges': '192.168.88.10-192.168.88.254'},
{'.id': '*2', 'name': 'hs-pool-8', 'ranges': '10.5.50.2-10.5.50.254'})
或使用ansible。有几个库使用ansible通过ssh与Mikrotik路由器通信。