Advertisement
Guest User

Untitled

a guest
Sep 18th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.85 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. import socket
  4. import sys
  5. import tty
  6. import termios
  7. import paramiko
  8. from paramiko.py3compat import u
  9. import ncs
  10. from _ncs import decrypt
  11.  
  12. debug = False
  13.  
  14. def get_credentials(root, device):
  15. authgrp = root.ncs__devices.authgroups.group[device.authgroup].default_map
  16.  
  17. return (device.address, authgrp.remote_name, decrypt(authgrp.remote_password))
  18.  
  19.  
  20. class IgnoreMissingHostKeyPolicy(paramiko.MissingHostKeyPolicy):
  21. def missing_host_key(self, client, hostname, key):
  22. return
  23.  
  24.  
  25. def main():
  26. with ncs.maapi.Maapi() as m:
  27. m.install_crypto_keys()
  28. with ncs.maapi.Session(m, 'admin', 'ssh-context'):
  29. with m.start_read_trans() as t:
  30. root = ncs.maagic.get_root(t)
  31.  
  32. while True:
  33. print("q: exit")
  34. print("d: enable paramiko debug")
  35. devs = []
  36. for device in root.ncs__devices.device:
  37. devs.append(device)
  38.  
  39. for (idx, dev) in enumerate(devs):
  40. print("{}: {}".format(idx, dev.name))
  41.  
  42. inp = input('# ')
  43. if inp == 'q':
  44. break
  45. if inp == 'd':
  46. print("enabling debug")
  47. paramiko.common.logging.basicConfig(level=paramiko.common.DEBUG)
  48. try:
  49. idx = int(inp)
  50. if (idx >= 0) and (idx < len(devs)):
  51. ssh_to(root, devs[idx])
  52. except ValueError:
  53. pass
  54.  
  55.  
  56. def ssh_to(root, device):
  57. (host, user, pwd) = get_credentials(root, device)
  58.  
  59. ssh = paramiko.SSHClient()
  60. ssh.set_missing_host_key_policy(IgnoreMissingHostKeyPolicy())
  61. ssh.connect(host, username=user, password=pwd, allow_agent=False, look_for_keys=False)
  62.  
  63. chan = ssh.invoke_shell()
  64.  
  65. interactive_shell(chan)
  66.  
  67. ssh.close()
  68.  
  69.  
  70. def interactive_shell(chan):
  71. import select
  72.  
  73. oldtty = termios.tcgetattr(sys.stdin)
  74. try:
  75. tty.setraw(sys.stdin.fileno())
  76. tty.setcbreak(sys.stdin.fileno())
  77. chan.settimeout(0.0)
  78.  
  79. while True:
  80. read, _, _ = select.select([chan, sys.stdin], [], [])
  81. if chan in read:
  82. try:
  83. data = u(chan.recv(1024))
  84. if not data:
  85. sys.stdout.write('\r\n*** EOF\r\n')
  86. break
  87. sys.stdout.write(data)
  88. sys.stdout.flush()
  89. except socket.timeout:
  90. pass
  91. if sys.stdin in read:
  92. data = sys.stdin.read(1)
  93. if not data:
  94. break
  95. chan.send(data)
  96.  
  97. finally:
  98. termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
  99.  
  100.  
  101. if __name__ == "__main__":
  102. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement