2

I am trying to automate router configuration with Python through Paramiko, however whenever I test a command through the exec_command function, it doesn't seem to do anything. If I enter the same commands through Putty it works though. I am fairly new to Python.

This is for configuration of a Ubiquiti Edge Router X. I've looked at answers here and some tutorials online and I think I am doing everything correctly

import paramiko

ip = '10.0.1.1'
user = 'ubnt'
passw = 'ubnt'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname = ip, port=22, username = user, password = passw)
stdin, stdout, stderr = ssh.exec_command("configure")
stdin, stdout, stderr = ssh.exec_command("set service dhcp-server shared-network-name LAN subnet 10.0.1.0/24 dns-server 4.2.2.2")
stdin, stdout, stderr = ssh.exec_command("commit")
stdin, stdout, stderr = ssh.exec_command("save")
output = stdout.readlines()
print(output)

The expected output should be that the dns server settings on my router should be changed to 4.2.2.2 but it doesn't seem to do anything. Any help would be appreciated. Thanks.

ishdacoder
  • 29
  • 1
  • 4

2 Answers2

0

I assume that the set, commit and save are actually subcommands of the configure command, not top-level commands.

So you need to feed them as an input to the configure command, not try to execute them as standalone commands (what your code is doing).

stdin, stdout, stderr = ssh.exec_command("configure")
stdin.write("set service dhcp-server shared-network-name LAN subnet 10.0.1.0/24 dns-server 4.2.2.2\n")
stdin.write("commit\n")
stdin.write("save\n")
stdin.flush()

See also Execute (sub)commands in secondary shell/command on SSH server in Paramiko

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
0

Thanks for the help guys. After a few days of googling around I found the solution. I had to put my commands in a wrapper class and paramiko worked fine after that.

Operational mode wrapper for top level commands: /opt/vyatta/bin/vyatta-op-cmd-wrapper

Configuration mode wrapper: /opt/vyatta/sbin/vyatta-cfg-cmd-wrapper

stdin, stdout, stderr = sshClient.exec_command('/opt/vyatta/bin/vyatta-op-cmd-wrapper configure')
stdin, stdout, stderr = sshClient.exec_command('/opt/vyatta/sbin/vyatta-cfg-cmd-wrapper begin')
stdin, stdout, stderr = sshClient.exec_command('/opt/vyatta/bin/vyatta-op-cmd-wrapper set service dhcp-server shared-network-name LAN subnet 10.0.1.0/24 dns-server 4.2.2.2')
stdin, stdout, stderr = sshClient.exec_command('/opt/vyatta/sbin/vyatta-cfg-cmd-wrapper commit')
stdin, stdout, stderr = sshClient.exec_command('/opt/vyatta/sbin/vyatta-cfg-cmd-wrapper save')
stdin, stdout, stderr = sshClient.exec_command('/opt/vyatta/sbin/vyatta-cfg-cmd-wrapper end')
ishdacoder
  • 29
  • 1
  • 4