带有 paramiko 的 Python CGI

标签 python cgi paramiko

我正在尝试编写一个 Python CGI 脚本,用户可以在其中输入名称(主机名)并从表单中选择内存,然后通过使用 paramiko 模块它将对给定节点执行 free -m 命令

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>'

它没有抛出错误,但同时也没有给出任何输出,不确定我做错了什么

最佳答案

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

关于带有 paramiko 的 Python CGI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42407353/

相关文章:

python - Paramiko:连接到 Cisco C2960 切换器时无法重新使用 ssh session

python - 为什么在加载模块时使用 Paramiko 会挂起?

python - django 查询返回错误 : expected str instance, 找到 ValuesListQuerySet

python - 使用正则表达式匹配字符串中的多个参数

python - 在 Linux 上使用 Python 读取 Excel 单元格注释?

python - 如何在 Python 3 CGI 中打印 unicode 字符?

python - 使用 gtk 对话框选择器小部件列出远程目标的文件

python - 替换重复的字符串,但在安装点

javascript - 将 html 页面中的 javascript 变量传递到 html 表单(在同一页面上)以提交给 perl cgi

java - CGI 和 Servlet 的执行方式有何不同?