2017-02-23 53 views
4

我想写一个Python CGI脚本,其中用户可以输入名称(主机名),并从表单中选择内存,然后通过使用的paramiko模块就会给定节点Python的CGI与的paramiko

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>' 
执行免费-m命令

这不是抛出错误,但同时它不给任何输出,不知道我做错了

+0

我编辑了标题。 GUI!= CGI –

+1

尝试打印出'''stderr'''进行调试,类似于你正在做的stdout。可能会有一个命令执行错误。 – gipsy

回答

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()