Friday, March 3, 2017

Python CGI with paramiko

Leave a Comment

I am trying to write a Python CGI script where user can enter Name(hostname) and Choose Memory from form and then via using paramiko module it will execute free -m command to the given node

import cgi import paramiko   print "Content-type:text/html\r\n\r\n"  print '<html>'  print '<head><title>My First CGI Program</title></head>'  print '<body>'  print '<h1>Hello Program!</h1>'  form = cgi.FieldStorage()  if form.getvalue("name"):  name = form.getvalue("name")  if form.getvalue("memory"):  ssh = paramiko.SSHClient()  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  ssh.connect(name, username='testuser', password='test12')     stdin, stdout, stderr=ssh.exec_command("free -m")   for line in stdout.readlines():         print line.strip()  ssh.close()  print '<form method="post" action="final.py">' print '<p>Name: <input type="text" name="name"/></p>' print '<input type="checkbox" name="memory" /> Memory' print '<input type="submit" value="Submit" />' print '</form>' print '</body>' print '</html>' 

It's not throwing error but at the same time it's not giving any output, Not sure What I am doing wrong

1 Answers

Answers 1

form = cgi.FieldStorage() hostname = form.getvalue("name") or None if hostname and form.getvalue("memory"):    ssh = paramiko.SSHClient()     #ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())    #This, of course, is not in the interest of the inventor and is infinitely unsafe,    #so should only be used in tests in secure networks.    #The correct way is to have Paramiko load the host keys,    #so that it can check them as intended like:     client.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))    client.connect(hostname, username="testuser")    stdin, stdout, stderr = client.exec_command('free -m')    #for test print all std's    for line in stdin, stdout, stderr:        print line.strip('\n')    client.close() 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment