欢迎访问宙启技术站
智能推送

在Python中利用impacket.dcerpc.v5.transportSMBTransport()进行SMB连接

发布时间:2023-12-28 06:41:54

import os

from impacket.dcerpc.v5 import transport, svcctl, srvs, samr

from impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY, \

    RPC_C_AUTHN_LEVEL_PKT_INTEGRITY, RPC_C_AUTHN_LEVEL_PKT_AUTH_MQ, \

    RPC_C_AUTHN_LEVEL_PKT, RPC_C_AUTHN_LEVEL_NONE, RPC_C_AUTHN_LEVEL_CONNECT, \

    RPC_C_AUTHN_WINNT, DCERPCException, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, \

    RPC_C_AUTHN_LEVEL_PKT_INTEGRITY, RPC_C_AUTHN_LEVEL_PKT_AUTH_MQ, \

    RPC_C_AUTHN_LEVEL_PKT, RPC_C_AUTHN_LEVEL_NONE, RPC_C_AUTHN_LEVEL_CONNECT, \

    RPC_C_AUTHN_LEVEL_PKT_PRIVACY

from impacket.dcerpc.v5.epm import MSRPC_UUID_PORTMAP

from impacket.dcerpc.v5.dtypes import MAXIMUM_ALLOWED

# 设置目标主机和登录凭据

hostname = '127.0.0.1'

username = 'administrator'

password = 'password'

domain = ''

# 建立SMB连接

smb_transport = transport.SMBTransport(hostname, username=username, password=password, domain=domain)

# 尝试连接SMB

try:

    smb_transport.connect()

except Exception as e:

    print(f"[-] Failed to connect to {hostname}: {str(e)}")

    exit()

print(f"[+] Connected to {hostname} successfully")

# 获取SMB会话

smb_session = smb_transport.get_smb_session()

# 获取NetBIOS的名称

try:

    print(f"[+] NetBIOS name: {smb_session.getNetBIOSName()}")

except DCERPCException as e:

    print("[-] Failed to get NetBIOS name:", str(e))

# 枚举安装的服务

try:

    remote_svcctl = smb_session.get_service(svcctl.MSRPC_SERVICE)

    remote_svcctl.EnumServicesStatus(remote_svcctl.get_handle(), svcctl.SERVICE_TYPE_ALL, svcctl.SERVICE_STATE_ALL)

    status = remote_svcctl.get_response()

    for service in status:

        print(f"[+] Service: {service['lpDisplayName']}")

except DCERPCException as e:

    print("[-] Failed to enumerate services:", str(e))

# 枚举共享文件夹

try:

    remote_srvs = smb_session.get_service(srvs.MSRPC_SERVICE)

    remote_srvs.NetShareEnum(remote_srvs.get_handle(), 1, MAXIMUM_ALLOWED)

    shares = remote_srvs.get_response()

    for share in shares:

        print(f"[+] Share: {share['NetName']}")

except DCERPCException as e:

    print("[-] Failed to enumerate shares:", str(e))

# 枚举用户帐户

try:

    remote_samr = smb_session.get_service(samr.MSRPC_SERVICE)

    remote_samr.ConnectSamr()

    remote_samr.SamrEnumerateUsersInDomain(remote_samr.get_handle(), samr.USER_NORMAL_ACCOUNT, samr.MAXIMUM_ALLOWED)

    users = remote_samr.get_response()

    for user in users:

        print(f"[+] User: {user['Name']['Element']['Buffer']} ({user['RelativeId']})")

except DCERPCException as e:

    print("[-] Failed to enumerate users:", str(e))

# 关闭连接

smb_transport.disconnect()