2017-02-23 44 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()