Example #1
0
def handle_tcp_telnet(socket, dstport):
	socket = TextChannel(socket)

	try:
		socket.send("Linux-x86/2.4\nSamsung Smart TV\n\nlocalhost login: "******"Password: "******"\n\nSuccessfully logged in. Log in successful.\n")
		socket.send("Busybox v1.01 (2014.08.14-10:49+0000) Built-in shell (ash)\n")
		socket.send("Enter 'help' for a list of built-in commands.\n\n{}".format(ps1a))
		process_commandline(socket, readline(socket, True, 10).strip())

		interactive_shell(socket, ps1b, 10)
	except Exception as err:
		#print(traceback.format_exc())
		pass

	try:
		print("-- TELNET TRANSPORT CLOSED --")
		socket.close()
	except:
		pass
Example #2
0
    def from_socket(socket, headers_max_size=16384, body_max_size=16384):
        first_line = readline(socket)
        if not first_line:
            raise RequestNotReceived()

        request = Request.from_request_line(first_line)
        headers_size = 0
        while True:
            line = readline(socket)
            if not line.rstrip(b'\r\n'):
                break

            if not request.add_header_from_line(line):
                self.incomplete = True
                return request

            headers_size += len(line)
            if headers_size > headers_max_size:
                self.incomplete = True
                return request

        content_length = min(request.content_length, body_max_size)
        while content_length > 0:
            data = socket.recv(content_length)
            if not data:
                if content_length > 0:
                    self.incomplete = True
                break

            request.body.extend(data)
            content_length -= len(data)

        return request
Example #3
0
	def handle_tcp_httpproxy(origsocket, dstport):
		socket = TextChannel(origsocket)

		try:
			target = readline(socket).strip()
			rematch = re.match("CONNECT [^:]+(:[0-9]+)? ?.*", target)

			if not rematch:
				raise Exception('Unexpected request')

			port_num = int(rematch.groups(":80")[0][1:])

			# Skip headers
			while readline(socket).strip() != '':
				pass

			log_append('tcp_httpproxy_connections', target, *origsocket.getpeername())

			if port_num not in HTTP_CONNECT_FORBIDDEN_PORTS:
				socket.send("HTTP/1.0 200 Connection established\nProxy-agent: Netscape-Proxy/1.1\n\n")
			else:
				socket.send("HTTP/1.0 407 Proxy authentication required\nProxy-agent: Netscape-Proxy/1.1\n\n")
				port_num = None

		except Exception as err:
			#print(traceback.format_exc())
			port_num = None

		if port_num:
			print("Forwarding intruder to fake port {}/tcp".format(port_num))
			tcp_handler(origsocket, port_num)
		else:
			socket.close()
			print("-- HTTP TRANSPORT CLOSED --")
Example #4
0
def handle_tcp_telnet(socket, dstport):
    socket = TextChannel(socket)

    try:
        socket.send("Linux-x86/2.4\nSamsung Smart TV\n\nlocalhost login: "******"Password: "******"\n\nSuccessfully logged in. Log in successful.\n")
        socket.send(
            "Busybox v1.01 (2014.08.14-10:49+0000) Built-in shell (ash)\n")
        socket.send(
            "Enter 'help' for a list of built-in commands.\n\n{}".format(ps1a))
        process_commandline(socket, readline(socket, True, 10).strip())

        interactive_shell(socket, ps1b, 10)
    except Exception:
        print(traceback.format_exc())
        pass

    try:
        print("-- TELNET TRANSPORT CLOSED --")
        socket.close()
    except:
        pass
Example #5
0
def doFront(host_name,ssh_port,root_name,root_pwd,do_path,local_path,file_name):

    ###连接服务器
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh_client.connect(host_name,ssh_port,root_name,root_pwd)
    utils.output( host_name + '-服务器连接成功')

    #连接完成开始执行指令
    cmd = 'mkdir -p ' + do_path + ';'
    stdin,stdout,stderr=ssh_client.exec_command(cmd,get_pty=True)

    utils.readline(stdout)
    utils.output('远程主机ssh登录 创建newsee 目录 完成!')

    #进入文件目录
    cmd='cd ' + do_path + ';'
    stdin,stdout,stderr=ssh_client.exec_command(cmd,get_pty=True)
    utils.readline(stdout)

    #进入文件目录
    cmd='rm -rf  ' + file_name + ';'
    stdin,stdout,stderr=ssh_client.exec_command(cmd,get_pty=True)
    # utils.readline(stdout)
    utils.output('删除历史 tar 文件!')

    #传输文件
    remote_path=do_path + file_name
    utils.remoteftp(host_name,ssh_port,root_name,root_pwd,local_path,remote_path)

    #进入文件目录
    cmd='cd ' + do_path + ';ls;'
    stdin,stdout,stderr=ssh_client.exec_command(cmd,get_pty=True)
    utils.readline(stdout)
    utils.output('enter menu:' + cmd)

    #删除static 和 index.html文件或者文件夹 add by xiaosisi on 2017/11/06 === start
    cmd='rm -rf static;'
    stdin,stdout,stderr=ssh_client.exec_command(cmd,get_pty=True)
    utils.readline(stdout)
    utils.output('enter menu:' + cmd)
    cmd='rm -rf index.html;'
    stdin,stdout,stderr=ssh_client.exec_command(cmd,get_pty=True)
    utils.readline(stdout)
    utils.output('enter menu:' + cmd)
    #删除static 和 index.html文件或者文件夹 add by xiaosisi on 2017/11/06 === end

    #解压文件
    cmd='tar  -pzxvf  ' + do_path + file_name + ' -C ' + do_path + ';'
    utils.output('begin exec:' + cmd)
    stdin,stdout,stderr=ssh_client.exec_command(cmd,get_pty=True)
    # utils.readline(stdout)
    utils.output('文件解压完成!')
Example #6
0
def fetch(sock):
    extra_lines = flush(sock)
    sock.send("fetch\n")

    crc = 0

    lines = []
    l = readline(sock)
    if not l:
        return None

    if l != 'START\n':
        W("Bad expected START line '%s'\n" % l.rstrip('\n'))
        extra_lines.append(l)
        return encode_extra(extra_lines)
    crc = crc16(l, crc)

    while True:
        l = readline(sock)

        crc = crc16(l, crc)

        if l == 'END\n':
            break

        lines.append(l.rstrip('\n'))

    lines += encode_extra(extra_lines)

    for d in lines:
        L("Received: %s" % d)

    l = readline(sock)
    recv_crc = None
    try:
        k, v = l.rstrip('\n').split('=')
        if k == 'CRC':
            recv_crc = int(v)
        if recv_crc < 0 or recv_crc > 0xffff:
            recv_crc = None
    except ValueError:
        pass

    if recv_crc is None:
        W("Bad expected CRC line '%s'\n" % l.rstrip('\n'))
        return None

    if recv_crc != crc:
        W("Bad CRC: calculated 0x%x vs received 0x%x\n" % (crc, recv_crc))
        return None

    return lines
Example #7
0
def handle_tcp_http(socket, dstport):
    socket = TextChannel(socket)

    try:
        keep_alive = True
        while keep_alive:
            firstline = readline(socket).strip()
            rematch = re.match("([A-Z]+) ([^ ]+) ?.*", firstline)

            if not rematch:
                raise Exception('Unexpected request')

            verb = rematch.group(1)
            url = rematch.group(2)

            # Skip headers
            keep_alive = False
            user_agent = ''
            while True:
                header = readline(socket).strip()
                if header == '':
                    break
                elif header.upper() == 'CONNECTION: KEEP-ALIVE':
                    keep_alive = True
                elif header.upper().startswith('USER-AGENT: '):
                    user_agent = header[len('USER-AGENT: '):]

            session_token = uuid.uuid4().hex
            log_append('tcp_http_requests',
                       socket.getpeername()[0], dstport, verb, url, user_agent,
                       session_token)

            socket.send(
                "HTTP/1.0 200 OK\nServer: microhttpd (MontaVista/2.4, i386-uClibc)\nSet-Cookie: sessionToken={}; Expires={}\nContent-Type: text/html\nContent-Length: 38\nConnection: {}\n\nmicrohttpd on Linux 2.4, it works!\n\n"
                .format(session_token, __getexpdate(5 * 365 * 24 * 60 * 60),
                        "keep-alive" if keep_alive else "close"))
    except ssl.SSLError as err:
        print("SSL error: {}".format(err.reason))
        pass
    except Exception as err:
        #print(traceback.format_exc())
        pass

    try:
        print("-- HTTP TRANSPORT CLOSED --")
        socket.close()
    except:
        pass
Example #8
0
def turn_off(sock):
    if TESTING:
        return 99
    L("Sending btoff")
    flush(sock)
    sock.send("btoff\n")
    # read newline
    l = readline(sock)
    if not l:
        W("Bad response to btoff")
        return None

    if not l.startswith('next_wake'):
        W("Bad response to btoff '%s'" % l)
        return None
    L("Next wake line %s" % l)

    toks = dict(v.split('=') for v in l.split(','))

    rem = int(toks['rem'])
    tick_secs = int(toks['tick_secs'])
    tick_wake = int(toks['tick_wake']) + 1
    next_wake = int(toks['next_wake'])

    rem_secs = float(rem) / tick_wake * tick_secs

    next_wake_secs = next_wake - rem_secs
    L("next_wake_secs %f\n", next_wake_secs)
    return next_wake_secs
Example #9
0
def fetch(sock):
    print "fetch"
    sock.send("fetch\n")

    crc = 0

    lines = []
    l = readline(sock)
    if l != 'START\n':
        print >> sys.stderr, "Bad expected START line '%s'\n" % l.rstrip('\n')
        return None
    crc = crc16(l, crc)

    while True:
        l = readline(sock)

        crc = crc16(l, crc)

        if l == 'END\n':
            break

        lines.append(l.rstrip('\n'))

    print lines

    l = readline(sock)
    recv_crc = None
    try:
        k, v = l.rstrip('\n').split('=')
        print k, v
        if k == 'CRC':
            recv_crc = int(v)
        if recv_crc < 0 or recv_crc > 0xffff:
            recv_crc = None
    except ValueError:
        pass

    if recv_crc is None:
        print >> sys.stderr, "Bad expected CRC line '%s'\n" % l.rstrip('\n')
        return None

    if recv_crc != crc:
        print >> sys.stderr, "Bad CRC: calculated 0x%x vs received 0x%x\n" % (
            crc, recv_crc)
        return None

    return lines
Example #10
0
def receive_data(socket):
    buff = ''
    while True:
        line = readline(socket)
        if line.strip('\r\n') == '.':
            break
        buff += line
    return buff
Example #11
0
def clear_meas(sock):
    sock.send("clear\n")
    l = readline(sock)
    if l and l.rstrip() == 'cleared':
        return True

    print >> sys.stderr, "Bad response to clear %s\n" % str(l)
    return False
Example #12
0
def interactive_shell(socket, ps1, linetimeout=None):
	for i in range(8):
		socket.send(ps1)
		cmdline = readline(socket, True, linetimeout).strip()
		if cmdline == 'exit':
			break

		process_commandline(socket, cmdline)
Example #13
0
def clear_meas(sock):
    sock.send("clear\n");
    l = readline(sock)
    if l and l.rstrip() == 'cleared':
        return True

    print>>sys.stderr, "Bad response to clear %s\n" % str(l)
    return False
Example #14
0
def receive_data(socket):
	buff = ''
	while True:
		line = readline(socket)
		if line.strip('\r\n') == '.':
			break
		buff += line
	return buff
Example #15
0
def fetch(sock):
    print "fetch"
    sock.send("fetch\n")

    crc = 0

    lines = []
    l = readline(sock)
    if l != 'START\n':
        print>>sys.stderr, "Bad expected START line '%s'\n" % l.rstrip('\n')
        return None
    crc = crc16(l, crc)

    while True:
        l = readline(sock)

        crc = crc16(l, crc)

        if l == 'END\n':
            break

        lines.append(l.rstrip('\n'))

    print lines

    l = readline(sock)
    recv_crc = None
    try:
        k, v = l.rstrip('\n').split('=')
        print k,v
        if k == 'CRC':
            recv_crc = int(v)
        if recv_crc < 0 or recv_crc > 0xffff:
            recv_crc = None
    except ValueError:
        pass

    if recv_crc is None:
        print>>sys.stderr, "Bad expected CRC line '%s'\n" % l.rstrip('\n')
        return None

    if recv_crc != crc:
        print>>sys.stderr, "Bad CRC: calculated 0x%x vs received 0x%x\n" % (crc, recv_crc)
        return None

    return lines
Example #16
0
def clear_meas(sock):
    flush(sock)
    sock.send("clear\n")
    l = readline(sock)
    if l and l.rstrip() == 'cleared':
        return True

    E("Bad response to clear '%s'" % str(l))
    return False
Example #17
0
def flush(sock):
    ret = []
    while True:
        l = readline(sock)
        if l:
            ret.append(l)
        else:
            break
    return ret
Example #18
0
def handle_tcp_http(socket, dstport):
	socket = TextChannel(socket)

	try:
		keep_alive = True
		while keep_alive:
			firstline = readline(socket).strip()
			rematch = re.match("([A-Z]+) ([^ ]+) ?.*", firstline)

			if not rematch:
				raise Exception('Unexpected request')

			verb = rematch.group(1)
			url = rematch.group(2)

			# Skip headers
			keep_alive = False
			user_agent = ''
			while True:
				header = readline(socket).strip()
				if header == '':
					break
				elif header.upper() == 'CONNECTION: KEEP-ALIVE':
					keep_alive = True
				elif header.upper().startswith('USER-AGENT: '):
					user_agent = header[len('USER-AGENT: '):]

			session_token = uuid.uuid4().hex
			log_append('tcp_http_requests', socket.getpeername()[0], dstport, verb, url, user_agent, session_token)

			socket.send("HTTP/1.0 200 OK\nServer: microhttpd (MontaVista/2.4, i386-uClibc)\nSet-Cookie: sessionToken={}; Expires={}\nContent-Type: text/html\nContent-Length: 38\nConnection: {}\n\nmicrohttpd on Linux 2.4, it works!\n\n".format(session_token, __getexpdate(5 * 365 * 24 * 60 * 60), "keep-alive" if keep_alive else "close"))
	except ssl.SSLError as err:
		print("SSL error: {}".format(err.reason))
		pass
	except Exception as err:
		#print(traceback.format_exc())
		pass

	try:
		print("-- HTTP TRANSPORT CLOSED --")
		socket.close()
	except:
		pass
Example #19
0
def do_comms(sock):
    args = sys.argv[1:]
    print "do_comms"
    for a in args:
        sock.send('%s\n' % a)

    while True:
        l = readline(sock)
        if not l:
            print '.',
            sys.stdout.flush()
        else:
            print l
Example #20
0
def do_comms(sock):
    args = sys.argv[1:]
    print "do_comms"
    for a in args:
        sock.send('%s\n' % a)

    while True:
        l = readline(sock)
	if not l:
		print '.',
		sys.stdout.flush()
	else:
		print l
Example #21
0
    def handle_tcp_httpproxy(origsocket, dstport):
        socket = TextChannel(origsocket)

        try:
            target = readline(socket).strip()
            rematch = re.match("CONNECT [^:]+(:[0-9]+)? ?.*", target)

            if not rematch:
                raise Exception('Unexpected request')

            port_num = int(rematch.groups(":80")[0][1:])

            # Skip headers
            while readline(socket).strip() != '':
                pass

            log_append('tcp_httpproxy_connections', target,
                       *origsocket.getpeername())

            if port_num not in HTTP_CONNECT_FORBIDDEN_PORTS:
                socket.send(
                    "HTTP/1.0 200 Connection established\nProxy-agent: Netscape-Proxy/1.1\n\n"
                )
            else:
                socket.send(
                    "HTTP/1.0 407 Proxy authentication required\nProxy-agent: Netscape-Proxy/1.1\n\n"
                )
                port_num = None

        except Exception as err:
            #print(traceback.format_exc())
            port_num = None

        if port_num:
            print("Forwarding intruder to fake port {}/tcp".format(port_num))
            tcp_handler(origsocket, port_num)
        else:
            socket.close()
            print("-- HTTP TRANSPORT CLOSED --")
Example #22
0
def turn_off(sock):
    if TESTING:
        return 99
    print>>sys.stderr, "sending btoff"
    sock.send("btoff\n");
    # read newline
    l = readline(sock)
    if not l:
        print>>sys.stderr, "Bad response to btoff\n"
        return None

    if not l.startswith('off:'):
        print>>sys.stderr, "Bad response to btoff '%s'\n" % l
        return None
    off, next_wake = l.rstrip().split(':')
    print>>sys.stderr, "Next wake %s" % next_wake

    return int(next_wake)
Example #23
0
def turn_off(sock):
    if TESTING:
        return 99
    print >> sys.stderr, "sending btoff"
    sock.send("btoff\n")
    # read newline
    l = readline(sock)
    if not l:
        print >> sys.stderr, "Bad response to btoff\n"
        return None

    if not l.startswith('off:'):
        print >> sys.stderr, "Bad response to btoff '%s'\n" % l
        return None
    off, next_wake = l.rstrip().split(':')
    print >> sys.stderr, "Next wake %s" % next_wake

    return int(next_wake)
Example #24
0
def shell(reader, writer):
    command = None
    password = None

    writer.transport.set_write_buffer_limits(low=0, high=0)

    cmdreader = readline(reader, writer)
    cmdreader.send(None)

    s = SmdrSingleton()

    while True:
        if command:
            s.write(writer, s.eol)
        s.write(writer, '-')
        command = None
        while command is None:
            # TODO: use reader.readline()
            inp = yield from reader.read(1)
            if not inp:
                return
            command = cmdreader.send(inp)

        s.log_input(command)

        # Writing CR instead of EOL after command, because Panasonic
        # telnet interface is doing the same. It looks weird, but so life is
        s.write(writer, CR)

        if command == 'q':
            reply = 'Goodbye.' + s.eol
            s.write(writer, reply)
            break
        elif command == 'help':
            reply = 'q, smdr'
            s.write(writer, reply)
        elif command == 'smdr':
            reply = 'Enter Password:'******'(\n|\r)*$', '', line) + s.eol)
                    yield from writer.drain()
        elif command:
            s.write(writer, 'No such command.')
        else:
            s.write(writer, 'Goodbye' + s.eol)
            break
    writer.close()
Example #25
0
def handle_tcp_smtp(plaintext_socket, dstport):
	socket = TextChannel(plaintext_socket)
	tls_started = False
	ctr = 0.5

	msg_from = ''
	msg_to = []

	try:
		socket.send("220 localhost ESMTP server ready\n")

		while True:
			cmd = readline(socket)
			cmdupper = cmd.upper() if cmd else None
			time.sleep(ctr) # Rate limit
			ctr *= 1.1

			if not cmd or not cmd.endswith('\n'):
				raise Exception('Invalid request')
			elif cmdupper.startswith('HELO'):
				socket.send("250 localhost\n")
			elif cmdupper.startswith('EHLO'):
				socket.send("250-localhost offers TWO extensions:\n250-8BITMIME\n250 STARTTLS\n")
			elif cmdupper.startswith('STARTTLS'):
				if tls_started:
					socket.send("454 TLS not available due to temporary reason\n")
				else:
					tls_started = True
					socket.send("220 Go ahead\n")
					socket = TextChannel(switchtossl(plaintext_socket))
			elif cmdupper.startswith('QUIT'):
				socket.send("221 localhost ESMTP server closing connection\n")
				break
			elif cmdupper.startswith('NOOP'):
				socket.send("250 No-op Ok\n")
			elif cmdupper.startswith('RSET'):
				msg_from = ''
				msg_to = []
				socket.send("250 Reset Ok\n")
			elif cmdupper.startswith('DATA'):
				socket.send("354 Ok Send data ending with <CRLF>.<CRLF>\n")
				msg_contents = receive_data(socket)
				msg_id = uuid.uuid4().hex
				store_email(plaintext_socket.getpeername()[0], msg_id, msg_contents, msg_from, msg_to)
				socket.send("250 Message received: {}@localhost\n".format(msg_id))
			elif cmdupper.startswith('MAIL FROM:') or cmdupper.startswith('SEND FROM:') or cmdupper.startswith('SOML FROM:') or cmdupper.startswith('SAML FROM:'):
				msg_from = cmd[len('MAIL FROM:'):].strip()
				socket.send("250 Sender: {} Ok\n".format(msg_from))
			elif cmdupper.startswith('RCPT TO:'):
				recipient = cmd[len('RCPT TO:'):].strip()
				msg_to.append(recipient)
				socket.send("250 Recipient: {} Ok\n".format(recipient))
			else:
				socket.send("502 Command not implemented\n")
	except Exception as err:
		#print(traceback.format_exc())
		pass

	try:
		print("-- SMTP TRANSPORT CLOSED --")
		socket.close()
	except:
		pass
Example #26
0
def main(sock, dport, logger, config):
    ip = sock.getpeername()[0]

    helo_done = False
    starttls_done = False
    receiving_data = False

    mail_from = None
    rcpt_to = []
    data = []

    try:
        hostname = config.protocols.smtp.hostname.encode()
    except AttributeError:
        hostname = b'localhost'

    sock.send(b'220 %s ESMTP server ready\r\n' % hostname)

    while True:
        line = utils.readline(sock)
        if not line:
            break

        if not line.endswith(b'\r\n'):
            if len(line) == 2048:
                sock.send(b'500 Line too long\r\n')
                if receiving_data:
                    receiving_data = False
            elif not receiving_data:
                sock.send(b'500 Command unrecognized\r\n')
            continue

        if receiving_data:
            if line == b'.\r\n':
                receiving_data = False
                logger.log(ip=ip,
                           dport=dport,
                           mail_from=mail_from,
                           rcpt_to=rcpt_to,
                           data=data)

                mail_from = None
                rcpt_to.clear()
                data.clear()
                sock.send(b'250 Message accepted\r\n')

            if line[0] == b'.':
                line = line[1:]

            data.append(line.decode())
            continue

        command = parse_command(line)

        if command[0] == b'HELO':
            if len(command) == 1:
                sock.send(b'501 Domain name required\r\n')
                continue

            helo_done = True
            sock.send(b'250 %s at your service\r\n' % hostname)

        elif command[0] == b'EHLO':
            if len(command) == 1:
                sock.send(b'501 Domain name required\r\n')
                continue

            helo_done = True
            sock.send(b'250-%s at your service\r\n' % hostname)
            sock.send(b'250-SMTPUTF8\r\n')
            sock.send(b'250-8BITMIME\r\n')
            sock.send(b'250 STARTTLS\r\n')

        elif command[0] == b'HELP':
            sock.send(b'214 Refer https://tools.ietf.org/html/rfc5321\r\n')

        elif command[0] == b'QUIT':
            sock.send(b'221 Closing connection\r\n')
            break

        elif command[0] == b'NOOP':
            sock.send(b'250 NOOP OK\r\n')

        elif command[0] == b'RSET':
            mail_from = None
            rcpt_to.clear()
            data.clear()
            sock.send(b'250 RSET OK\r\n')

        elif command[0] == b'MAIL':
            if not helo_done:
                sock.send(b'503 Must issue HELO/EHLO first\r\n')
                continue

            if len(command) == 1 or not (command[1].startswith(b'FROM:<')
                                         and command[1].endswith(b'>')):
                sock.send(b'501 Syntax error\r\n')
                continue

            mail_from = command[1][6:-1].decode()
            sock.send(b'250 Sender OK\r\n')

        elif command[0] == b'RCPT':
            if not helo_done:
                sock.send(b'503 Must issue HELO/EHLO first\r\n')
                continue

            if len(command) == 1 or not (command[1].startswith(b'TO:<')
                                         and command[1].endswith(b'>')):
                sock.send(b'501 Syntax error\r\n')
                continue

            rcpt_to.append(command[1][4:-1].decode())
            sock.send(b'250 Recipient OK\r\n')

        elif command[0] == b'DATA':
            if not (mail_from and rcpt_to):
                sock.send(b'250 Sender/recipient not specified\r\n')
                continue

            receiving_data = True
            sock.send(b'354 Start mail input\r\n')

        elif command[0] == b'VRFY':
            sock.send(b'252 Cannot VRFY user but will attempt delivery\r\n')

        elif command[0] == b'STARTTLS':
            if starttls_done:
                sock.send(b'454 TLS not available due to temporary reason\r\n')
                continue

            starttls_done = True
            helo_done = False
            mail_from = None
            rcpt_to.clear()
            data.clear()

            sock.send(b'220 Ready to start TLS\r\n')
            sock = ssl.wrap_socket(sock, config.tls.keyfile,
                                   config.tls.certfile, True)

        else:
            sock.send(b'502 Command not implemented\r\n')
Example #27
0
def do(host_name,ssh_port,root_name,root_pwd,do_path,log_path,local_path,file_name,is_install_docker,daemon_file,is_init,open_port):

    ###连接服务器
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh_client.connect(host_name,ssh_port,root_name,root_pwd)
    utils.output( host_name + '-服务器连接成功')

    #连接完成开始执行指令
    cmd = 'mkdir -p ' + do_path + ';'
    stdin,stdout,stderr=ssh_client.exec_command(cmd,get_pty=True)
    utils.output('远程主机ssh登录 创建newsee 数据目录 完成!' + do_path)
    time.sleep(2)
    #创建日志目录
    cmd = 'mkdir -p ' + log_path + ';'
    stdin,stdout,stderr=ssh_client.exec_command(cmd,get_pty=True)
    utils.output('远程主机ssh登录 创建newsee 日志目录 完成!')
    time.sleep(2)
    #设置日志目录访问权限
    cmd = 'chmod -R 777 ' + log_path + ';'
    stdin,stdout,stderr=ssh_client.exec_command(cmd,get_pty=True)
    utils.output('远程主机ssh登录 设置newsee 日志目录权限 完成!')
    time.sleep(2)
    utils.readline(stdout)
    utils.output('远程主机ssh登录 创建newsee 目录 完成!')

    #传输文件
    remote_path=do_path + file_name
    utils.remoteftp(host_name,ssh_port,root_name,root_pwd,local_path,remote_path)

    #进入文件目录
    cmd='cd ' + do_path + ';'
    stdin,stdout,stderr=ssh_client.exec_command(cmd,get_pty=True)
    utils.readline(stdout)

    if is_install_docker > 0:
        #SET UP THE REPOSITORY
        cmd='yum install -y yum-utils device-mapper-persistent-data lvm2; \
            yum-config-manager  --add-repo  https://download.docker.com/linux/centos/docker-ce.repo;  \
            yum-config-manager --enable docker-ce-edge;'
        stdin,stdout,stderr=ssh_client.exec_command(cmd,get_pty=True)
        utils.readline(stdout)
        utils.output('Docker 安装预设置完成')
        #开始安装docker
        cmd='yum makecache fast; \
            yum install docker-ce -y;'
        stdin,stdout,stderr=ssh_client.exec_command(cmd,get_pty=True)
        utils.readline(stdout)

        utils.output('Docker 安装完成')
        #设置docker镜像加速
        if daemon_file != '':
            #启用docker
            utils.remoteftp(host_name,ssh_port,root_name,root_pwd,daemon_file,'/etc/docker/daemon.json')
            utils.output('Docker 镜像加速设置完成')
    if is_init > 0:
        #启用docker
        cmd='systemctl start docker;'
        stdin,stdout,stderr=ssh_client.exec_command(cmd,get_pty=True)
        utils.readline(stdout)
        utils.output('启用docker 完成!')

        #设置开机启用docker
        cmd='systemctl enable docker;'
        stdin,stdout,stderr=ssh_client.exec_command(cmd,get_pty=True)
        utils.readline(stdout)
        utils.output('设置开机启用docker 完成!')

    #docker 删除现有容器
    cmd='docker rm -f  ' + file_name
    stdin,stdout,stderr=ssh_client.exec_command(cmd,get_pty=True)
    utils.readline(stdout)
    utils.output('docker容器 删除完成!')

    time.sleep(2)

    cmd= 'cd ' + do_path + ';' + 'ls;'
    utils.output(cmd)
    stdin,stdout,stderr=ssh_client.exec_command(cmd,get_pty=True)
    utils.readline(stdout)

    #docker 运行容器
    cmd='sudo docker run -d  --net=host -v ' + do_path + ':/app  -v ' + log_path + ':/logs    --name ' + file_name + '  -v /etc/localtime:/etc/localtime  --restart=always  java:8 java  -jar /app/' + file_name + ';'
    #cmd='sudo docker run -d  --net=host -v $PWD:/app --name ' + file_name + '  -v /etc/localtime:/etc/localtime  --restart=always  java:8 java -jar /app/' + file_name + ';'

    #cmd='docker run -d  --net=host -v $PWD:/app --name ' + file_name + '  java:8 java -jar /app/' + file_name + ';'
    utils.output(cmd)
    stdin,stdout,stderr=ssh_client.exec_command(cmd,get_pty=True)
    utils.readline(stdout)
    utils.output('docker容器 设置运行 完成!')

    #查看docker 运行状态
    cmd='docker ps ;'
    stdin,stdout,stderr=ssh_client.exec_command(cmd,get_pty=True)
    utils.readline(stdout)

    if open_port > 0:
        #启用docker
        cmd='firewall-cmd --zone=public --add-port=' + str(open_port) + '/tcp --permanent;firewall-cmd --reload;'
        stdin,stdout,stderr=ssh_client.exec_command(cmd,get_pty=True)
        utils.readline(stdout)
        utils.output('防火墙端口设置 完成!')
Example #28
0
def handle_tcp_http(socket, dsthost, dstport, persona):
    # load body
    index_file = persona.get('index')
    if (os.path.exists(index_file) and os.path.isfile(index_file)):
        with open(index_file) as body_file:
            body = body_file.read()
    else:
        body = "<h1>It's Alive!</h1>"

    socket = TextChannel(socket)
    try:
        keep_alive = True
        while keep_alive:
            firstline = readline(socket).strip()
            if firstline == "":
                continue
            rematch = re.match("([A-Z]+) ([^ ]+) ?.*", firstline)
            if not rematch:
                raise Exception('Unexpected request: "{}"'.format(firstline))

            verb = rematch.group(1)
            url = rematch.group(2)

            # Skip headers
            keep_alive = False
            user_agent = ''
            while True:
                header = readline(socket).strip()
                if header == '':
                    break
                elif header.upper() == 'CONNECTION: KEEP-ALIVE':
                    keep_alive = True
                elif header.upper().startswith('USER-AGENT: '):
                    user_agent = header[len('USER-AGENT: '):]

            session_token = uuid.uuid4().hex
            log_append('tcp_http_requests',
                       socket.getpeername()[0], dstport, verb, url, user_agent,
                       session_token)

            #HEADERS['Server'] = persona.get('headers').get('Server')
            HEADERS.update(persona.get('headers'))
            HEADERS['Set-Cookie'] = 'sessionToken={}; Expires={}'.format(
                session_token, __getexpdate(5 * 365 * 24 * 60 * 60))
            HEADERS['Connection'] = "keep-alive" if keep_alive else "close"
            HEADERS['Content-Length'] = str(len(body))

            header = 'HTTP/1.1 200 OK\n'
            for header_title in HEADERS:
                header += header_title + ': ' + HEADERS[header_title] + '\n'

            socket.send(header + '\n' + body)

    except ssl.SSLError as err:
        print("SSL error: {}".format(err.reason))
        pass
    except ConnectionResetError:
        print("Connection reset by peer")
        pass
    except Exception:
        print(traceback.format_exc())
        pass

    try:
        socket.close
    except:
        pass
Example #29
0
def handle_tcp_smtp(plaintext_socket, dstport):
    socket = TextChannel(plaintext_socket)
    tls_started = False
    ctr = 0.5

    msg_from = ''
    msg_to = []

    try:
        socket.send("220 localhost ESMTP server ready\n")

        while True:
            cmd = readline(socket)
            cmdupper = cmd.upper() if cmd else None
            time.sleep(ctr)  # Rate limit
            ctr *= 1.1

            if not cmd or not cmd.endswith('\n'):
                raise Exception('Invalid request')
            elif cmdupper.startswith('HELO'):
                socket.send("250 localhost\n")
            elif cmdupper.startswith('EHLO'):
                socket.send(
                    "250-localhost offers TWO extensions:\n250-8BITMIME\n250 STARTTLS\n"
                )
            elif cmdupper.startswith('STARTTLS'):
                if tls_started:
                    socket.send(
                        "454 TLS not available due to temporary reason\n")
                else:
                    tls_started = True
                    socket.send("220 Go ahead\n")
                    socket = TextChannel(switchtossl(plaintext_socket))
            elif cmdupper.startswith('QUIT'):
                socket.send("221 localhost ESMTP server closing connection\n")
                break
            elif cmdupper.startswith('NOOP'):
                socket.send("250 No-op Ok\n")
            elif cmdupper.startswith('RSET'):
                msg_from = ''
                msg_to = []
                socket.send("250 Reset Ok\n")
            elif cmdupper.startswith('DATA'):
                socket.send("354 Ok Send data ending with <CRLF>.<CRLF>\n")
                msg_contents = receive_data(socket)
                msg_id = uuid.uuid4().hex
                store_email(plaintext_socket.getpeername()[0], msg_id,
                            msg_contents, msg_from, msg_to)
                socket.send(
                    "250 Message received: {}@localhost\n".format(msg_id))
            elif cmdupper.startswith('MAIL FROM:') or cmdupper.startswith(
                    'SEND FROM:') or cmdupper.startswith(
                        'SOML FROM:') or cmdupper.startswith('SAML FROM:'):
                msg_from = cmd[len('MAIL FROM:'):].strip()
                socket.send("250 Sender: {} Ok\n".format(msg_from))
            elif cmdupper.startswith('RCPT TO:'):
                recipient = cmd[len('RCPT TO:'):].strip()
                msg_to.append(recipient)
                socket.send("250 Recipient: {} Ok\n".format(recipient))
            else:
                socket.send("502 Command not implemented\n")
    except Exception as err:
        #print(traceback.format_exc())
        pass

    try:
        print("-- SMTP TRANSPORT CLOSED --")
        socket.close()
    except:
        pass